aboutsummaryrefslogtreecommitdiff
path: root/packages
diff options
context:
space:
mode:
Diffstat (limited to 'packages')
-rw-r--r--packages/Python/lldbsuite/__init__.py28
-rw-r--r--packages/Python/lldbsuite/support/__init__.py0
-rw-r--r--packages/Python/lldbsuite/support/fs.py64
-rw-r--r--packages/Python/lldbsuite/support/seven.py20
-rw-r--r--packages/Python/lldbsuite/support/sockutil.py23
-rw-r--r--packages/Python/lldbsuite/test/.categories0
-rw-r--r--packages/Python/lldbsuite/test/Makefile33
-rw-r--r--packages/Python/lldbsuite/test/README-TestSuite159
-rw-r--r--packages/Python/lldbsuite/test/__init__.py7
-rw-r--r--packages/Python/lldbsuite/test/android/platform/Makefile4
-rw-r--r--packages/Python/lldbsuite/test/android/platform/TestDefaultCacheLineSize.py38
-rw-r--r--packages/Python/lldbsuite/test/android/platform/main.cpp13
-rw-r--r--packages/Python/lldbsuite/test/api/check_public_api_headers/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/api/check_public_api_headers/TestPublicAPIHeaders.py88
-rw-r--r--packages/Python/lldbsuite/test/api/check_public_api_headers/main.cpp.template24
-rw-r--r--packages/Python/lldbsuite/test/api/multiple-debuggers/.categories1
-rw-r--r--packages/Python/lldbsuite/test/api/multiple-debuggers/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/api/multiple-debuggers/TestMultipleDebuggers.py44
-rw-r--r--packages/Python/lldbsuite/test/api/multiple-debuggers/multi-process-driver.cpp283
-rw-r--r--packages/Python/lldbsuite/test/api/multiple-debuggers/testprog.cpp12
-rw-r--r--packages/Python/lldbsuite/test/api/multithreaded/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/api/multithreaded/TestMultithreaded.py91
-rw-r--r--packages/Python/lldbsuite/test/api/multithreaded/common.h68
-rw-r--r--packages/Python/lldbsuite/test/api/multithreaded/driver.cpp38
-rw-r--r--packages/Python/lldbsuite/test/api/multithreaded/inferior.cpp17
-rw-r--r--packages/Python/lldbsuite/test/api/multithreaded/listener_test.cpp74
-rw-r--r--packages/Python/lldbsuite/test/api/multithreaded/lldb-headers.h11
-rw-r--r--packages/Python/lldbsuite/test/api/multithreaded/test_breakpoint_callback.cpp49
-rw-r--r--packages/Python/lldbsuite/test/api/multithreaded/test_listener_event_description.cpp97
-rw-r--r--packages/Python/lldbsuite/test/api/multithreaded/test_listener_event_process_state.cpp68
-rw-r--r--packages/Python/lldbsuite/test/api/multithreaded/test_listener_resume.cpp53
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/TestEmulations.py54
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-1-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-1-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-10-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-11-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-12-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-2-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-2-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-3-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-3-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-4-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-4-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-5-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-5-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-6-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-6-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-7-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-7-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-8-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-8-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-9-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-bic-1-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-bic-1-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-1-arm.dat119
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-1-thumb.dat119
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-2-arm.dat123
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-2-thumb.dat123
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-3-arm.dat119
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-3-thumb.dat119
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-1-arm.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-1-thumb.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-10-thumb.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-11-thumb.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-12-thumb.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-2-arm.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-2-thumb.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-3-arm.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-3-thumb.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-4-arm.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-4-thumb.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-5-arm.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-5-thumb.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-6-arm.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-6-thumb.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-7-arm.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-7-thumb.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-8-arm.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-8-thumb.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-9-thumb.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrd-1-arm.dat119
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrd-1-thumb.dat119
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrd-2-thumb.dat119
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrh-1-thumb.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrsh-1-arm.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrsh-2-arm.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-1-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-1-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-10-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-11-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-12-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-13-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-14-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-15-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-16-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-17-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-18-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-19-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-2-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-2-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-20-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-21-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-22-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-23-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-24-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-25-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-26-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-27-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-28-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-29-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-3-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-3-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-30-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-31-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-4-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-4-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-5-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-5-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-6-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-6-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-7-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-8-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-9-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-moveq-1-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-movs-1-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-1-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-1-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-2-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-2-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-3-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-3-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-4-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-4-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-pop-1-arm.dat121
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-pop-1-thumb.dat121
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-pop-2-arm.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-pop-2-thumb.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-pop-3-thumb.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-1-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-1-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-2-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-2-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-3-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-3-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-1-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-1-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-2-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-2-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-3-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-3-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-4-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-4-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-5-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-strb-1-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-strb-2-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-strbt-1-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-strd-1-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-strt-1-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-1-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-1-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-10-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-2-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-2-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-3-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-3-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-4-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-4-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-5-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-5-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-6-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-6-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-8-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-9-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-1-arm.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-1-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-10-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-2-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-3-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-4-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-5-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-6-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-8-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-9-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpop-1-thumb.dat125
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpop-2-thumb.dat118
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpop-3-thumb.dat121
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpush-1-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpush-2-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpush-3-thumb.dat111
-rw-r--r--packages/Python/lldbsuite/test/attic/dotest.pl44
-rw-r--r--packages/Python/lldbsuite/test/attic/tester.py115
-rw-r--r--packages/Python/lldbsuite/test/bench-history206
-rw-r--r--packages/Python/lldbsuite/test/bench.py74
-rw-r--r--packages/Python/lldbsuite/test/benchmarks/continue/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/benchmarks/continue/TestBenchmarkContinue.py66
-rw-r--r--packages/Python/lldbsuite/test/benchmarks/continue/main.cpp36
-rw-r--r--packages/Python/lldbsuite/test/benchmarks/disassembly/TestDisassembly.py155
-rw-r--r--packages/Python/lldbsuite/test/benchmarks/disassembly/TestDoAttachThenDisassembly.py67
-rw-r--r--packages/Python/lldbsuite/test/benchmarks/disassembly/TestXcode41Vs42GDBDisassembly.py94
-rw-r--r--packages/Python/lldbsuite/test/benchmarks/expression/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/benchmarks/expression/TestExpressionCmd.py72
-rw-r--r--packages/Python/lldbsuite/test/benchmarks/expression/TestRepeatedExprs.py130
-rw-r--r--packages/Python/lldbsuite/test/benchmarks/expression/main.cpp51
-rw-r--r--packages/Python/lldbsuite/test/benchmarks/frame_variable/TestFrameVariableResponse.py70
-rw-r--r--packages/Python/lldbsuite/test/benchmarks/libcxxlist/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/benchmarks/libcxxlist/TestBenchmarkLibcxxList.py59
-rw-r--r--packages/Python/lldbsuite/test/benchmarks/libcxxlist/main.cpp11
-rw-r--r--packages/Python/lldbsuite/test/benchmarks/libcxxmap/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/benchmarks/libcxxmap/TestBenchmarkLibcxxMap.py59
-rw-r--r--packages/Python/lldbsuite/test/benchmarks/libcxxmap/main.cpp11
-rw-r--r--packages/Python/lldbsuite/test/benchmarks/startup/TestStartupDelays.py80
-rw-r--r--packages/Python/lldbsuite/test/benchmarks/stepping/TestSteppingSpeed.py67
-rw-r--r--packages/Python/lldbsuite/test/benchmarks/turnaround/TestCompileRunToBreakpointTurnaround.py119
-rw-r--r--packages/Python/lldbsuite/test/configuration.py161
-rw-r--r--packages/Python/lldbsuite/test/crashinfo.c64
-rw-r--r--packages/Python/lldbsuite/test/curses_results.py224
-rw-r--r--packages/Python/lldbsuite/test/dosep.py1680
-rw-r--r--packages/Python/lldbsuite/test/dotest.py1128
-rw-r--r--packages/Python/lldbsuite/test/dotest_args.py188
-rw-r--r--packages/Python/lldbsuite/test/dotest_channels.py200
-rw-r--r--packages/Python/lldbsuite/test/driver/batch_mode/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/driver/batch_mode/TestBatchMode.py89
-rw-r--r--packages/Python/lldbsuite/test/driver/batch_mode/main.c15
-rw-r--r--packages/Python/lldbsuite/test/example/TestSequenceFunctions.py36
-rw-r--r--packages/Python/lldbsuite/test/expression_command/.categories1
-rw-r--r--packages/Python/lldbsuite/test/expression_command/call-function/Makefile15
-rw-r--r--packages/Python/lldbsuite/test/expression_command/call-function/TestCallStdStringFunction.py43
-rw-r--r--packages/Python/lldbsuite/test/expression_command/call-function/TestCallStopAndContinue.py46
-rw-r--r--packages/Python/lldbsuite/test/expression_command/call-function/TestCallUserDefinedFunction.py52
-rw-r--r--packages/Python/lldbsuite/test/expression_command/call-function/main.cpp53
-rw-r--r--packages/Python/lldbsuite/test/expression_command/call-restarts/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/expression_command/call-restarts/TestCallThatRestarts.py139
-rw-r--r--packages/Python/lldbsuite/test/expression_command/call-restarts/lotta-signals.c61
-rw-r--r--packages/Python/lldbsuite/test/expression_command/call-throws/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/expression_command/call-throws/TestCallThatThrows.py112
-rw-r--r--packages/Python/lldbsuite/test/expression_command/call-throws/call-throws.m47
-rw-r--r--packages/Python/lldbsuite/test/expression_command/char/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/expression_command/char/TestExprsChar.py69
-rw-r--r--packages/Python/lldbsuite/test/expression_command/char/main.cpp10
-rw-r--r--packages/Python/lldbsuite/test/expression_command/expr-in-syscall/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/expression_command/expr-in-syscall/TestExpressionInSyscall.py82
-rw-r--r--packages/Python/lldbsuite/test/expression_command/expr-in-syscall/main.cpp12
-rw-r--r--packages/Python/lldbsuite/test/expression_command/formatters/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/expression_command/formatters/TestFormatters.py167
-rw-r--r--packages/Python/lldbsuite/test/expression_command/formatters/foosynth.py29
-rw-r--r--packages/Python/lldbsuite/test/expression_command/formatters/formatters.py17
-rw-r--r--packages/Python/lldbsuite/test/expression_command/formatters/main.cpp48
-rw-r--r--packages/Python/lldbsuite/test/expression_command/issue_11588/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/expression_command/issue_11588/Test11588.py77
-rw-r--r--packages/Python/lldbsuite/test/expression_command/issue_11588/main.cpp54
-rw-r--r--packages/Python/lldbsuite/test/expression_command/issue_11588/s11588.py26
-rw-r--r--packages/Python/lldbsuite/test/expression_command/macros/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/expression_command/macros/TestMacros.py106
-rw-r--r--packages/Python/lldbsuite/test/expression_command/macros/macro1.h17
-rw-r--r--packages/Python/lldbsuite/test/expression_command/macros/macro2.h8
-rw-r--r--packages/Python/lldbsuite/test/expression_command/macros/main.cpp15
-rw-r--r--packages/Python/lldbsuite/test/expression_command/options/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/expression_command/options/TestExprOptions.py76
-rw-r--r--packages/Python/lldbsuite/test/expression_command/options/foo.cpp11
-rw-r--r--packages/Python/lldbsuite/test/expression_command/options/main.cpp15
-rw-r--r--packages/Python/lldbsuite/test/expression_command/persist_objc_pointeetype/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/expression_command/persist_objc_pointeetype/TestPersistObjCPointeeType.py50
-rw-r--r--packages/Python/lldbsuite/test/expression_command/persist_objc_pointeetype/main.m80
-rw-r--r--packages/Python/lldbsuite/test/expression_command/persistent_ptr_update/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/expression_command/persistent_ptr_update/TestPersistentPtrUpdate.py41
-rw-r--r--packages/Python/lldbsuite/test/expression_command/persistent_ptr_update/main.c11
-rw-r--r--packages/Python/lldbsuite/test/expression_command/persistent_types/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/expression_command/persistent_types/TestNestedPersistentTypes.py41
-rw-r--r--packages/Python/lldbsuite/test/expression_command/persistent_types/TestPersistentTypes.py57
-rw-r--r--packages/Python/lldbsuite/test/expression_command/persistent_types/main.c14
-rw-r--r--packages/Python/lldbsuite/test/expression_command/persistent_variables/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/expression_command/persistent_variables/TestPersistentVariables.py54
-rw-r--r--packages/Python/lldbsuite/test/expression_command/persistent_variables/main.c14
-rw-r--r--packages/Python/lldbsuite/test/expression_command/po_verbosity/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/expression_command/po_verbosity/TestPoVerbosity.py61
-rw-r--r--packages/Python/lldbsuite/test/expression_command/po_verbosity/main.m9
-rw-r--r--packages/Python/lldbsuite/test/expression_command/radar_8638051/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/expression_command/radar_8638051/Test8638051.py39
-rw-r--r--packages/Python/lldbsuite/test/expression_command/radar_8638051/main.c54
-rw-r--r--packages/Python/lldbsuite/test/expression_command/radar_9531204/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/expression_command/radar_9531204/TestPrintfAfterUp.py42
-rw-r--r--packages/Python/lldbsuite/test/expression_command/radar_9531204/main.c25
-rw-r--r--packages/Python/lldbsuite/test/expression_command/radar_9673664/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/expression_command/radar_9673664/TestExprHelpExamples.py41
-rw-r--r--packages/Python/lldbsuite/test/expression_command/radar_9673664/main.c16
-rw-r--r--packages/Python/lldbsuite/test/expression_command/test/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/expression_command/test/TestExprs.py248
-rw-r--r--packages/Python/lldbsuite/test/expression_command/test/TestExprs2.py60
-rw-r--r--packages/Python/lldbsuite/test/expression_command/test/main.cpp44
-rw-r--r--packages/Python/lldbsuite/test/expression_command/timeout/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/expression_command/timeout/TestCallWithTimeout.py92
-rw-r--r--packages/Python/lldbsuite/test/expression_command/timeout/wait-a-while.cpp35
-rw-r--r--packages/Python/lldbsuite/test/expression_command/two-files/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/expression_command/two-files/TestObjCTypeQueryFromOtherCompileUnit.py39
-rw-r--r--packages/Python/lldbsuite/test/expression_command/two-files/foo.m28
-rw-r--r--packages/Python/lldbsuite/test/expression_command/two-files/main.m22
-rw-r--r--packages/Python/lldbsuite/test/functionalities/abbreviation/.categories1
-rw-r--r--packages/Python/lldbsuite/test/functionalities/abbreviation/TestAbbreviations.py101
-rw-r--r--packages/Python/lldbsuite/test/functionalities/abbreviation/TestCommonShortSpellings.py39
-rw-r--r--packages/Python/lldbsuite/test/functionalities/alias/.categories1
-rw-r--r--packages/Python/lldbsuite/test/functionalities/archives/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/archives/README62
-rw-r--r--packages/Python/lldbsuite/test/functionalities/archives/TestBSDArchives.py57
-rw-r--r--packages/Python/lldbsuite/test/functionalities/archives/a.c19
-rw-r--r--packages/Python/lldbsuite/test/functionalities/archives/b.c19
-rw-r--r--packages/Python/lldbsuite/test/functionalities/archives/main.c17
-rw-r--r--packages/Python/lldbsuite/test/functionalities/asan/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/asan/TestMemoryHistory.py103
-rw-r--r--packages/Python/lldbsuite/test/functionalities/asan/TestReportData.py79
-rw-r--r--packages/Python/lldbsuite/test/functionalities/asan/main.c34
-rw-r--r--packages/Python/lldbsuite/test/functionalities/attach_resume/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/attach_resume/TestAttachResume.py73
-rw-r--r--packages/Python/lldbsuite/test/functionalities/attach_resume/main.cpp50
-rw-r--r--packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/TestFdLeak.py78
-rw-r--r--packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/main.c28
-rw-r--r--packages/Python/lldbsuite/test/functionalities/backticks/.categories1
-rw-r--r--packages/Python/lldbsuite/test/functionalities/backticks/TestBackticksWithoutATarget.py21
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/TestAddressBreakpoints.py91
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/main.c8
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py206
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommandsFromPython.py95
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestRegexpBreakCommand.py51
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/a.c9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/b.c9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/bktptcmd.py6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/main.c13
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/TestBreakpointConditions.py181
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/main.c54
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/TestBreakpointIDs.py51
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/main.cpp65
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/TestBreakpointIgnoreCount.py136
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/main.c54
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/TestBreakpointLanguage.py85
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/a.c5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/b.cpp5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/main.cpp11
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/TestBreakpointLocations.py88
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/main.c43
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/TestBreakpointOptions.py93
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/foo.cpp12
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/main.cpp8
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/TestCompDirSymLink.py63
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/main.cpp13
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoins/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoins/TestConsecutiveBreakpoints.py59
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoins/main.cpp19
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/TestCPPBreakpointLocations.py62
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/main.cpp77
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/TestCPPExceptionBreakpoint.py48
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/main.cpp13
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/TestBreakpointsWithNoTargets.py67
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/main.c11
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/TestInlinedBreakpoints.py57
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/basic_type.cpp178
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/int.cpp9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/objc/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/objc/TestObjCBreakpoints.py94
-rw-r--r--packages/Python/lldbsuite/test/functionalities/breakpoint/objc/main.m98
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_history/.categories1
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_history/TestCommandHistory.py68
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_regex/.categories1
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_regex/TestCommandRegex.py56
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/.categories1
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/TestCommandScript.py142
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/bug11569.py7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/import/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/import/TestImport.py73
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/import/bar/bar.py12
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/import/bar/barutil.py2
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/import/dummymodule.py2
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/import/foo/bar/foobar.py5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/import/foo/foo.py5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/import/foo/foo2.py9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/import/main.c15
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/Makefile3
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/TestRdar12586188.py31
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/fail12586188.py4
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/fail212586188.py4
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/TPunitA.py6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/TPunitB.py6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/__init__.py6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/main.cpp70
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/mysto.py23
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/py_import12
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_script/welcome.py46
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_source/.categories1
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_source/.lldb1
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_source/TestCommandSource.py36
-rw-r--r--packages/Python/lldbsuite/test/functionalities/command_source/my.py6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/completion/.categories1
-rw-r--r--packages/Python/lldbsuite/test/functionalities/completion/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/completion/TestCompletion.py324
-rw-r--r--packages/Python/lldbsuite/test/functionalities/completion/main.cpp14
-rw-r--r--packages/Python/lldbsuite/test/functionalities/conditional_break/.lldb3
-rw-r--r--packages/Python/lldbsuite/test/functionalities/conditional_break/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/conditional_break/TestConditionalBreak.py133
-rw-r--r--packages/Python/lldbsuite/test/functionalities/conditional_break/conditional_break.py30
-rw-r--r--packages/Python/lldbsuite/test/functionalities/conditional_break/main.c54
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/.categories1
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/TestFormattersBoolRefPtr.py72
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/main.mm29
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/TestCompactVectors.py58
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/main.cpp26
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/TestDataFormatterAdv.py285
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/main.cpp174
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/TestDataFormatterCategories.py329
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/main.cpp46
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py265
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/main.cpp121
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/TestDataFormatterDisabling.py80
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/main.cpp18
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/TestDataFormatterEnumFormat.py65
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/main.cpp13
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/TestDataFormatterGlobals.py67
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/main.cpp27
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/TestDataFormatterNamedSummaries.py122
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/main.cpp59
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/.categories1
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjC.py464
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/main.m694
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/TestDataFormatterNSString.py107
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/main.m99
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/TestFormattersOneIsSingular.py90
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/main.m42
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/TestPtrToArrayFormatting.py57
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/main.cpp17
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py252
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/fooSynthProvider.py23
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/ftsp.py32
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/main.cpp66
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/TestDataFormatterScript.py170
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/main.cpp53
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/Makefile19
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/TestDataFormatterSkipSummary.py175
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/main.cpp57
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/TestDataFormatterSmartArray.py348
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/main.cpp65
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/Makefile4
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/TestInitializerList.py40
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/main.cpp21
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/TestDataFormatterLibccIterator.py66
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/main.cpp42
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/TestDataFormatterLibcxxList.py186
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/TestDataFormatterLibcxxListLoop.py54
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/main.cpp30
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/main.cpp43
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/TestDataFormatterLibccMap.py298
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/main.cpp77
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/TestDataFormatterLibccMultiMap.py298
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/main.cpp77
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/TestDataFormatterLibcxxMultiSet.py69
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/main.cpp57
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/TestDataFormatterLibcxxSet.py69
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/main.cpp57
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/TestDataFormatterLibcxxString.py86
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/main.cpp15
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/TestDataFormatterUnordered.py75
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/main.cpp84
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/TestDataFormatterLibcxxVBool.py58
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/main.cpp69
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/TestDataFormatterLibcxxVector.py180
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/main.cpp35
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/Makefile15
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/TestDataFormatterStdIterator.py62
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/main.cpp38
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/Makefile15
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/TestDataFormatterStdList.py188
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/main.cpp34
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/Makefile14
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/TestDataFormatterStdMap.py322
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/main.cpp55
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/Makefile15
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/TestDataFormatterStdString.py66
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/main.cpp12
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/TestDataFormatterStdVBool.py58
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/main.cpp63
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/Makefile15
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/TestDataFormatterStdVector.py207
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/main.cpp31
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/Makefile12
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/TestDataFormatterSynth.py205
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/main.cpp86
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/TestDataFormatterSynthVal.py96
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/main.cpp29
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/myIntSynthProvider.py36
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/Makefile12
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/TestDumpDynamic.py5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/main.cpp35
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/TestFormatPropagation.py75
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/main.cpp13
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/TestFrameFormatSmallStruct.py38
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/main.cpp25
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/TestDataFormatterHexCaps.py82
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/main.cpp28
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/TestDataFormatterLanguageCategoryUpdates.py60
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/main.cpp20
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/TestNSArraySynthetic.py67
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/main.m35
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/TestNSDictionarySynthetic.py69
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/main.m30
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/TestNSSetSynthetic.py74
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/main.m34
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/TestFormattersOsType.py52
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/main.mm23
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/TestPtrRef2Typedef.py57
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/main.cpp19
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/TestDataFormatterRefPtrRecursion.py41
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/main.cpp21
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/Makefile4
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/TestSetValueFromCString.py4
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/main.m19
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/Makefile12
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/TestStringPrinter.py4
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/main.cpp40
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/Makefile12
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/Test-rdar-9974002.py133
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/main.cpp30
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/TestSyntheticCapping.py75
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/fooSynthProvider.py21
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/main.cpp62
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/Makefile12
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/TestSyntheticFilterRecompute.py74
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/main.m25
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/Makefile4
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/TestTypedefArray.py4
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/main.cpp14
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/TestUserFormatVsSummary.py59
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/main.cpp20
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/Makefile11
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/TestVarInAggregateMisuse.py74
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/main.cpp41
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/TestDataFormatterVarScriptFormatting.py56
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/helperfunc.py5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/main.cpp8
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/TestVectorTypesFormatting.py73
-rw-r--r--packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/main.cpp17
-rw-r--r--packages/Python/lldbsuite/test/functionalities/dead-strip/Makefile18
-rw-r--r--packages/Python/lldbsuite/test/functionalities/dead-strip/TestDeadStrip.py58
-rw-r--r--packages/Python/lldbsuite/test/functionalities/dead-strip/cmds.txt4
-rw-r--r--packages/Python/lldbsuite/test/functionalities/dead-strip/main.c53
-rw-r--r--packages/Python/lldbsuite/test/functionalities/disassembly/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/disassembly/TestDisassembleBreakpoint.py54
-rw-r--r--packages/Python/lldbsuite/test/functionalities/disassembly/main.cpp28
-rw-r--r--packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/TestDynamicValueChildCount.py78
-rw-r--r--packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/pass-to-base.cpp36
-rw-r--r--packages/Python/lldbsuite/test/functionalities/embedded_interpreter/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/embedded_interpreter/TestConvenienceVariables.py78
-rw-r--r--packages/Python/lldbsuite/test/functionalities/embedded_interpreter/main.c6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/exec/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/exec/TestExec.py85
-rw-r--r--packages/Python/lldbsuite/test/functionalities/exec/main.cpp94
-rw-r--r--packages/Python/lldbsuite/test/functionalities/expr-doesnt-deadlock/.categories1
-rw-r--r--packages/Python/lldbsuite/test/functionalities/expr-doesnt-deadlock/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/expr-doesnt-deadlock/TestExprDoesntBlock.py57
-rw-r--r--packages/Python/lldbsuite/test/functionalities/expr-doesnt-deadlock/locking.c80
-rw-r--r--packages/Python/lldbsuite/test/functionalities/fat_archives/Makefile14
-rw-r--r--packages/Python/lldbsuite/test/functionalities/fat_archives/TestFatArchives.py58
-rw-r--r--packages/Python/lldbsuite/test/functionalities/fat_archives/a.c4
-rw-r--r--packages/Python/lldbsuite/test/functionalities/fat_archives/a.h1
-rw-r--r--packages/Python/lldbsuite/test/functionalities/fat_archives/main.c6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/format/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/format/TestFormats.py59
-rw-r--r--packages/Python/lldbsuite/test/functionalities/format/main.c15
-rw-r--r--packages/Python/lldbsuite/test/functionalities/inferior-assert/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/inferior-assert/TestInferiorAssert.py253
-rw-r--r--packages/Python/lldbsuite/test/functionalities/inferior-assert/main.c19
-rw-r--r--packages/Python/lldbsuite/test/functionalities/inferior-changed/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/inferior-changed/TestInferiorChanged.py80
-rw-r--r--packages/Python/lldbsuite/test/functionalities/inferior-changed/main.c16
-rw-r--r--packages/Python/lldbsuite/test/functionalities/inferior-changed/main2.c18
-rw-r--r--packages/Python/lldbsuite/test/functionalities/inferior-crashing/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/inferior-crashing/TestInferiorCrashing.py220
-rw-r--r--packages/Python/lldbsuite/test/functionalities/inferior-crashing/main.c18
-rw-r--r--packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/TestRecursiveInferior.py220
-rw-r--r--packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/main.c19
-rw-r--r--packages/Python/lldbsuite/test/functionalities/inline-stepping/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/inline-stepping/TestInlineStepping.py270
-rw-r--r--packages/Python/lldbsuite/test/functionalities/inline-stepping/calling.cpp136
-rw-r--r--packages/Python/lldbsuite/test/functionalities/jitloader_gdb/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/jitloader_gdb/TestJITLoaderGDB.py37
-rw-r--r--packages/Python/lldbsuite/test/functionalities/jitloader_gdb/main.c44
-rw-r--r--packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/TestLaunchWithShellExpand.py97
-rw-r--r--packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/file1.txt0
-rw-r--r--packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/file2.txt0
-rw-r--r--packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/file3.txt0
-rw-r--r--packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/file4.txy0
-rw-r--r--packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/file5.tyx0
-rw-r--r--packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/foo bar0
-rw-r--r--packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/main.cpp5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/load_unload/Makefile24
-rw-r--r--packages/Python/lldbsuite/test/functionalities/load_unload/TestLoadUnload.py357
-rw-r--r--packages/Python/lldbsuite/test/functionalities/load_unload/a.cpp22
-rw-r--r--packages/Python/lldbsuite/test/functionalities/load_unload/a.mk23
-rw-r--r--packages/Python/lldbsuite/test/functionalities/load_unload/b.cpp21
-rw-r--r--packages/Python/lldbsuite/test/functionalities/load_unload/b.mk11
-rw-r--r--packages/Python/lldbsuite/test/functionalities/load_unload/c.cpp13
-rw-r--r--packages/Python/lldbsuite/test/functionalities/load_unload/c.mk11
-rw-r--r--packages/Python/lldbsuite/test/functionalities/load_unload/cmds.txt2
-rw-r--r--packages/Python/lldbsuite/test/functionalities/load_unload/d.cpp21
-rw-r--r--packages/Python/lldbsuite/test/functionalities/load_unload/d.mk13
-rw-r--r--packages/Python/lldbsuite/test/functionalities/load_unload/hidden/Makefile11
-rw-r--r--packages/Python/lldbsuite/test/functionalities/load_unload/hidden/d.cpp21
-rw-r--r--packages/Python/lldbsuite/test/functionalities/load_unload/main.cpp80
-rw-r--r--packages/Python/lldbsuite/test/functionalities/longjmp/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/longjmp/TestLongjmp.py85
-rw-r--r--packages/Python/lldbsuite/test/functionalities/longjmp/main.c31
-rw-r--r--packages/Python/lldbsuite/test/functionalities/memory/read/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/memory/read/TestMemoryRead.py99
-rw-r--r--packages/Python/lldbsuite/test/functionalities/memory/read/main.cpp19
-rw-r--r--packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/TestIndexVariable.py43
-rw-r--r--packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/main.cpp51
-rw-r--r--packages/Python/lldbsuite/test/functionalities/nosucharch/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/nosucharch/TestNoSuchArch.py29
-rw-r--r--packages/Python/lldbsuite/test/functionalities/nosucharch/main.cpp3
-rw-r--r--packages/Python/lldbsuite/test/functionalities/object-file/TestImageListMultiArchitecture.py41
-rw-r--r--packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-freebsd-10.0-x86_64-clang-3.3bin0 -> 7477 bytes
-rw-r--r--packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-freebsd-10.0-x86_64-gcc-4.7.3bin0 -> 7520 bytes
-rw-r--r--packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-netbsd-6.1-x86_64-gcc-4.5.3bin0 -> 7352 bytes
-rw-r--r--packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-ubuntu-14.04-x86_64-clang-3.5prebin0 -> 8112 bytes
-rw-r--r--packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-ubuntu-14.04-x86_64-gcc-4.8.2bin0 -> 8056 bytes
-rw-r--r--packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-unknown-kalimba_arch4-kcc-36bin0 -> 17224 bytes
-rw-r--r--packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-unknown-kalimba_arch5-kcc-39bin0 -> 28356 bytes
-rw-r--r--packages/Python/lldbsuite/test/functionalities/object-file/bin/hello.c8
-rw-r--r--packages/Python/lldbsuite/test/functionalities/object-file/bin/hello.cpp8
-rw-r--r--packages/Python/lldbsuite/test/functionalities/paths/TestPaths.py48
-rw-r--r--packages/Python/lldbsuite/test/functionalities/platform/TestPlatformCommand.py65
-rw-r--r--packages/Python/lldbsuite/test/functionalities/plugins/commands/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/functionalities/plugins/commands/TestPluginCommands.py58
-rw-r--r--packages/Python/lldbsuite/test/functionalities/plugins/commands/plugin.cpp62
-rw-r--r--packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/Makefile3
-rw-r--r--packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/TestPythonOSPlugin.py150
-rw-r--r--packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/main.c7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system.py90
-rw-r--r--packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system2.py88
-rw-r--r--packages/Python/lldbsuite/test/functionalities/postmortem/minidump/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/postmortem/minidump/TestMiniDump.py128
-rw-r--r--packages/Python/lldbsuite/test/functionalities/postmortem/minidump/fizzbuzz.cpp31
-rw-r--r--packages/Python/lldbsuite/test/functionalities/postmortem/minidump/fizzbuzz_no_heap.dmpbin0 -> 6297 bytes
-rw-r--r--packages/Python/lldbsuite/test/functionalities/postmortem/minidump/main.cpp21
-rw-r--r--packages/Python/lldbsuite/test/functionalities/process_attach/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/process_attach/TestProcessAttach.py58
-rw-r--r--packages/Python/lldbsuite/test/functionalities/process_attach/attach_denied/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/process_attach/attach_denied/TestAttachDenied.py60
-rw-r--r--packages/Python/lldbsuite/test/functionalities/process_attach/attach_denied/main.cpp108
-rw-r--r--packages/Python/lldbsuite/test/functionalities/process_attach/main.cpp37
-rw-r--r--packages/Python/lldbsuite/test/functionalities/process_group/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/process_group/TestChangeProcessGroup.py107
-rw-r--r--packages/Python/lldbsuite/test/functionalities/process_group/main.c86
-rw-r--r--packages/Python/lldbsuite/test/functionalities/process_launch/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/process_launch/TestProcessLaunch.py207
-rw-r--r--packages/Python/lldbsuite/test/functionalities/process_launch/input-file.txt2
-rw-r--r--packages/Python/lldbsuite/test/functionalities/process_launch/main.cpp17
-rw-r--r--packages/Python/lldbsuite/test/functionalities/process_launch/my_working_dir/.keep0
-rw-r--r--packages/Python/lldbsuite/test/functionalities/process_launch/print_cwd.cpp21
-rw-r--r--packages/Python/lldbsuite/test/functionalities/process_launch/print_env.cpp11
-rw-r--r--packages/Python/lldbsuite/test/functionalities/process_save_core/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/process_save_core/TestProcessSaveCore.py58
-rw-r--r--packages/Python/lldbsuite/test/functionalities/process_save_core/main.cpp21
-rw-r--r--packages/Python/lldbsuite/test/functionalities/recursion/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/recursion/TestValueObjectRecursion.py59
-rw-r--r--packages/Python/lldbsuite/test/functionalities/recursion/main.cpp41
-rw-r--r--packages/Python/lldbsuite/test/functionalities/register/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/register/TestRegisters.py349
-rw-r--r--packages/Python/lldbsuite/test/functionalities/register/a.cpp44
-rw-r--r--packages/Python/lldbsuite/test/functionalities/register/main.cpp51
-rw-r--r--packages/Python/lldbsuite/test/functionalities/rerun/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/rerun/TestRerun.py76
-rw-r--r--packages/Python/lldbsuite/test/functionalities/rerun/main.cpp5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/return-value/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/return-value/TestReturnValue.py214
-rw-r--r--packages/Python/lldbsuite/test/functionalities/return-value/call-func.c407
-rw-r--r--packages/Python/lldbsuite/test/functionalities/set-data/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/set-data/TestSetData.py62
-rw-r--r--packages/Python/lldbsuite/test/functionalities/set-data/main.m19
-rw-r--r--packages/Python/lldbsuite/test/functionalities/signal/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/signal/TestSendSignal.py105
-rw-r--r--packages/Python/lldbsuite/test/functionalities/signal/handle-segv/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/signal/handle-segv/TestHandleSegv.py43
-rw-r--r--packages/Python/lldbsuite/test/functionalities/signal/handle-segv/main.c58
-rw-r--r--packages/Python/lldbsuite/test/functionalities/signal/main.c27
-rw-r--r--packages/Python/lldbsuite/test/functionalities/signal/raise/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/signal/raise/TestRaise.py221
-rw-r--r--packages/Python/lldbsuite/test/functionalities/signal/raise/main.c42
-rw-r--r--packages/Python/lldbsuite/test/functionalities/single-quote-in-filename-to-lldb/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/single-quote-in-filename-to-lldb/TestSingleQuoteInFilename.py71
-rw-r--r--packages/Python/lldbsuite/test/functionalities/single-quote-in-filename-to-lldb/main.c7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/single-quote-in-filename-to-lldb/path with '09/.keep0
-rw-r--r--packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/TestStepNoDebug.py113
-rw-r--r--packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/with-debug.c29
-rw-r--r--packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/without-debug.c17
-rw-r--r--packages/Python/lldbsuite/test/functionalities/stop-hook/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/stop-hook/TestStopHookCmd.py65
-rw-r--r--packages/Python/lldbsuite/test/functionalities/stop-hook/TestStopHookMechanism.py101
-rw-r--r--packages/Python/lldbsuite/test/functionalities/stop-hook/main.cpp54
-rw-r--r--packages/Python/lldbsuite/test/functionalities/stop-hook/multiple_threads/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/stop-hook/multiple_threads/TestStopHookMultipleThreads.py77
-rw-r--r--packages/Python/lldbsuite/test/functionalities/stop-hook/multiple_threads/main.cpp77
-rw-r--r--packages/Python/lldbsuite/test/functionalities/target_command/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/functionalities/target_command/TestTargetCommand.py201
-rw-r--r--packages/Python/lldbsuite/test/functionalities/target_command/a.c16
-rw-r--r--packages/Python/lldbsuite/test/functionalities/target_command/b.c13
-rw-r--r--packages/Python/lldbsuite/test/functionalities/target_command/c.c29
-rw-r--r--packages/Python/lldbsuite/test/functionalities/target_command/globals.c25
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/TestNumThreads.py53
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/Makefile6
-rwxr-xr-xpackages/Python/lldbsuite/test/functionalities/thread/backtrace_all/ParallelTask.cpp151
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/TestBacktraceAll.py57
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/break_after_join/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/break_after_join/TestBreakAfterJoin.py77
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/break_after_join/main.cpp118
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentEvents.py491
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/main.cpp200
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/Makefile4
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/TestCrashDuringStep.py53
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/main.cpp16
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/TestCreateAfterAttach.py122
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/main.cpp78
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/create_during_step/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/create_during_step/TestCreateDuringStep.py127
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/create_during_step/main.cpp89
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/TestExitDuringBreak.py81
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/main.cpp130
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/TestExitDuringStep.py144
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/main.cpp87
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/jump/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/jump/TestThreadJump.py60
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/jump/main.cpp35
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/jump/other.cpp13
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/main.cpp50
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/multi_break/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/multi_break/TestMultipleBreakpoints.py77
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/multi_break/main.cpp61
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/state/Makefile4
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/state/TestThreadStates.py333
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/state/main.cpp45
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/step_out/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/step_out/TestThreadStepOut.py131
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/step_out/main.cpp63
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/thread_exit/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/thread_exit/TestThreadExit.py116
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/thread_exit/main.cpp85
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/TestThreadSpecificBreakpoint.py63
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/main.cpp20
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/TestThreadSpecificBpPlusCondition.py65
-rw-r--r--packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/main.cpp39
-rw-r--r--packages/Python/lldbsuite/test/functionalities/tty/TestTerminal.py40
-rw-r--r--packages/Python/lldbsuite/test/functionalities/type_completion/Makefile12
-rw-r--r--packages/Python/lldbsuite/test/functionalities/type_completion/TestTypeCompletion.py108
-rw-r--r--packages/Python/lldbsuite/test/functionalities/type_completion/main.cpp81
-rw-r--r--packages/Python/lldbsuite/test/functionalities/type_lookup/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/type_lookup/TestTypeLookup.py43
-rw-r--r--packages/Python/lldbsuite/test/functionalities/type_lookup/main.m16
-rw-r--r--packages/Python/lldbsuite/test/functionalities/unwind/noreturn/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/functionalities/unwind/noreturn/TestNoreturnUnwind.py76
-rw-r--r--packages/Python/lldbsuite/test/functionalities/unwind/noreturn/main.c37
-rw-r--r--packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/TestSigtrampUnwind.py81
-rw-r--r--packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/main.c27
-rw-r--r--packages/Python/lldbsuite/test/functionalities/unwind/standard/Makefile3
-rw-r--r--packages/Python/lldbsuite/test/functionalities/unwind/standard/TestStandardUnwind.py145
-rw-r--r--packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/divmod.cpp15
-rw-r--r--packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/fprintf.cpp16
-rw-r--r--packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/new_delete.cpp15
-rw-r--r--packages/Python/lldbsuite/test/functionalities/value_md5_crash/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/value_md5_crash/TestValueMD5Crash.py52
-rw-r--r--packages/Python/lldbsuite/test/functionalities/value_md5_crash/main.cpp29
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchlocation/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchlocation/TestWatchLocation.py98
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchlocation/main.cpp106
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchpoint/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchpoint/TestMyFirstWatchpoint.py84
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchpoint/main.c30
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/multiple_threads/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/multiple_threads/TestWatchpointMultipleThreads.py137
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/multiple_threads/main.cpp83
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/step_over_watchpoint/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/step_over_watchpoint/TestStepOverWatchpoint.py113
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/step_over_watchpoint/main.c19
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/variable_out_of_scope/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/variable_out_of_scope/TestWatchedVarHitWhenInScope.py83
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/variable_out_of_scope/main.c15
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/TestWatchpointCommands.py313
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/TestWatchpointCommandLLDB.py139
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/TestWatchpointCommandPython.py87
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/main.cpp28
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/condition/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/condition/TestWatchpointConditionCmd.py78
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/condition/main.cpp28
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/main.c24
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_events/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_events/TestWatchpointEvents.py89
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_events/main.c9
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_on_vectors/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_on_vectors/TestValueOfVectorVariable.py47
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_on_vectors/main.c16
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/TestWatchLocationWithWatchSet.py89
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/TestWatchpointSetErrorCases.py67
-rw-r--r--packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/main.cpp121
-rw-r--r--packages/Python/lldbsuite/test/help/TestHelp.py165
-rw-r--r--packages/Python/lldbsuite/test/issue_verification/Makefile4
-rw-r--r--packages/Python/lldbsuite/test/issue_verification/README.txt5
-rw-r--r--packages/Python/lldbsuite/test/issue_verification/TestExpectedTimeout.py.park20
-rw-r--r--packages/Python/lldbsuite/test/issue_verification/TestFail.py.park16
-rw-r--r--packages/Python/lldbsuite/test/issue_verification/TestRerunFail.py.park23
-rw-r--r--packages/Python/lldbsuite/test/issue_verification/TestRerunInline.py.park13
-rw-r--r--packages/Python/lldbsuite/test/issue_verification/TestRerunTimeout.py.park22
-rw-r--r--packages/Python/lldbsuite/test/issue_verification/TestSignal.py.park26
-rw-r--r--packages/Python/lldbsuite/test/issue_verification/TestSignalOutsideTestMethod.py.park24
-rw-r--r--packages/Python/lldbsuite/test/issue_verification/TestTimeout.py.park19
-rwxr-xr-xpackages/Python/lldbsuite/test/issue_verification/disable.py20
-rwxr-xr-xpackages/Python/lldbsuite/test/issue_verification/enable.py20
-rw-r--r--packages/Python/lldbsuite/test/issue_verification/inline_rerun_inferior.cpp14
-rw-r--r--packages/Python/lldbsuite/test/issue_verification/rerun_base.py28
-rw-r--r--packages/Python/lldbsuite/test/lang/c/anonymous/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/c/anonymous/TestAnonymous.py147
-rw-r--r--packages/Python/lldbsuite/test/lang/c/anonymous/main.c82
-rw-r--r--packages/Python/lldbsuite/test/lang/c/array_types/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/c/array_types/TestArrayTypes.py198
-rw-r--r--packages/Python/lldbsuite/test/lang/c/array_types/cmds.txt3
-rw-r--r--packages/Python/lldbsuite/test/lang/c/array_types/main.c51
-rw-r--r--packages/Python/lldbsuite/test/lang/c/bitfields/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/c/bitfields/TestBitfields.py162
-rw-r--r--packages/Python/lldbsuite/test/lang/c/bitfields/main.c67
-rw-r--r--packages/Python/lldbsuite/test/lang/c/blocks/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/c/blocks/TestBlocks.py61
-rw-r--r--packages/Python/lldbsuite/test/lang/c/blocks/main.c21
-rw-r--r--packages/Python/lldbsuite/test/lang/c/const_variables/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/lang/c/const_variables/TestConstVariables.py64
-rw-r--r--packages/Python/lldbsuite/test/lang/c/const_variables/functions.c18
-rw-r--r--packages/Python/lldbsuite/test/lang/c/const_variables/main.c23
-rw-r--r--packages/Python/lldbsuite/test/lang/c/enum_types/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/c/enum_types/TestEnumTypes.py71
-rw-r--r--packages/Python/lldbsuite/test/lang/c/enum_types/main.c29
-rw-r--r--packages/Python/lldbsuite/test/lang/c/forward/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/c/forward/README.txt5
-rw-r--r--packages/Python/lldbsuite/test/lang/c/forward/TestForwardDeclaration.py47
-rw-r--r--packages/Python/lldbsuite/test/lang/c/forward/foo.c8
-rw-r--r--packages/Python/lldbsuite/test/lang/c/forward/foo.h4
-rw-r--r--packages/Python/lldbsuite/test/lang/c/forward/main.c18
-rw-r--r--packages/Python/lldbsuite/test/lang/c/function_types/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/c/function_types/TestFunctionTypes.py76
-rw-r--r--packages/Python/lldbsuite/test/lang/c/function_types/main.c22
-rw-r--r--packages/Python/lldbsuite/test/lang/c/global_variables/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/lang/c/global_variables/TestGlobalVariables.py76
-rw-r--r--packages/Python/lldbsuite/test/lang/c/global_variables/a.c15
-rw-r--r--packages/Python/lldbsuite/test/lang/c/global_variables/cmds.txt3
-rw-r--r--packages/Python/lldbsuite/test/lang/c/global_variables/main.c24
-rw-r--r--packages/Python/lldbsuite/test/lang/c/inlines/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/c/inlines/inlines.c53
-rw-r--r--packages/Python/lldbsuite/test/lang/c/inlines/inlines.h4
-rw-r--r--packages/Python/lldbsuite/test/lang/c/modules/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/c/modules/TestCModules.py65
-rw-r--r--packages/Python/lldbsuite/test/lang/c/modules/main.c20
-rw-r--r--packages/Python/lldbsuite/test/lang/c/recurse/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/c/recurse/main.c28
-rw-r--r--packages/Python/lldbsuite/test/lang/c/register_variables/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/lang/c/register_variables/TestRegisterVariables.py70
-rw-r--r--packages/Python/lldbsuite/test/lang/c/register_variables/test.c27
-rw-r--r--packages/Python/lldbsuite/test/lang/c/set_values/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/c/set_values/TestSetValues.py111
-rw-r--r--packages/Python/lldbsuite/test/lang/c/set_values/main.c116
-rw-r--r--packages/Python/lldbsuite/test/lang/c/shared_lib/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/lang/c/shared_lib/TestSharedLib.py71
-rw-r--r--packages/Python/lldbsuite/test/lang/c/shared_lib/foo.c22
-rw-r--r--packages/Python/lldbsuite/test/lang/c/shared_lib/foo.h10
-rw-r--r--packages/Python/lldbsuite/test/lang/c/shared_lib/main.c13
-rw-r--r--packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/Makefile10
-rw-r--r--packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/TestSharedLibStrippedSymbols.py73
-rw-r--r--packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/foo.c22
-rw-r--r--packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/foo.h12
-rw-r--r--packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/main.c13
-rw-r--r--packages/Python/lldbsuite/test/lang/c/stepping/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/c/stepping/TestStepAndBreakpoints.py242
-rw-r--r--packages/Python/lldbsuite/test/lang/c/stepping/TestThreadStepping.py81
-rw-r--r--packages/Python/lldbsuite/test/lang/c/stepping/main.c69
-rw-r--r--packages/Python/lldbsuite/test/lang/c/strings/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/c/strings/TestCStrings.py54
-rw-r--r--packages/Python/lldbsuite/test/lang/c/strings/main.c18
-rw-r--r--packages/Python/lldbsuite/test/lang/c/struct_types/Makefile3
-rw-r--r--packages/Python/lldbsuite/test/lang/c/struct_types/TestStructTypes.py4
-rw-r--r--packages/Python/lldbsuite/test/lang/c/struct_types/main.c43
-rw-r--r--packages/Python/lldbsuite/test/lang/c/tls_globals/Makefile11
-rw-r--r--packages/Python/lldbsuite/test/lang/c/tls_globals/TestTlsGlobals.py75
-rw-r--r--packages/Python/lldbsuite/test/lang/c/tls_globals/a.c18
-rw-r--r--packages/Python/lldbsuite/test/lang/c/tls_globals/main.c36
-rw-r--r--packages/Python/lldbsuite/test/lang/c/typedef/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/c/typedef/Testtypedef.py40
-rw-r--r--packages/Python/lldbsuite/test/lang/c/typedef/main.c46
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/auto/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/auto/TestCPPAuto.py25
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/auto/main.cpp16
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/bool/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/bool/TestCPPBool.py26
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/bool/main.cpp17
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/TestCPPBreakpointCommands.py84
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/nested.cpp76
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/call-function/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/call-function/TestCallCPPFunction.py33
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/call-function/main.cpp11
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/chained-calls/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/chained-calls/TestCppChainedCalls.py73
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/chained-calls/main.cpp33
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/char1632_t/.categories1
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/char1632_t/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/char1632_t/TestChar1632T.py90
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/char1632_t/main.cpp44
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/class_static/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/class_static/TestStaticVariables.py120
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/class_static/main.cpp53
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/class_types/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypes.py215
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypesDisassembly.py94
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/class_types/cmds.txt3
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/class_types/main.cpp126
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/diamond/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/diamond/TestDiamond.py41
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/diamond/main.cpp85
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/dynamic-value/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestCppValueCast.py129
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestDynamicValue.py223
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/dynamic-value/pass-to-base.cpp69
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/dynamic-value/sbvalue-cast.cpp80
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/enum_types/Makefile10
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/enum_types/TestCPP11EnumTypes.py110
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/enum_types/main.cpp33
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/exceptions/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/exceptions/TestCPPExceptionBreakpoints.py65
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/exceptions/exceptions.cpp42
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/TestFrameVariableAnonymousUnions.py27
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/main.cpp23
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/global_operators/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/global_operators/TestCppGlobalOperators.py54
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/global_operators/main.cpp16
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/incomplete-types/Makefile35
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/incomplete-types/TestCppIncompleteTypes.py66
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/incomplete-types/a.cpp10
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/incomplete-types/a.h11
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/incomplete-types/length.cpp8
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/incomplete-types/length.h8
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/incomplete-types/main.cpp18
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/TestWithLimitDebugInfo.py48
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/base.cpp6
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/base.h10
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/derived.cpp6
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/derived.h13
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/main.cpp7
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/namespace/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespace.py125
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespaceLookup.py223
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/namespace/cmds.txt3
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/namespace/main.cpp124
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/namespace/ns.cpp32
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/namespace/ns.h36
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/namespace/ns2.cpp65
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/namespace/ns3.cpp27
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/nsimport/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/nsimport/TestCppNsImport.py101
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/nsimport/main.cpp72
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/TestOverloadedFunctions.py36
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/main.cpp43
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/static-a.cpp9
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/static-b.cpp9
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/rdar12991846/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/rdar12991846/TestRdar12991846.py85
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/rdar12991846/main.cpp21
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/rvalue-references/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/rvalue-references/TestRvalueReferences.py49
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/rvalue-references/main.cpp12
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/scope/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/scope/TestCppScope.py67
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/scope/main.cpp25
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/signed_types/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/signed_types/TestSignedTypes.py60
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/signed_types/main.cpp33
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/static_members/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/static_members/TestCPPStaticMembers.py59
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/static_members/main.cpp36
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/static_methods/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/static_methods/TestCPPStaticMethods.py36
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/static_methods/main.cpp38
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/stl/Makefile15
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/stl/TestSTL.py118
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/stl/TestStdCXXDisassembly.py111
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/stl/cmds.txt3
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/stl/main.cpp30
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/this/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/this/TestCPPThis.py53
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/this/main.cpp53
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/unique-types/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/unique-types/TestUniqueTypes.py62
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/unique-types/main.cpp24
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/unsigned_types/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/unsigned_types/TestUnsignedTypes.py54
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/unsigned_types/main.cpp22
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/virtual/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/virtual/TestVirtual.py90
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/virtual/main.cpp113
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/wchar_t/.categories1
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/wchar_t/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/wchar_t/TestCxxWCharT.py74
-rw-r--r--packages/Python/lldbsuite/test/lang/cpp/wchar_t/main.cpp35
-rw-r--r--packages/Python/lldbsuite/test/lang/go/expressions/TestExpressions.py113
-rw-r--r--packages/Python/lldbsuite/test/lang/go/expressions/main.go21
-rw-r--r--packages/Python/lldbsuite/test/lang/go/formatters/TestGoFormatters.py65
-rw-r--r--packages/Python/lldbsuite/test/lang/go/formatters/main.go9
-rw-r--r--packages/Python/lldbsuite/test/lang/go/goroutines/TestGoroutines.py85
-rw-r--r--packages/Python/lldbsuite/test/lang/go/goroutines/main.go89
-rw-r--r--packages/Python/lldbsuite/test/lang/go/runtime/TestGoLanguageRuntime80
-rw-r--r--packages/Python/lldbsuite/test/lang/go/runtime/main.go38
-rw-r--r--packages/Python/lldbsuite/test/lang/go/types/TestGoASTContext.py133
-rw-r--r--packages/Python/lldbsuite/test/lang/go/types/main.go47
-rw-r--r--packages/Python/lldbsuite/test/lang/mixed/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/mixed/TestMixedLanguages.py56
-rw-r--r--packages/Python/lldbsuite/test/lang/mixed/foo.cpp11
-rw-r--r--packages/Python/lldbsuite/test/lang/mixed/main.c15
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/.categories1
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/blocks/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/blocks/TestObjCIvarsInBlocks.py103
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/blocks/ivars-in-blocks.h11
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/blocks/ivars-in-blocks.m57
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/blocks/main.m10
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/forward-decl/Container.h13
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/forward-decl/Container.m27
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/forward-decl/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/forward-decl/TestForwardDecl.py54
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/forward-decl/main.m14
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/foundation/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/foundation/TestConstStrings.py53
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/foundation/TestFoundationDisassembly.py134
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods.py262
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods2.py169
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/foundation/TestObjectDescriptionAPI.py71
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/foundation/TestRuntimeTypes.py48
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/foundation/TestSymbolTable.py68
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/foundation/const-strings.m24
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/foundation/main.m141
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/foundation/my-base.h8
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/foundation/my-base.m10
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/hidden-ivars/InternalDefiner.h11
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/hidden-ivars/InternalDefiner.m31
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/hidden-ivars/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/hidden-ivars/TestHiddenIvars.py174
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/hidden-ivars/main.m54
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/ivar-IMP/Makefile12
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/ivar-IMP/TestObjCiVarIMP.py63
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/ivar-IMP/myclass.h6
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/ivar-IMP/myclass.m16
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/ivar-IMP/repro.m7
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/modules-auto-import/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/modules-auto-import/TestModulesAutoImport.py53
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/modules-auto-import/main.m7
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/modules-incomplete/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/modules-incomplete/TestIncompleteModules.py61
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/modules-incomplete/main.m11
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/modules-incomplete/module.map4
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/modules-incomplete/myModule.h8
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/modules-incomplete/myModule.m14
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/TestModulesInlineFunctions.py55
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/main.m9
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/module.map4
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/myModule.c7
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/myModule.h7
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/modules/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/modules/TestObjCModules.py71
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/modules/main.m12
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc++/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc++/TestObjCXX.py33
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc++/main.mm19
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/TestObjCBaseClassSBType.py58
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/main.m22
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/TestObjCBuiltinTypes.py55
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/main.cpp9
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-checker/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-checker/TestObjCCheckers.py75
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-checker/main.m32
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-class-method/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-class-method/TestObjCClassMethod.py56
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-class-method/class.m24
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/.categories1
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/TestObjCDynamicSBType.py62
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/main.m53
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/TestObjCDynamicValue.py177
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/dynamic-value.m147
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/TestObjCIvarOffsets.py74
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/main.m15
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/objc-ivar-offsets.h27
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/objc-ivar-offsets.m19
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-ivar-protocols/TestIvarProtocols.py4
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-ivar-protocols/main.m33
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/Makefile15
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/TestObjCIvarStripped.py59
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/main.m33
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/TestObjCNewSyntax.py103
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/main.m21
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-optimized/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-optimized/TestObjcOptimized.py63
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-optimized/main.m44
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-property/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-property/TestObjCProperty.py114
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-property/main.m100
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/TestRuntimeIvars.py4
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/main.m10
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/Makefile15
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/TestObjCStaticMethodStripped.py65
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/static.m29
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-static-method/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-static-method/TestObjCStaticMethod.py61
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-static-method/static.m29
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-stepping/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-stepping/TestObjCStepping.py172
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-stepping/stepping-tests.m138
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/TestObjCStructArgument.py57
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/test.m34
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-struct-return/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-struct-return/TestObjCStructReturn.py53
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-struct-return/test.m23
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-super/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-super/TestObjCSuper.py59
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/objc-super/class.m39
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/print-obj/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/print-obj/TestPrintObj.py87
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/print-obj/blocked.m73
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/radar-9691614/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/radar-9691614/TestObjCMethodReturningBOOL.py45
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/radar-9691614/main.m67
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/rdar-10967107/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/rdar-10967107/TestRdar10967107.py44
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/rdar-10967107/main.m13
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/rdar-11355592/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/rdar-11355592/TestRdar11355592.py65
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/rdar-11355592/main.m37
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/rdar-12408181/Makefile11
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/rdar-12408181/TestRdar12408181.py48
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/rdar-12408181/main.m24
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/real-definition/Bar.h12
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/real-definition/Bar.m43
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/real-definition/Foo.h11
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/real-definition/Foo.m25
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/real-definition/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/real-definition/TestRealDefinition.py86
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/real-definition/main.m13
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/sample/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/sample/main.m70
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/self/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/self/TestObjCSelf.py36
-rw-r--r--packages/Python/lldbsuite/test/lang/objc/self/main.m54
-rw-r--r--packages/Python/lldbsuite/test/lang/objcxx/objcxx-ivar-vector/TestIvarVector.py4
-rw-r--r--packages/Python/lldbsuite/test/lang/objcxx/objcxx-ivar-vector/main.mm33
-rw-r--r--packages/Python/lldbsuite/test/lang/objcxx/sample/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/lang/objcxx/sample/main.mm71
-rw-r--r--packages/Python/lldbsuite/test/linux/builtin_trap/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/linux/builtin_trap/TestBuiltinTrap.py51
-rw-r--r--packages/Python/lldbsuite/test/linux/builtin_trap/main.cpp17
-rw-r--r--packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/TestCreateDuringInstructionStep.py66
-rw-r--r--packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/main.cpp55
-rw-r--r--packages/Python/lldbsuite/test/lldb_pylint_helper.py181
-rw-r--r--packages/Python/lldbsuite/test/lldbbench.py118
-rw-r--r--packages/Python/lldbsuite/test/lldbcurses.py1143
-rw-r--r--packages/Python/lldbsuite/test/lldbinline.py210
-rw-r--r--packages/Python/lldbsuite/test/lldbpexpect.py63
-rw-r--r--packages/Python/lldbsuite/test/lldbplatformutil.py27
-rw-r--r--packages/Python/lldbsuite/test/lldbtest.py2775
-rw-r--r--packages/Python/lldbsuite/test/lldbtest_config.py21
-rw-r--r--packages/Python/lldbsuite/test/lldbutil.py1016
-rw-r--r--packages/Python/lldbsuite/test/lock.py27
-rw-r--r--packages/Python/lldbsuite/test/logging/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/logging/TestLogging.py107
-rw-r--r--packages/Python/lldbsuite/test/logging/main.cpp62
-rw-r--r--packages/Python/lldbsuite/test/macosx/add-dsym/Makefile11
-rw-r--r--packages/Python/lldbsuite/test/macosx/add-dsym/TestAddDsymMidExecutionCommand.py45
-rw-r--r--packages/Python/lldbsuite/test/macosx/add-dsym/main.c7
-rw-r--r--packages/Python/lldbsuite/test/macosx/debug-info/apple_types/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/macosx/debug-info/apple_types/TestAppleTypesIsProduced.py67
-rw-r--r--packages/Python/lldbsuite/test/macosx/debug-info/apple_types/main.c27
-rw-r--r--packages/Python/lldbsuite/test/macosx/indirect_symbol/Makefile48
-rw-r--r--packages/Python/lldbsuite/test/macosx/indirect_symbol/TestIndirectSymbols.py88
-rw-r--r--packages/Python/lldbsuite/test/macosx/indirect_symbol/alias.list1
-rw-r--r--packages/Python/lldbsuite/test/macosx/indirect_symbol/indirect.c14
-rw-r--r--packages/Python/lldbsuite/test/macosx/indirect_symbol/main.c14
-rw-r--r--packages/Python/lldbsuite/test/macosx/indirect_symbol/reexport.c7
-rw-r--r--packages/Python/lldbsuite/test/macosx/order/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/macosx/order/TestOrderFile.py36
-rw-r--r--packages/Python/lldbsuite/test/macosx/order/cmds.txt3
-rw-r--r--packages/Python/lldbsuite/test/macosx/order/main.c54
-rw-r--r--packages/Python/lldbsuite/test/macosx/order/order-file4
-rw-r--r--packages/Python/lldbsuite/test/macosx/queues/Makefile28
-rw-r--r--packages/Python/lldbsuite/test/macosx/queues/TestQueues.py243
-rw-r--r--packages/Python/lldbsuite/test/macosx/queues/main.c133
-rw-r--r--packages/Python/lldbsuite/test/macosx/safe-to-func-call/Makefile28
-rw-r--r--packages/Python/lldbsuite/test/macosx/safe-to-func-call/TestSafeFuncCalls.py63
-rw-r--r--packages/Python/lldbsuite/test/macosx/safe-to-func-call/main.c30
-rw-r--r--packages/Python/lldbsuite/test/macosx/universal/Makefile19
-rw-r--r--packages/Python/lldbsuite/test/macosx/universal/TestUniversal.py107
-rw-r--r--packages/Python/lldbsuite/test/macosx/universal/main.c7
-rw-r--r--packages/Python/lldbsuite/test/make/Makefile.rules600
-rw-r--r--packages/Python/lldbsuite/test/make/test_common.h19
-rw-r--r--packages/Python/lldbsuite/test/plugins/builder_base.py137
-rw-r--r--packages/Python/lldbsuite/test/plugins/builder_darwin.py21
-rw-r--r--packages/Python/lldbsuite/test/plugins/builder_freebsd.py4
-rw-r--r--packages/Python/lldbsuite/test/plugins/builder_linux2.py4
-rw-r--r--packages/Python/lldbsuite/test/plugins/builder_netbsd.py4
-rw-r--r--packages/Python/lldbsuite/test/plugins/builder_win32.py4
-rw-r--r--packages/Python/lldbsuite/test/python_api/.categories1
-rw-r--r--packages/Python/lldbsuite/test/python_api/breakpoint/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/python_api/breakpoint/TestBreakpointAPI.py45
-rw-r--r--packages/Python/lldbsuite/test/python_api/breakpoint/main.c14
-rw-r--r--packages/Python/lldbsuite/test/python_api/class_members/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/python_api/class_members/TestSBTypeClassMembers.py77
-rw-r--r--packages/Python/lldbsuite/test/python_api/class_members/main.mm47
-rw-r--r--packages/Python/lldbsuite/test/python_api/debugger/TestDebuggerAPI.py40
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/TestDefaultConstructorForAPIObjects.py395
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_address.py22
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_block.py17
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpoint.py36
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpointlocation.py28
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_broadcaster.py20
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_communication.py28
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_compileunit.py15
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_debugger.py56
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_error.py25
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_event.py17
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_filespec.py14
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_frame.py37
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_function.py19
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_instruction.py16
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_instructionlist.py17
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_lineentry.py14
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_listener.py23
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_module.py29
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_process.py49
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_section.py22
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_stringlist.py17
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbol.py16
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbolcontext.py15
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_target.py65
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_thread.py37
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_type.py22
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_value.py67
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_valuelist.py14
-rw-r--r--packages/Python/lldbsuite/test/python_api/default-constructor/sb_watchpoint.py21
-rw-r--r--packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassembleRawData.py39
-rw-r--r--packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassemble_VST1_64.py58
-rw-r--r--packages/Python/lldbsuite/test/python_api/event/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/python_api/event/TestEvents.py288
-rw-r--r--packages/Python/lldbsuite/test/python_api/event/main.c49
-rw-r--r--packages/Python/lldbsuite/test/python_api/exprpath_synthetic/TestExprPathSynthetic.py4
-rw-r--r--packages/Python/lldbsuite/test/python_api/exprpath_synthetic/main.mm20
-rw-r--r--packages/Python/lldbsuite/test/python_api/findvalue_duplist/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/python_api/findvalue_duplist/TestSBFrameFindValue.py50
-rw-r--r--packages/Python/lldbsuite/test/python_api/findvalue_duplist/main.cpp7
-rw-r--r--packages/Python/lldbsuite/test/python_api/formatters/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/python_api/formatters/TestFormattersSBAPI.py346
-rw-r--r--packages/Python/lldbsuite/test/python_api/formatters/main.cpp59
-rw-r--r--packages/Python/lldbsuite/test/python_api/formatters/synth.py105
-rw-r--r--packages/Python/lldbsuite/test/python_api/frame/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/python_api/frame/TestFrames.py207
-rw-r--r--packages/Python/lldbsuite/test/python_api/frame/inlines/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/python_api/frame/inlines/TestInlinedFrame.py79
-rw-r--r--packages/Python/lldbsuite/test/python_api/frame/inlines/inlines.c53
-rw-r--r--packages/Python/lldbsuite/test/python_api/frame/inlines/inlines.h4
-rw-r--r--packages/Python/lldbsuite/test/python_api/frame/main.c58
-rw-r--r--packages/Python/lldbsuite/test/python_api/function_symbol/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/python_api/function_symbol/TestDisasmAPI.py111
-rw-r--r--packages/Python/lldbsuite/test/python_api/function_symbol/TestSymbolAPI.py81
-rw-r--r--packages/Python/lldbsuite/test/python_api/function_symbol/main.c60
-rw-r--r--packages/Python/lldbsuite/test/python_api/hello_world/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/python_api/hello_world/TestHelloWorld.py147
-rw-r--r--packages/Python/lldbsuite/test/python_api/hello_world/main.c35
-rw-r--r--packages/Python/lldbsuite/test/python_api/interpreter/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/python_api/interpreter/TestCommandInterpreterAPI.py73
-rw-r--r--packages/Python/lldbsuite/test/python_api/interpreter/main.c6
-rw-r--r--packages/Python/lldbsuite/test/python_api/lldbutil/frame/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/python_api/lldbutil/frame/TestFrameUtils.py59
-rw-r--r--packages/Python/lldbsuite/test/python_api/lldbutil/frame/main.c47
-rw-r--r--packages/Python/lldbsuite/test/python_api/lldbutil/iter/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestLLDBIterator.py122
-rw-r--r--packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestRegistersIterator.py94
-rw-r--r--packages/Python/lldbsuite/test/python_api/lldbutil/iter/main.cpp134
-rw-r--r--packages/Python/lldbsuite/test/python_api/lldbutil/process/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/python_api/lldbutil/process/TestPrintStackTraces.py52
-rw-r--r--packages/Python/lldbsuite/test/python_api/lldbutil/process/main.cpp136
-rw-r--r--packages/Python/lldbsuite/test/python_api/module_section/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/python_api/module_section/TestModuleAndSection.py127
-rw-r--r--packages/Python/lldbsuite/test/python_api/module_section/b.cpp3
-rw-r--r--packages/Python/lldbsuite/test/python_api/module_section/c.cpp3
-rw-r--r--packages/Python/lldbsuite/test/python_api/module_section/main.cpp136
-rw-r--r--packages/Python/lldbsuite/test/python_api/objc_type/Makefile9
-rw-r--r--packages/Python/lldbsuite/test/python_api/objc_type/TestObjCType.py64
-rw-r--r--packages/Python/lldbsuite/test/python_api/objc_type/main.m52
-rw-r--r--packages/Python/lldbsuite/test/python_api/process/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/python_api/process/TestProcessAPI.py289
-rw-r--r--packages/Python/lldbsuite/test/python_api/process/io/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/python_api/process/io/TestProcessIO.py206
-rw-r--r--packages/Python/lldbsuite/test/python_api/process/io/main.c19
-rw-r--r--packages/Python/lldbsuite/test/python_api/process/main.cpp31
-rw-r--r--packages/Python/lldbsuite/test/python_api/rdar-12481949/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/python_api/rdar-12481949/Test-rdar-12481949.py54
-rw-r--r--packages/Python/lldbsuite/test/python_api/rdar-12481949/main.cpp17
-rw-r--r--packages/Python/lldbsuite/test/python_api/sbdata/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/python_api/sbdata/TestSBData.py348
-rw-r--r--packages/Python/lldbsuite/test/python_api/sbdata/main.cpp43
-rw-r--r--packages/Python/lldbsuite/test/python_api/sbtype_typeclass/TestSBTypeTypeClass.py4
-rw-r--r--packages/Python/lldbsuite/test/python_api/sbtype_typeclass/main.m34
-rw-r--r--packages/Python/lldbsuite/test/python_api/sbvalue_const_addrof/Makefile4
-rw-r--r--packages/Python/lldbsuite/test/python_api/sbvalue_const_addrof/TestSBValueConstAddrOf.py3
-rw-r--r--packages/Python/lldbsuite/test/python_api/sbvalue_const_addrof/main.cpp40
-rw-r--r--packages/Python/lldbsuite/test/python_api/sbvalue_persist/Makefile15
-rw-r--r--packages/Python/lldbsuite/test/python_api/sbvalue_persist/TestSBValuePersist.py74
-rw-r--r--packages/Python/lldbsuite/test/python_api/sbvalue_persist/main.cpp14
-rw-r--r--packages/Python/lldbsuite/test/python_api/section/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/python_api/section/TestSectionAPI.py41
-rw-r--r--packages/Python/lldbsuite/test/python_api/section/main.c28
-rw-r--r--packages/Python/lldbsuite/test/python_api/signals/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/python_api/signals/TestSignalsAPI.py47
-rw-r--r--packages/Python/lldbsuite/test/python_api/signals/main.cpp28
-rw-r--r--packages/Python/lldbsuite/test/python_api/symbol-context/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/python_api/symbol-context/TestSymbolContext.py89
-rw-r--r--packages/Python/lldbsuite/test/python_api/symbol-context/main.c51
-rw-r--r--packages/Python/lldbsuite/test/python_api/target/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/python_api/target/TestTargetAPI.py372
-rw-r--r--packages/Python/lldbsuite/test/python_api/target/main.c60
-rw-r--r--packages/Python/lldbsuite/test/python_api/thread/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/python_api/thread/TestThreadAPI.py245
-rw-r--r--packages/Python/lldbsuite/test/python_api/thread/main.cpp26
-rw-r--r--packages/Python/lldbsuite/test/python_api/thread/main2.cpp54
-rw-r--r--packages/Python/lldbsuite/test/python_api/type/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/python_api/type/TestTypeList.py116
-rw-r--r--packages/Python/lldbsuite/test/python_api/type/main.cpp60
-rw-r--r--packages/Python/lldbsuite/test/python_api/value/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/python_api/value/TestValueAPI.py135
-rw-r--r--packages/Python/lldbsuite/test/python_api/value/change_values/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/python_api/value/change_values/TestChangeValueAPI.py148
-rw-r--r--packages/Python/lldbsuite/test/python_api/value/change_values/main.c29
-rw-r--r--packages/Python/lldbsuite/test/python_api/value/linked_list/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/python_api/value/linked_list/TestValueAPILinkedList.py133
-rw-r--r--packages/Python/lldbsuite/test/python_api/value/linked_list/main.cpp56
-rw-r--r--packages/Python/lldbsuite/test/python_api/value/main.c52
-rw-r--r--packages/Python/lldbsuite/test/python_api/value_var_update/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/python_api/value_var_update/TestValueVarUpdate.py59
-rw-r--r--packages/Python/lldbsuite/test/python_api/value_var_update/main.c15
-rw-r--r--packages/Python/lldbsuite/test/python_api/watchpoint/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/python_api/watchpoint/TestSetWatchpoint.py93
-rw-r--r--packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIgnoreCount.py89
-rw-r--r--packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIter.py115
-rw-r--r--packages/Python/lldbsuite/test/python_api/watchpoint/condition/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/python_api/watchpoint/condition/TestWatchpointConditionAPI.py89
-rw-r--r--packages/Python/lldbsuite/test/python_api/watchpoint/condition/main.cpp28
-rw-r--r--packages/Python/lldbsuite/test/python_api/watchpoint/main.c24
-rw-r--r--packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/Makefile6
-rw-r--r--packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestSetWatchlocation.py90
-rw-r--r--packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestTargetWatchAddress.py130
-rw-r--r--packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/main.cpp104
-rw-r--r--packages/Python/lldbsuite/test/redo.py195
-rw-r--r--packages/Python/lldbsuite/test/result_formatter.py1304
-rw-r--r--packages/Python/lldbsuite/test/settings/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/settings/TestSettings.py495
-rw-r--r--packages/Python/lldbsuite/test/settings/main.cpp75
-rw-r--r--packages/Python/lldbsuite/test/settings/quoting/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/settings/quoting/TestQuoting.py92
-rw-r--r--packages/Python/lldbsuite/test/settings/quoting/main.c13
-rw-r--r--packages/Python/lldbsuite/test/source-manager/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/source-manager/TestSourceManager.py172
-rw-r--r--packages/Python/lldbsuite/test/source-manager/hidden/.keep0
-rw-r--r--packages/Python/lldbsuite/test/source-manager/main.c6
-rw-r--r--packages/Python/lldbsuite/test/terminal/TestSTTYBeforeAndAfter.py121
-rw-r--r--packages/Python/lldbsuite/test/test_categories.py70
-rw-r--r--packages/Python/lldbsuite/test/test_result.py224
-rw-r--r--packages/Python/lldbsuite/test/test_runner/README.txt5
-rw-r--r--packages/Python/lldbsuite/test/test_runner/lib/lldb_utils.py66
-rw-r--r--packages/Python/lldbsuite/test/test_runner/lib/process_control.py705
-rwxr-xr-xpackages/Python/lldbsuite/test/test_runner/test/inferior.py146
-rwxr-xr-xpackages/Python/lldbsuite/test/test_runner/test/process_control_tests.py235
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/TestMiExit.py84
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/TestMiFile.py77
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/TestMiGdbSetShow.py190
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/TestMiLibraryLoaded.py33
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/TestMiPrompt.py54
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/breakpoint/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/breakpoint/TestMiBreak.py246
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/breakpoint/main.cpp27
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/control/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/control/TestMiExec.py457
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/control/main.cpp33
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/data/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/data/TestMiData.py337
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/data/main.cpp59
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/TestMiCliSupport.py206
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/TestMiInterpreterExec.py229
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/main.cpp19
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/lldbmi_testcase.py54
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/main.cpp19
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/signal/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/signal/TestMiSignal.py197
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/signal/main.cpp33
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/stack/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/stack/TestMiStack.py479
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/stack/main.cpp127
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/TestMiStartupOptions.py290
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/main.cpp15
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/start_script5
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/start_script_error2
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/start_script_exit7
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/symbol/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/symbol/TestMiSymbol.py81
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/symbol/main.cpp18
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/symbol/symbol_list_lines_inline_test.cpp39
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/symbol/symbol_list_lines_inline_test.h24
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/symbol/symbol_list_lines_inline_test2.cpp38
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/syntax/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/syntax/TestMiSyntax.py80
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/syntax/main.cpp17
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/target/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/target/TestMiTarget.py125
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/target/test_attach.cpp21
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/variable/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/variable/TestMiGdbSetShowPrint.py227
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/variable/TestMiVar.py396
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-mi/variable/main.cpp152
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/TestGDBRemoteMemoryRead.py41
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAttach.py60
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAuxvSupport.py201
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteExpeditedRegisters.py144
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteKill.py53
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteProcessInfo.py179
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteRegisterState.py126
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteSingleStep.py25
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteThreadsInStopReply.py164
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_qThreadStopInfo.py150
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_vCont.py116
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/TestLldbGdbServer.py1473
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubReverseConnect.py87
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubSetSID.py82
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py1299
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/Makefile8
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteAbort.py42
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteSegFault.py40
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/main.cpp39
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/lldbgdbserverutils.py843
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/main.cpp404
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/TestPlatformProcessConnect.py56
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/main.cpp7
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/socket_packet_pump.py187
-rw-r--r--packages/Python/lldbsuite/test/tools/lldb-server/test/test_lldbgdbserverutils.py49
-rw-r--r--packages/Python/lldbsuite/test/types/AbstractBase.py259
-rw-r--r--packages/Python/lldbsuite/test/types/HideTestFailures.py78
-rw-r--r--packages/Python/lldbsuite/test/types/Makefile7
-rw-r--r--packages/Python/lldbsuite/test/types/TestFloatTypes.py41
-rw-r--r--packages/Python/lldbsuite/test/types/TestFloatTypesExpr.py44
-rw-r--r--packages/Python/lldbsuite/test/types/TestIntegerTypes.py113
-rw-r--r--packages/Python/lldbsuite/test/types/TestIntegerTypesExpr.py113
-rw-r--r--packages/Python/lldbsuite/test/types/TestRecursiveTypes.py51
-rw-r--r--packages/Python/lldbsuite/test/types/basic_type.cpp211
-rw-r--r--packages/Python/lldbsuite/test/types/char.cpp9
-rw-r--r--packages/Python/lldbsuite/test/types/double.cpp9
-rw-r--r--packages/Python/lldbsuite/test/types/float.cpp9
-rw-r--r--packages/Python/lldbsuite/test/types/int.cpp9
-rw-r--r--packages/Python/lldbsuite/test/types/long.cpp18
-rw-r--r--packages/Python/lldbsuite/test/types/long_long.cpp18
-rw-r--r--packages/Python/lldbsuite/test/types/recursive_type_1.cpp12
-rw-r--r--packages/Python/lldbsuite/test/types/recursive_type_2.cpp10
-rw-r--r--packages/Python/lldbsuite/test/types/recursive_type_main.cpp8
-rw-r--r--packages/Python/lldbsuite/test/types/short.cpp9
-rw-r--r--packages/Python/lldbsuite/test/types/unsigned_char.cpp9
-rw-r--r--packages/Python/lldbsuite/test/types/unsigned_int.cpp9
-rw-r--r--packages/Python/lldbsuite/test/types/unsigned_long.cpp18
-rw-r--r--packages/Python/lldbsuite/test/types/unsigned_long_long.cpp18
-rw-r--r--packages/Python/lldbsuite/test/types/unsigned_short.cpp9
-rw-r--r--packages/Python/lldbsuite/test/warnings/uuid/Makefile5
-rw-r--r--packages/Python/lldbsuite/test/warnings/uuid/TestAddDsymCommand.py107
-rw-r--r--packages/Python/lldbsuite/test/warnings/uuid/main.cpp.template19
-rw-r--r--packages/Python/lldbsuite/test/xunit_formatter.py565
1563 files changed, 103123 insertions, 0 deletions
diff --git a/packages/Python/lldbsuite/__init__.py b/packages/Python/lldbsuite/__init__.py
new file mode 100644
index 000000000000..aa6874e78bc2
--- /dev/null
+++ b/packages/Python/lldbsuite/__init__.py
@@ -0,0 +1,28 @@
+# Module level initialization for the `lldbsuite` module.
+
+import inspect
+import os
+import sys
+
+def find_lldb_root():
+ lldb_root = os.path.dirname(inspect.getfile(inspect.currentframe()))
+ while True:
+ lldb_root = os.path.dirname(lldb_root)
+ if lldb_root is None:
+ return None
+
+ test_path = os.path.join(lldb_root, "use_lldb_suite_root.py")
+ if os.path.isfile(test_path):
+ return lldb_root
+ return None
+
+# lldbsuite.lldb_root refers to the root of the git/svn source checkout
+lldb_root = find_lldb_root()
+
+# lldbsuite.lldb_test_root refers to the root of the python test tree
+lldb_test_root = os.path.join(
+ lldb_root,
+ "packages",
+ "Python",
+ "lldbsuite",
+ "test")
diff --git a/packages/Python/lldbsuite/support/__init__.py b/packages/Python/lldbsuite/support/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
--- /dev/null
+++ b/packages/Python/lldbsuite/support/__init__.py
diff --git a/packages/Python/lldbsuite/support/fs.py b/packages/Python/lldbsuite/support/fs.py
new file mode 100644
index 000000000000..9a56808369de
--- /dev/null
+++ b/packages/Python/lldbsuite/support/fs.py
@@ -0,0 +1,64 @@
+"""
+ The LLVM Compiler Infrastructure
+
+This file is distributed under the University of Illinois Open Source
+License. See LICENSE.TXT for details.
+
+Prepares language bindings for LLDB build process. Run with --help
+to see a description of the supported command line arguments.
+"""
+
+# Python modules:
+import os
+import platform
+import sys
+
+
+def _find_file_in_paths(paths, exe_basename):
+ """Returns the full exe path for the first path match.
+
+ @params paths the list of directories to search for the exe_basename
+ executable
+ @params exe_basename the name of the file for which to search.
+ e.g. "swig" or "swig.exe".
+
+ @return the full path to the executable if found in one of the
+ given paths; otherwise, returns None.
+ """
+ for path in paths:
+ trial_exe_path = os.path.join(path, exe_basename)
+ if os.path.exists(trial_exe_path):
+ return os.path.normcase(trial_exe_path)
+ return None
+
+def find_executable(executable):
+ """Finds the specified executable in the PATH or known good locations."""
+
+ # Figure out what we're looking for.
+ if platform.system() == "Windows":
+ executable = executable + ".exe"
+ extra_dirs = []
+ else:
+ extra_dirs = ["/usr/local/bin"]
+
+ # Figure out what paths to check.
+ path_env = os.environ.get("PATH", None)
+ if path_env is not None:
+ paths_to_check = path_env.split(os.path.pathsep)
+ else:
+ paths_to_check = []
+
+ # Add in the extra dirs
+ paths_to_check.extend(extra_dirs)
+ if len(paths_to_check) < 1:
+ raise os.OSError(
+ "executable was not specified, PATH has no "
+ "contents, and there are no extra directories to search")
+
+ result = _find_file_in_paths(paths_to_check, executable)
+
+ if not result or len(result) < 1:
+ raise os.OSError(
+ "failed to find exe='%s' in paths='%s'" % (executable, paths_to_check))
+ return result
+
diff --git a/packages/Python/lldbsuite/support/seven.py b/packages/Python/lldbsuite/support/seven.py
new file mode 100644
index 000000000000..56ddd8db3f66
--- /dev/null
+++ b/packages/Python/lldbsuite/support/seven.py
@@ -0,0 +1,20 @@
+import six
+
+if six.PY2:
+ import commands
+ get_command_output = commands.getoutput
+ get_command_status_output = commands.getstatusoutput
+
+ cmp_ = cmp
+else:
+ def get_command_status_output(command):
+ try:
+ import subprocess
+ return (0, subprocess.check_output(command, shell=True, universal_newlines=True))
+ except subprocess.CalledProcessError as e:
+ return (e.returncode, e.output)
+
+ def get_command_output(command):
+ return get_command_status_output(command)[1]
+
+ cmp_ = lambda x, y: (x > y) - (x < y) \ No newline at end of file
diff --git a/packages/Python/lldbsuite/support/sockutil.py b/packages/Python/lldbsuite/support/sockutil.py
new file mode 100644
index 000000000000..b3d81d14884a
--- /dev/null
+++ b/packages/Python/lldbsuite/support/sockutil.py
@@ -0,0 +1,23 @@
+"""
+ The LLVM Compiler Infrastructure
+
+This file is distributed under the University of Illinois Open Source
+License. See LICENSE.TXT for details.
+
+Helper functions for working with sockets.
+"""
+
+# Python modules:
+import io
+import socket
+
+# LLDB modules
+import use_lldb_suite
+
+def recvall(sock, size):
+ bytes = io.BytesIO()
+ while size > 0:
+ this_result = sock.recv(size)
+ bytes.write(this_result)
+ size -= len(this_result)
+ return bytes.getvalue()
diff --git a/packages/Python/lldbsuite/test/.categories b/packages/Python/lldbsuite/test/.categories
new file mode 100644
index 000000000000..e69de29bb2d1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/.categories
diff --git a/packages/Python/lldbsuite/test/Makefile b/packages/Python/lldbsuite/test/Makefile
new file mode 100644
index 000000000000..4d08ef39d4db
--- /dev/null
+++ b/packages/Python/lldbsuite/test/Makefile
@@ -0,0 +1,33 @@
+LLDB_LEVEL := ..
+include $(LLDB_LEVEL)/Makefile
+
+.PHONY: programs
+
+all:: check-local
+
+#----------------------------------------------------------------------
+# Make all of the test programs
+#----------------------------------------------------------------------
+programs:
+ find . -type d -depth 1 | xargs -J % find % \
+ -name Makefile \
+ -exec echo \; \
+ -exec echo make -f '{}' \; \
+ -execdir make \;
+
+#----------------------------------------------------------------------
+# Clean all of the test programs
+#----------------------------------------------------------------------
+clean::
+ find . -type d -depth 1 | xargs -J % find % \
+ -name Makefile \
+ -exec echo \; \
+ -exec echo make -f '{}' clean \; \
+ -execdir make clean \;
+
+#----------------------------------------------------------------------
+# Run the tests
+#----------------------------------------------------------------------
+check-local::
+ rm -rf lldb-test-traces
+ python $(PROJ_SRC_DIR)/dotest.py --executable $(ToolDir)/lldb -q -s lldb-test-traces -u CXXFLAGS -u CFLAGS -C $(subst ccache,,$(CC))
diff --git a/packages/Python/lldbsuite/test/README-TestSuite b/packages/Python/lldbsuite/test/README-TestSuite
new file mode 100644
index 000000000000..6df4d7bd7be7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/README-TestSuite
@@ -0,0 +1,159 @@
+This README file describes the files and directories related to the Python test
+suite under the current 'test' directory.
+
+o dotest.py
+
+ Provides the test driver for the test suite. To invoke it, cd to the 'test'
+ directory and issue the './dotest.py' command or './dotest.py -v' for more
+ verbose output. '.dotest.py -h' prints out the help messge.
+
+ A specific naming pattern is followed by the .py script under the 'test'
+ directory in order to be recognized by 'dotest.py' test driver as a module
+ which implements a test case, namely, Test*.py.
+
+ Some example usages:
+
+ 1. ./dotest.py -v . 2> ~/Developer/Log/lldbtest.log0
+ This runs the test suite and directs the run log to a file.
+
+ 2. LLDB_LOG=/tmp/lldb.log GDB_REMOTE_LOG=/tmp/gdb-remote.log ./dotest.py -v . 2> ~/Developer/Log/lldbtest.log
+ This runs the test suite, with logging turned on for the lldb as well as
+ the process.gdb-remote channels and directs the run log to a file.
+
+o lldbtest.py
+
+ Provides an abstract base class of lldb test case named 'TestBase', which in
+ turn inherits from Python's unittest.TestCase. The concrete subclass can
+ override lldbtest.TestBase in order to inherit the common behavior for
+ unittest.TestCase.setUp/tearDown implemented in this file.
+
+ To provide a test case, the concrete subclass provides methods whose names
+ start with the letters test. For more details about the Python's unittest
+ framework, go to http://docs.python.org/library/unittest.html.
+
+ ./command_source/TestCommandSource.py provides a simple example of test case
+ which overrides lldbtest.TestBase to exercise the lldb's 'command source'
+ command. The subclass should override the attribute 'mydir' in order for the
+ runtime to locate the individual test cases when running as part of a large
+ test suite or when running each test case as a separate Python invocation.
+
+ The doc string provides more details about the setup required for running a
+ test case on its own. To run the whole test suite, 'dotest.py' is all you
+ need to do.
+
+o subdirectories of 'test'
+
+ Most of them predate the introduction of the python test suite and contain
+ example C/C++/ObjC source files which get compiled into executables which are
+ to be exercised by the debugger.
+
+ For such subdirectory which has an associated Test*.py file, it was added as
+ part of the Python-based test suite to test lldb functionality.
+
+ Some of the subdirectories, for example, the 'help' subdirectory, do not have
+ C/C++/ObjC source files; they were created to house the Python test case which
+ does not involve lldb reading in an executable file at all.
+
+o make directory
+
+ Contains Makefile.rules, which can be utilized by test cases to write Makefile
+ based rules to build binaries for the inferiors.
+
+ By default, the built executable name is a.out, which can be overwritten by
+ specifying your EXE make variable, via the Makefile under the specific test
+ directory or via supplying a Python dictionary to the build method in your
+ Python test script. An example of the latter can be found in
+ test/lang/objc/radar-9691614/TestObjCMethodReturningBOOL.py, where:
+
+ def test_method_ret_BOOL_with_dsym(self):
+ """Test that objective-c method returning BOOL works correctly."""
+ d = {'EXE': self.exe_name}
+ self.buildDsym(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ self.objc_method_ret_BOOL(self.exe_name)
+
+ def test_method_ret_BOOL_with_dwarf(self):
+ """Test that objective-c method returning BOOL works correctly."""
+ d = {'EXE': self.exe_name}
+ self.buildDwarf(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ self.objc_method_ret_BOOL(self.exe_name)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # We'll use the test method name as the exe_name.
+ self.exe_name = self.testMethodName
+ # Find the line number to break inside main().
+ self.main_source = "main.m"
+ self.line = line_number(self.main_source, '// Set breakpoint here.')
+
+ The exe names for the two test methods are equal to the test method names and
+ are therefore guaranteed different.
+
+o plugins directory
+
+ Contains platform specific plugin to build binaries with dsym/dwarf debugging
+ info. Other platform specific functionalities may be added in the future.
+
+o unittest2 directory
+
+ Many new features were added to unittest in Python 2.7, including test
+ discovery. unittest2 allows you to use these features with earlier versions of
+ Python.
+
+ It currently has unittest2 0.5.1 from http://pypi.python.org/pypi/unittest2.
+ Version 0.5.1 of unittest2 has feature parity with unittest in Python 2.7
+ final. If you want to ensure that your tests run identically under unittest2
+ and unittest in Python 2.7 you should use unittest2 0.5.1.
+
+ Later versions of unittest2 include changes in unittest made in Python 3.2 and
+ onwards after the release of Python 2.7.
+
+o dotest.pl
+
+ In case you wonder, there is also a 'dotest.pl' perl script file. It was
+ created to visit each Python test case under the specified directory and
+ invoke Python's builtin unittest.main() on each test case.
+
+ It does not take advantage of the test runner and test suite functionality
+ provided by Python's unitest framework. Its existence is because we want a
+ different way of running the whole test suite. As lldb and the Python test
+ suite become more reliable, we don't expect to be using 'dotest.pl' anymore.
+
+ Note: dotest.pl has been moved to the attic directory.
+
+o Profiling dotest.py runs
+
+ I used the following command line thingy to do the profiling on a SnowLeopard
+ machine:
+
+$ DOTEST_PROFILE=YES DOTEST_SCRIPT_DIR=/Volumes/data/lldb/svn/trunk/test /System/Library/Frameworks/Python.framework/Versions/Current/lib/python2.6/cProfile.py -o my.profile ./dotest.py -v -w 2> ~/Developer/Log/lldbtest.log
+
+ After that, I used the pstats.py module to browse the statistics:
+
+$ python /System/Library/Frameworks/Python.framework/Versions/Current/lib/python2.6/pstats.py my.profile
+
+o Writing test cases:
+
+ We strongly prefer writing test cases using the SB API's rather than the runCmd & expect.
+ Unless you are actually testing some feature of the command line, please don't write
+ command based tests. For historical reasons there are plenty of examples of tests in the
+ test suite that use runCmd where they shouldn't, but don't copy them, copy the plenty that
+ do use the SB API's instead.
+
+ The reason for this is that our policy is that we will maintain compatibility with the
+ SB API's. But we don't make any similar guarantee about the details of command result format.
+ If your test is using the command line, it is going to have to check against the command result
+ text, and you either end up writing your check pattern by checking as little as possible so
+ you won't be exposed to random changes in the text; in which case you can end up missing some
+ failure, or you test too much and it means irrelevant changes break your tests.
+
+ However, if you use the Python API's it is possible to check all the results you want
+ to check in a very explicit way, which makes the tests much more robust.
+
+ Even if you are testing that a command-line command does some specific thing, it is still
+ better in general to use the SB API's to drive to the point where you want to run the test,
+ then use SBInterpreter::HandleCommand to run the command. You get the full result text
+ from the command in the command return object, and all the part where you are driving the
+ debugger to the point you want to test will be more robust.
diff --git a/packages/Python/lldbsuite/test/__init__.py b/packages/Python/lldbsuite/test/__init__.py
new file mode 100644
index 000000000000..93971c2f2364
--- /dev/null
+++ b/packages/Python/lldbsuite/test/__init__.py
@@ -0,0 +1,7 @@
+# Module level initialization for the `lldbsuite.test` module.
+
+from __future__ import absolute_import
+
+from . import dotest
+
+run_suite = dotest.run_suite
diff --git a/packages/Python/lldbsuite/test/android/platform/Makefile b/packages/Python/lldbsuite/test/android/platform/Makefile
new file mode 100644
index 000000000000..22e42c5a776e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/android/platform/Makefile
@@ -0,0 +1,4 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/android/platform/TestDefaultCacheLineSize.py b/packages/Python/lldbsuite/test/android/platform/TestDefaultCacheLineSize.py
new file mode 100644
index 000000000000..b925afe1b70c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/android/platform/TestDefaultCacheLineSize.py
@@ -0,0 +1,38 @@
+"""
+Verify the default cache line size for android targets
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class DefaultCacheLineSizeTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipUnlessPlatform(['android'])
+ def test_cache_line_size(self):
+ self.build(dictionary=self.getBuildFlags())
+ exe = os.path.join(os.getcwd(), "a.out")
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target and target.IsValid(), "Target is valid")
+
+ breakpoint = target.BreakpointCreateByName("main")
+ self.assertTrue(breakpoint and breakpoint.IsValid(), "Breakpoint is valid")
+
+ # Run the program.
+ process = target.LaunchSimple(None, None, self.get_process_working_directory())
+ self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID)
+ self.assertEqual(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED)
+
+ # check the setting value
+ self.expect("settings show target.process.memory-cache-line-size", patterns=[" = 2048"])
+
+ # Run to completion.
+ process.Continue()
+ self.assertEqual(process.GetState(), lldb.eStateExited, PROCESS_EXITED)
diff --git a/packages/Python/lldbsuite/test/android/platform/main.cpp b/packages/Python/lldbsuite/test/android/platform/main.cpp
new file mode 100644
index 000000000000..3fb9edc47270
--- /dev/null
+++ b/packages/Python/lldbsuite/test/android/platform/main.cpp
@@ -0,0 +1,13 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+int main ()
+{
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/api/check_public_api_headers/Makefile b/packages/Python/lldbsuite/test/api/check_public_api_headers/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/api/check_public_api_headers/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/api/check_public_api_headers/TestPublicAPIHeaders.py b/packages/Python/lldbsuite/test/api/check_public_api_headers/TestPublicAPIHeaders.py
new file mode 100644
index 000000000000..0d0507f1d70c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/api/check_public_api_headers/TestPublicAPIHeaders.py
@@ -0,0 +1,88 @@
+"""Test the integrity of the lldb public api directory containing SB*.h headers.
+
+There should be nothing unwanted there and a simpe main.cpp which includes SB*.h
+should compile and link with the LLDB framework."""
+
+from __future__ import print_function
+
+
+
+import os, re
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class SBDirCheckerCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ TestBase.setUp(self)
+ self.template = 'main.cpp.template'
+ self.source = 'main.cpp'
+ self.exe_name = 'a.out'
+
+ @skipIfNoSBHeaders
+ def test_sb_api_directory(self):
+ """Test the SB API directory and make sure there's no unwanted stuff."""
+
+ # Only proceed if this is an Apple OS, "x86_64", and local platform.
+ if not (self.platformIsDarwin() and self.getArchitecture() == "x86_64"):
+ self.skipTest("This test is only for LLDB.framework built 64-bit")
+ if self.getArchitecture() == "i386":
+ self.skipTest("LLDB is 64-bit and cannot be linked to 32-bit test program.")
+
+ # Generate main.cpp, build it, and execute.
+ self.generate_main_cpp()
+ self.buildDriver(self.source, self.exe_name)
+ self.sanity_check_executable(self.exe_name)
+
+ def generate_main_cpp(self):
+ """Generate main.cpp from main.cpp.template."""
+ temp = os.path.join(os.getcwd(), self.template)
+ with open(temp, 'r') as f:
+ content = f.read()
+
+ public_api_dir = os.path.join(os.environ["LLDB_SRC"], "include", "lldb", "API")
+
+ # Look under the include/lldb/API directory and add #include statements
+ # for all the SB API headers.
+ public_headers = os.listdir(public_api_dir)
+ # For different platforms, the include statement can vary.
+ if self.platformIsDarwin():
+ include_stmt = "'#include <%s>' % os.path.join('LLDB', header)"
+ if self.getPlatform() == "freebsd" or self.getPlatform() == "linux" or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
+ include_stmt = "'#include <%s>' % os.path.join(public_api_dir, header)"
+ list = [eval(include_stmt) for header in public_headers if (header.startswith("SB") and
+ header.endswith(".h"))]
+ includes = '\n'.join(list)
+ new_content = content.replace('%include_SB_APIs%', includes)
+ src = os.path.join(os.getcwd(), self.source)
+ with open(src, 'w') as f:
+ f.write(new_content)
+
+ # The main.cpp has been generated, add a teardown hook to remove it.
+ self.addTearDownHook(lambda: os.remove(src))
+
+ def sanity_check_executable(self, exe_name):
+ """Sanity check executable compiled from the auto-generated program."""
+ exe = os.path.join(os.getcwd(), exe_name)
+ self.runCmd("file %s" % exe, CURRENT_EXECUTABLE_SET)
+
+ self.line_to_break = line_number(self.source, '// Set breakpoint here.')
+
+ env_cmd = "settings set target.env-vars %s=%s" %(self.dylibPath, self.getLLDBLibraryEnvVal())
+ if self.TraceOn():
+ print("Set environment to: ", env_cmd)
+ self.runCmd(env_cmd)
+ self.addTearDownHook(lambda: self.dbg.HandleCommand("settings remove target.env-vars %s" % self.dylibPath))
+
+ lldbutil.run_break_set_by_file_and_line (self, self.source, self.line_to_break, num_expected_locations = -1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ self.runCmd('frame variable')
diff --git a/packages/Python/lldbsuite/test/api/check_public_api_headers/main.cpp.template b/packages/Python/lldbsuite/test/api/check_public_api_headers/main.cpp.template
new file mode 100644
index 000000000000..ed754add6100
--- /dev/null
+++ b/packages/Python/lldbsuite/test/api/check_public_api_headers/main.cpp.template
@@ -0,0 +1,24 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+%include_SB_APIs%
+
+using namespace lldb;
+int
+main(int argc, char const *argv[])
+{
+ SBDebugger::Initialize();
+ SBDebugger dbg = SBDebugger::Create();
+
+ printf("Hello SBDebugger %llu\n", dbg.GetID()); // Set breakpoint here.
+
+ SBDebugger::Terminate();
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/api/multiple-debuggers/.categories b/packages/Python/lldbsuite/test/api/multiple-debuggers/.categories
new file mode 100644
index 000000000000..6e70196ccd70
--- /dev/null
+++ b/packages/Python/lldbsuite/test/api/multiple-debuggers/.categories
@@ -0,0 +1 @@
+stresstest
diff --git a/packages/Python/lldbsuite/test/api/multiple-debuggers/Makefile b/packages/Python/lldbsuite/test/api/multiple-debuggers/Makefile
new file mode 100644
index 000000000000..08f8850e3e8f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/api/multiple-debuggers/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../make
+
+MAKE_DSYM := NO
+
+ENABLE_THREADS := YES
+CXX_SOURCES := multi-process-driver.cpp testprog.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/api/multiple-debuggers/TestMultipleDebuggers.py b/packages/Python/lldbsuite/test/api/multiple-debuggers/TestMultipleDebuggers.py
new file mode 100644
index 000000000000..67dca2273d8a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/api/multiple-debuggers/TestMultipleDebuggers.py
@@ -0,0 +1,44 @@
+"""Test the lldb public C++ api when doing multiple debug sessions simultaneously."""
+
+from __future__ import print_function
+
+
+
+import os, re
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+import lldb
+import subprocess
+
+class TestMultipleSimultaneousDebuggers(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfi386
+ @skipIfNoSBHeaders
+ @expectedFailureFreeBSD("llvm.org/pr20282")
+ @expectedFailureLinux("llvm.org/pr20282")
+ @expectedFailureWindows # Test crashes
+ @expectedFlakeyDarwin()
+ def test_multiple_debuggers(self):
+ env = {self.dylibPath : self.getLLDBLibraryEnvVal()}
+
+ self.driver_exe = os.path.join(os.getcwd(), "multi-process-driver")
+ self.buildDriver('multi-process-driver.cpp', self.driver_exe)
+ self.addTearDownHook(lambda: os.remove(self.driver_exe))
+ self.signBinary(self.driver_exe)
+
+ self.inferior_exe = os.path.join(os.getcwd(), "testprog")
+ self.buildDriver('testprog.cpp', self.inferior_exe)
+ self.addTearDownHook(lambda: os.remove(self.inferior_exe))
+
+# check_call will raise a CalledProcessError if multi-process-driver doesn't return
+# exit code 0 to indicate success. We can let this exception go - the test harness
+# will recognize it as a test failure.
+
+ if self.TraceOn():
+ print("Running test %s" % self.driver_exe)
+ check_call([self.driver_exe, self.inferior_exe], env=env)
+ else:
+ with open(os.devnull, 'w') as fnull:
+ check_call([self.driver_exe, self.inferior_exe], env=env, stdout=fnull, stderr=fnull)
diff --git a/packages/Python/lldbsuite/test/api/multiple-debuggers/multi-process-driver.cpp b/packages/Python/lldbsuite/test/api/multiple-debuggers/multi-process-driver.cpp
new file mode 100644
index 000000000000..1c2689ff6c4f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/api/multiple-debuggers/multi-process-driver.cpp
@@ -0,0 +1,283 @@
+
+// This program creates NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS of pthreads,
+// creates an lldb Debugger on each thread, creates targets, inserts two
+// breakpoints, runs to the first breakpoint, backtraces, runs to the second
+// breakpoint, backtraces, kills the inferior process, closes down the
+// debugger.
+
+// The main thread keeps track of which pthreads have completed and which
+// pthreads have completed successfully, and exits when all pthreads have
+// completed successfully, or our time limit has been exceeded.
+
+// This test file helps to uncover race conditions and locking mistakes
+// that are hit when lldb is being used to debug multiple processes
+// simultaneously.
+
+#include <stdio.h>
+#include <stdlib.h>
+
+
+#include "lldb/API/LLDB.h"
+#include "lldb/API/SBCommandInterpreter.h"
+#include "lldb/API/SBCommandReturnObject.h"
+#include "lldb/API/SBDebugger.h"
+
+#include <chrono>
+#include <thread>
+
+#define NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS 20
+
+#define DEBUG 0
+
+using namespace lldb;
+
+bool *completed_threads_array = 0;
+bool *successful_threads_array = 0;
+
+const char *inferior_process_name = "testprog";
+
+bool
+wait_for_stop_event (SBProcess process, SBListener listener)
+{
+ bool stopped = false;
+ while (!stopped)
+ {
+ SBEvent event;
+ bool waitfor_ret = listener.WaitForEvent (2, event);
+ if (event.GetType() == SBProcess::eBroadcastBitStateChanged)
+ {
+ if (process.GetState() == StateType::eStateStopped
+ || process.GetState() == StateType::eStateCrashed
+ || process.GetState() == StateType::eStateDetached
+ || process.GetState() == StateType::eStateExited)
+ {
+ stopped = true;
+ }
+ }
+ }
+ return stopped;
+}
+
+bool
+walk_stack_to_main (SBThread thread)
+{
+ if (thread.IsValid() == 0)
+ {
+ return false;
+ }
+
+ bool found_main = false;
+ uint32_t curr_frame = 0;
+ const uint32_t framecount = thread.GetNumFrames();
+ while (!found_main && curr_frame < framecount)
+ {
+ SBFrame frame = thread.GetFrameAtIndex (curr_frame);
+ if (strcmp (frame.GetFunctionName(), "main") == 0)
+ {
+ found_main = true;
+ break;
+ }
+ curr_frame += 1;
+ }
+ return found_main;
+}
+
+void *do_one_debugger (void *in)
+{
+ uint64_t threadnum = (uint64_t) in;
+
+#if defined (__APPLE__)
+ char *threadname;
+ asprintf (&threadname, "thread #%lld", threadnum);
+ pthread_setname_np (threadname);
+ free (threadname);
+#endif
+
+#if DEBUG == 1
+ printf ("#%lld: Starting debug session\n", threadnum);
+#endif
+
+ SBDebugger debugger = lldb::SBDebugger::Create (false);
+ if (debugger.IsValid ())
+ {
+ debugger.SetAsync (true);
+ SBTarget target = debugger.CreateTargetWithFileAndArch(inferior_process_name, "x86_64");
+ SBCommandInterpreter command_interp = debugger.GetCommandInterpreter();
+ if (target.IsValid())
+ {
+ SBBreakpoint bar_br = target.BreakpointCreateByName ("bar", "testprog");
+ if (!bar_br.IsValid())
+ {
+ printf ("#%lld: failed to set breakpoint on bar, exiting.\n", threadnum);
+ exit (1);
+ }
+ SBBreakpoint foo_br = target.BreakpointCreateByName ("foo", "testprog");
+ if (!foo_br.IsValid())
+ {
+ printf ("#%lld: Failed to set breakpoint on foo()\n", threadnum);
+ }
+
+ SBLaunchInfo launch_info (NULL);
+ SBError error;
+ SBProcess process = target.Launch (launch_info, error);
+ if (process.IsValid())
+ {
+ SBListener listener = debugger.GetListener();
+ SBBroadcaster broadcaster = process.GetBroadcaster();
+ uint32_t rc = broadcaster.AddListener (listener, SBProcess::eBroadcastBitStateChanged);
+ if (rc == 0)
+ {
+ printf ("adding listener failed\n");
+ exit (1);
+ }
+
+ wait_for_stop_event (process, listener);
+
+ if (!walk_stack_to_main (process.GetThreadAtIndex(0)))
+ {
+ printf ("#%lld: backtrace while @ foo() failed\n", threadnum);
+ completed_threads_array[threadnum] = true;
+ return (void *) 1;
+ }
+
+ if (strcmp (process.GetThreadAtIndex(0).GetFrameAtIndex(0).GetFunctionName(), "foo") != 0)
+ {
+#if DEBUG == 1
+ printf ("#%lld: First breakpoint did not stop at foo(), instead stopped at '%s'\n", threadnum, process.GetThreadAtIndex(0).GetFrameAtIndex(0).GetFunctionName());
+#endif
+ completed_threads_array[threadnum] = true;
+ return (void*) 1;
+ }
+
+ process.Continue();
+
+ wait_for_stop_event (process, listener);
+
+ if (process.GetState() == StateType::eStateExited)
+ {
+ printf ("#%lld: Process exited\n", threadnum);
+ completed_threads_array[threadnum] = true;
+ return (void *) 1;
+ }
+
+
+ if (!walk_stack_to_main (process.GetThreadAtIndex(0)))
+ {
+ printf ("#%lld: backtrace while @ bar() failed\n", threadnum);
+ completed_threads_array[threadnum] = true;
+ return (void *) 1;
+ }
+
+ if (strcmp (process.GetThreadAtIndex(0).GetFrameAtIndex(0).GetFunctionName(), "bar") != 0)
+ {
+ printf ("#%lld: First breakpoint did not stop at bar()\n", threadnum);
+ completed_threads_array[threadnum] = true;
+ return (void*) 1;
+ }
+
+ process.Kill();
+
+ wait_for_stop_event (process, listener);
+
+ SBDebugger::Destroy(debugger);
+
+#if DEBUG == 1
+ printf ("#%lld: All good!\n", threadnum);
+#endif
+ successful_threads_array[threadnum] = true;
+ completed_threads_array[threadnum] = true;
+ return (void*) 0;
+ }
+ else
+ {
+ printf("#%lld: process failed to launch\n", threadnum);
+ successful_threads_array[threadnum] = false;
+ completed_threads_array[threadnum] = true;
+ return (void*) 0;
+ }
+ }
+ else
+ {
+ printf ("#%lld: did not get valid target\n", threadnum);
+ successful_threads_array[threadnum] = false;
+ completed_threads_array[threadnum] = true;
+ return (void*) 0;
+ }
+ }
+ else
+ {
+ printf ("#%lld: did not get debugger\n", threadnum);
+ successful_threads_array[threadnum] = false;
+ completed_threads_array[threadnum] = true;
+ return (void*) 0;
+ }
+ completed_threads_array[threadnum] = true;
+ return (void*) 1;
+}
+
+int main (int argc, char **argv)
+{
+ SBDebugger::Initialize();
+
+ completed_threads_array = (bool *) malloc (sizeof (bool) * NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS);
+ memset (completed_threads_array, 0, sizeof (bool) * NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS);
+ successful_threads_array = (bool *) malloc (sizeof (bool) * NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS);
+ memset (successful_threads_array, 0, sizeof (bool) * NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS);
+
+ if (argc > 1 && argv[1] != NULL)
+ {
+ inferior_process_name = argv[1];
+ }
+
+ std::thread threads[NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS];
+ for (uint64_t i = 0; i< NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS; i++)
+ {
+ threads[i] = std::move(std::thread(do_one_debugger, (void*)i));
+ }
+
+
+ int max_time_to_wait = 20; // 20 iterations, or 60 seconds
+ int iter = 0;
+ while (1)
+ {
+ std::this_thread::sleep_for(std::chrono::seconds(3));
+ bool all_done = true;
+ int successful_threads = 0;
+ int total_completed_threads = 0;
+ for (uint64_t i = 0; i < NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS; i++)
+ {
+ if (successful_threads_array[i] == true)
+ successful_threads++;
+ if (completed_threads_array[i] == true)
+ total_completed_threads++;
+ if (completed_threads_array[i] == false)
+ {
+ all_done = false;
+ }
+ }
+ if (all_done)
+ {
+#if DEBUG == 1
+ printf ("All threads completed.\n");
+ printf ("%d threads completed successfully out of %d\n", successful_threads, NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS);
+#endif
+ SBDebugger::Terminate();
+ exit(0);
+ }
+ else
+ {
+#if DEBUG == 1
+ printf ("%d threads completed so far (%d successfully), out of %d\n", total_completed_threads, successful_threads, NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS);
+#endif
+ }
+ if (iter++ == max_time_to_wait)
+ {
+ printf ("reached maximum timeout but only %d threads have completed so far (%d successfully), out of %d. Exiting.\n", total_completed_threads, successful_threads, NUMBER_OF_SIMULTANEOUS_DEBUG_SESSIONS);
+ break;
+ }
+ }
+
+
+ SBDebugger::Terminate();
+ exit (1);
+}
diff --git a/packages/Python/lldbsuite/test/api/multiple-debuggers/testprog.cpp b/packages/Python/lldbsuite/test/api/multiple-debuggers/testprog.cpp
new file mode 100644
index 000000000000..c9d1ea14f17b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/api/multiple-debuggers/testprog.cpp
@@ -0,0 +1,12 @@
+int bar ()
+{
+ return 5;
+}
+int foo ()
+{
+ return bar() + 5;
+}
+int main ()
+{
+ return foo();
+}
diff --git a/packages/Python/lldbsuite/test/api/multithreaded/Makefile b/packages/Python/lldbsuite/test/api/multithreaded/Makefile
new file mode 100644
index 000000000000..37323ea78190
--- /dev/null
+++ b/packages/Python/lldbsuite/test/api/multithreaded/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../make
+
+ENABLE_THREADS := YES
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
+
+clean::
+ rm -rf $(wildcard *.o *.d *.dSYM)
diff --git a/packages/Python/lldbsuite/test/api/multithreaded/TestMultithreaded.py b/packages/Python/lldbsuite/test/api/multithreaded/TestMultithreaded.py
new file mode 100644
index 000000000000..0b405091ebd1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/api/multithreaded/TestMultithreaded.py
@@ -0,0 +1,91 @@
+"""Test the lldb public C++ api breakpoint callbacks."""
+
+from __future__ import print_function
+
+# __package__ = "lldbsuite.test"
+
+
+import os, re
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+import subprocess
+
+class SBBreakpointCallbackCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfRemote
+ @skipIfNoSBHeaders
+ @skipIfWindows # clang-cl does not support throw or catch (llvm.org/pr24538)
+ def test_breakpoint_callback(self):
+ """Test the that SBBreakpoint callback is invoked when a breakpoint is hit. """
+ self.build_and_test('driver.cpp test_breakpoint_callback.cpp',
+ 'test_breakpoint_callback')
+
+ @skipIfRemote
+ @skipIfNoSBHeaders
+ @skipIfWindows # clang-cl does not support throw or catch (llvm.org/pr24538)
+ @expectedFlakeyFreeBSD
+ def test_sb_api_listener_event_description(self):
+ """ Test the description of an SBListener breakpoint event is valid."""
+ self.build_and_test('driver.cpp listener_test.cpp test_listener_event_description.cpp',
+ 'test_listener_event_description')
+ pass
+
+ @skipIfRemote
+ @skipIfNoSBHeaders
+ @skipIfWindows # clang-cl does not support throw or catch (llvm.org/pr24538)
+ @expectedFlakeyFreeBSD
+ @expectedFlakeyLinux # Driver occasionally returns '1' as exit status
+ @expectedFailureAll("llvm.org/pr23139", oslist=["linux"], compiler="gcc", compiler_version=[">=","4.9"], archs=["x86_64"])
+ def test_sb_api_listener_event_process_state(self):
+ """ Test that a registered SBListener receives events when a process
+ changes state.
+ """
+ self.build_and_test('driver.cpp listener_test.cpp test_listener_event_process_state.cpp',
+ 'test_listener_event_process_state')
+ pass
+
+
+ @skipIfRemote
+ @skipIfNoSBHeaders
+ @skipIfWindows # clang-cl does not support throw or catch (llvm.org/pr24538)
+ @expectedFlakeyFreeBSD
+ @expectedFlakeyLinux
+ def test_sb_api_listener_resume(self):
+ """ Test that a process can be resumed from a non-main thread. """
+ self.build_and_test('driver.cpp listener_test.cpp test_listener_resume.cpp',
+ 'test_listener_resume')
+ pass
+
+ def build_and_test(self, sources, test_name, args = None):
+ """ Build LLDB test from sources, and run expecting 0 exit code """
+
+ # These tests link against host lldb API.
+ # Compiler's target triple must match liblldb triple
+ # because remote is disabled, we can assume that the os is the same
+ # still need to check architecture
+ if self.getLldbArchitecture() != self.getArchitecture():
+ self.skipTest("This test is only run if the target arch is the same as the lldb binary arch")
+
+ self.inferior = 'inferior_program'
+ self.buildProgram('inferior.cpp', self.inferior)
+ self.addTearDownHook(lambda: os.remove(self.inferior))
+
+ self.buildDriver(sources, test_name)
+ self.addTearDownHook(lambda: os.remove(test_name))
+
+ test_exe = os.path.join(os.getcwd(), test_name)
+ self.signBinary(test_exe)
+ exe = [test_exe, self.inferior]
+
+ env = {self.dylibPath : self.getLLDBLibraryEnvVal()}
+ if self.TraceOn():
+ print("Running test %s" % " ".join(exe))
+ check_call(exe, env=env)
+ else:
+ with open(os.devnull, 'w') as fnull:
+ check_call(exe, env=env, stdout=fnull, stderr=fnull)
+
+ def build_program(self, sources, program):
+ return self.buildDriver(sources, program)
diff --git a/packages/Python/lldbsuite/test/api/multithreaded/common.h b/packages/Python/lldbsuite/test/api/multithreaded/common.h
new file mode 100644
index 000000000000..dad8bba07a3f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/api/multithreaded/common.h
@@ -0,0 +1,68 @@
+#ifndef LLDB_TEST_API_COMMON_H
+#define LLDB_TEST_API_COMMON_H
+
+#include <condition_variable>
+#include <chrono>
+#include <exception>
+#include <iostream>
+#include <mutex>
+#include <string>
+#include <queue>
+
+#include <unistd.h>
+
+/// Simple exception class with a message
+struct Exception : public std::exception
+{
+ std::string s;
+ Exception(std::string ss) : s(ss) {}
+ virtual ~Exception() throw () { }
+ const char* what() const throw() { return s.c_str(); }
+};
+
+// Synchronized data structure for listener to send events through
+template<typename T>
+class multithreaded_queue {
+ std::condition_variable m_condition;
+ std::mutex m_mutex;
+ std::queue<T> m_data;
+ bool m_notified;
+
+public:
+
+ void push(T e) {
+ std::lock_guard<std::mutex> lock(m_mutex);
+ m_data.push(e);
+ m_notified = true;
+ m_condition.notify_all();
+ }
+
+ T pop(int timeout_seconds, bool &success) {
+ int count = 0;
+ while (count < timeout_seconds) {
+ std::unique_lock<std::mutex> lock(m_mutex);
+ if (!m_data.empty()) {
+ m_notified = false;
+ T ret = m_data.front();
+ m_data.pop();
+ success = true;
+ return ret;
+ } else if (!m_notified)
+ m_condition.wait_for(lock, std::chrono::seconds(1));
+ count ++;
+ }
+ success = false;
+ return T();
+ }
+};
+
+/// Allocates a char buffer with the current working directory
+inline char* get_working_dir() {
+#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
+ return getwd(0);
+#else
+ return get_current_dir_name();
+#endif
+}
+
+#endif // LLDB_TEST_API_COMMON_H
diff --git a/packages/Python/lldbsuite/test/api/multithreaded/driver.cpp b/packages/Python/lldbsuite/test/api/multithreaded/driver.cpp
new file mode 100644
index 000000000000..fa0c48e0ecfb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/api/multithreaded/driver.cpp
@@ -0,0 +1,38 @@
+
+/// LLDB C API Test Driver
+
+#include <algorithm>
+#include <iostream>
+#include <iterator>
+#include <string>
+#include <vector>
+
+#include "lldb-headers.h"
+
+#include "common.h"
+
+using namespace std;
+using namespace lldb;
+
+void test(SBDebugger &dbg, std::vector<string> args);
+
+int main(int argc, char** argv) {
+ int code = 0;
+
+ SBDebugger::Initialize();
+ SBDebugger dbg = SBDebugger::Create();
+
+ try {
+ if (!dbg.IsValid())
+ throw Exception("invalid debugger");
+ vector<string> args(argv + 1, argv + argc);
+
+ test(dbg, args);
+ } catch (Exception &e) {
+ cout << "ERROR: " << e.what() << endl;
+ code = 1;
+ }
+
+ SBDebugger::Destroy(dbg);
+ return code;
+}
diff --git a/packages/Python/lldbsuite/test/api/multithreaded/inferior.cpp b/packages/Python/lldbsuite/test/api/multithreaded/inferior.cpp
new file mode 100644
index 000000000000..9dbb289f98be
--- /dev/null
+++ b/packages/Python/lldbsuite/test/api/multithreaded/inferior.cpp
@@ -0,0 +1,17 @@
+
+#include <iostream>
+
+using namespace std;
+
+int next() {
+ static int i = 0;
+ cout << "incrementing " << i << endl;
+ return ++i;
+}
+
+int main() {
+ int i = 0;
+ while (i < 5)
+ i = next();
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/api/multithreaded/listener_test.cpp b/packages/Python/lldbsuite/test/api/multithreaded/listener_test.cpp
new file mode 100644
index 000000000000..b20868ff94f4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/api/multithreaded/listener_test.cpp
@@ -0,0 +1,74 @@
+// LLDB test snippet that registers a listener with a process that hits
+// a breakpoint.
+
+#include <atomic>
+#include <iostream>
+#include <string>
+#include <thread>
+#include <vector>
+
+#include "lldb-headers.h"
+#include "common.h"
+
+using namespace lldb;
+using namespace std;
+
+void listener_func();
+void check_listener(SBDebugger &dbg);
+
+// Listener thread and related variables
+atomic<bool> g_done;
+SBListener g_listener("test-listener");
+thread g_listener_thread;
+
+void shutdown_listener() {
+ g_done.store(true);
+ if (g_listener_thread.joinable())
+ g_listener_thread.join();
+}
+
+void test(SBDebugger &dbg, std::vector<string> args) {
+ try {
+ g_done.store(false);
+ SBTarget target = dbg.CreateTarget(args.at(0).c_str());
+ if (!target.IsValid()) throw Exception("invalid target");
+
+ SBBreakpoint breakpoint = target.BreakpointCreateByName("next");
+ if (!breakpoint.IsValid()) throw Exception("invalid breakpoint");
+
+ std::unique_ptr<char> working_dir(get_working_dir());
+
+ SBError error;
+ SBProcess process = target.Launch(g_listener,
+ 0, 0, 0, 0, 0,
+ working_dir.get(),
+ 0,
+ false,
+ error);
+ if (!error.Success())
+ throw Exception("Error launching process.");
+
+ /* FIXME: the approach below deadlocks
+ SBProcess process = target.LaunchSimple (0, 0, working_dir.get());
+
+ // get debugger listener (which is attached to process by default)
+ g_listener = dbg.GetListener();
+ */
+
+ // FIXME: because a listener is attached to the process at launch-time,
+ // registering the listener below results in two listeners being attached,
+ // which is not supported by LLDB.
+ // register listener
+ // process.GetBroadcaster().AddListener(g_listener,
+ // SBProcess::eBroadcastBitStateChanged);
+
+ // start listener thread
+ g_listener_thread = thread(listener_func);
+ check_listener(dbg);
+
+ } catch (Exception &e) {
+ shutdown_listener();
+ throw e;
+ }
+ shutdown_listener();
+}
diff --git a/packages/Python/lldbsuite/test/api/multithreaded/lldb-headers.h b/packages/Python/lldbsuite/test/api/multithreaded/lldb-headers.h
new file mode 100644
index 000000000000..da0914b3b071
--- /dev/null
+++ b/packages/Python/lldbsuite/test/api/multithreaded/lldb-headers.h
@@ -0,0 +1,11 @@
+
+#ifndef LLDB_HEADERS_H
+#define LLDB_HEADERS_H
+
+#ifdef __APPLE__
+#include <LLDB/LLDB.h>
+#else
+#include "lldb/API/LLDB.h"
+#endif
+
+#endif // LLDB_HEADERS_H
diff --git a/packages/Python/lldbsuite/test/api/multithreaded/test_breakpoint_callback.cpp b/packages/Python/lldbsuite/test/api/multithreaded/test_breakpoint_callback.cpp
new file mode 100644
index 000000000000..def31f82b0c7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/api/multithreaded/test_breakpoint_callback.cpp
@@ -0,0 +1,49 @@
+
+// LLDB C++ API Test: verify that the function registered with
+// SBBreakpoint.SetCallback() is invoked when a breakpoint is hit.
+
+#include <mutex>
+#include <iostream>
+#include <vector>
+#include <string>
+
+#include "lldb-headers.h"
+
+#include "common.h"
+
+using namespace std;
+using namespace lldb;
+
+mutex g_mutex;
+condition_variable g_condition;
+int g_breakpoint_hit_count = 0;
+
+bool BPCallback (void *baton,
+ SBProcess &process,
+ SBThread &thread,
+ SBBreakpointLocation &location) {
+ lock_guard<mutex> lock(g_mutex);
+ g_breakpoint_hit_count += 1;
+ g_condition.notify_all();
+ return true;
+}
+
+void test(SBDebugger &dbg, vector<string> args) {
+ dbg.SetAsync(false);
+ SBTarget target = dbg.CreateTarget(args.at(0).c_str());
+ if (!target.IsValid()) throw Exception("invalid target");
+
+ SBBreakpoint breakpoint = target.BreakpointCreateByName("next");
+ if (!breakpoint.IsValid()) throw Exception("invalid breakpoint");
+ breakpoint.SetCallback(BPCallback, 0);
+
+ std::unique_ptr<char> working_dir(get_working_dir());
+ SBProcess process = target.LaunchSimple (0, 0, working_dir.get());
+
+ {
+ unique_lock<mutex> lock(g_mutex);
+ g_condition.wait_for(lock, chrono::seconds(5));
+ if (g_breakpoint_hit_count != 1)
+ throw Exception("Breakpoint hit count expected to be 1");
+ }
+}
diff --git a/packages/Python/lldbsuite/test/api/multithreaded/test_listener_event_description.cpp b/packages/Python/lldbsuite/test/api/multithreaded/test_listener_event_description.cpp
new file mode 100644
index 000000000000..0d7844dce6d0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/api/multithreaded/test_listener_event_description.cpp
@@ -0,0 +1,97 @@
+
+// LLDB C++ API Test: verify the event description that is received by an
+// SBListener object registered with a process with a breakpoint.
+
+#include <atomic>
+#include <array>
+#include <iostream>
+#include <string>
+#include <thread>
+
+#include "lldb-headers.h"
+
+#include "common.h"
+
+using namespace lldb;
+using namespace std;
+
+// listener thread control
+extern atomic<bool> g_done;
+extern SBListener g_listener;
+
+multithreaded_queue<string> g_event_descriptions;
+string g_error_desc;
+
+void listener_func() {
+ while (!g_done) {
+ SBEvent event;
+ bool got_event = g_listener.WaitForEvent(1, event);
+
+ if (got_event) {
+ if (!event.IsValid())
+ throw Exception("event is not valid in listener thread");
+
+ SBStream description;
+ event.GetDescription(description);
+ string str(description.GetData());
+ g_event_descriptions.push(str);
+ }
+ }
+}
+
+bool check_state(string &state, string &desc, bool got_description)
+{
+ g_error_desc.clear();
+
+ if(!got_description)
+ {
+ g_error_desc.append("Did not get expected event description");
+ return false;
+ }
+
+ if (desc.find("state-changed") == desc.npos)
+ g_error_desc.append("Event description incorrect: missing 'state-changed' ");
+
+ if (desc.find("pid = ") == desc.npos)
+ g_error_desc.append("Event description incorrect: missing process pid ");
+
+ string state_search_str = "state = " + state;
+ if (desc.find(state_search_str) == desc.npos)
+ {
+ string errString = ("Event description incorrect: expected state "
+ + state
+ + " but desc was "
+ + desc);
+ g_error_desc.append(errString);
+ }
+
+ if (g_error_desc.length() > 0)
+ return false;
+
+ cout << "check_state: " << state << " OK\n";
+ return true;
+}
+
+void check_listener(SBDebugger &dbg)
+{
+ bool got_description;
+ string state;
+
+ // check for "launching" state, this may or may not be present
+ string desc = g_event_descriptions.pop(5, got_description);
+ state = "launching";
+ if (check_state(state, desc, got_description))
+ {
+ // found a 'launching' state, pop next one from queue
+ desc = g_event_descriptions.pop(5, got_description);
+ }
+
+ state = "running";
+ if( !check_state(state, desc, got_description) )
+ throw Exception(g_error_desc);
+
+ desc = g_event_descriptions.pop(5, got_description);
+ state = "stopped";
+ if( !check_state(state, desc, got_description) )
+ throw Exception(g_error_desc);
+}
diff --git a/packages/Python/lldbsuite/test/api/multithreaded/test_listener_event_process_state.cpp b/packages/Python/lldbsuite/test/api/multithreaded/test_listener_event_process_state.cpp
new file mode 100644
index 000000000000..0a698d1081d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/api/multithreaded/test_listener_event_process_state.cpp
@@ -0,0 +1,68 @@
+
+// LLDB C++ API Test: verify the event description as obtained by calling
+// SBEvent::GetCStringFromEvent that is received by an
+// SBListener object registered with a process with a breakpoint.
+
+#include <atomic>
+#include <iostream>
+#include <string>
+#include <thread>
+
+#include "lldb-headers.h"
+
+#include "common.h"
+
+using namespace lldb;
+using namespace std;
+
+// listener thread control
+extern atomic<bool> g_done;
+
+multithreaded_queue<string> g_thread_descriptions;
+multithreaded_queue<string> g_frame_functions;
+
+extern SBListener g_listener;
+
+void listener_func() {
+ while (!g_done) {
+ SBEvent event;
+ bool got_event = g_listener.WaitForEvent(1, event);
+ if (got_event) {
+ if (!event.IsValid())
+ throw Exception("event is not valid in listener thread");
+
+ // send process description
+ SBProcess process = SBProcess::GetProcessFromEvent(event);
+ SBStream description;
+
+ for (int i = 0; i < process.GetNumThreads(); ++i) {
+ // send each thread description
+ description.Clear();
+ SBThread thread = process.GetThreadAtIndex(i);
+ thread.GetDescription(description);
+ g_thread_descriptions.push(description.GetData());
+
+ // send each frame function name
+ uint32_t num_frames = thread.GetNumFrames();
+ for(int j = 0; j < num_frames; ++j) {
+ const char* function_name = thread.GetFrameAtIndex(j).GetSymbol().GetName();
+ if (function_name)
+ g_frame_functions.push(function_name);
+ }
+ }
+ }
+ }
+}
+
+void check_listener(SBDebugger &dbg) {
+ // check thread description
+ bool got_description = false;
+ string desc = g_thread_descriptions.pop(5, got_description);
+ if (!got_description)
+ throw Exception("Expected at least one thread description string");
+
+ // check at least one frame has a function name
+ desc = g_frame_functions.pop(5, got_description);
+ if (!got_description)
+ throw Exception("Expected at least one frame function name string");
+}
diff --git a/packages/Python/lldbsuite/test/api/multithreaded/test_listener_resume.cpp b/packages/Python/lldbsuite/test/api/multithreaded/test_listener_resume.cpp
new file mode 100644
index 000000000000..8cf786b11603
--- /dev/null
+++ b/packages/Python/lldbsuite/test/api/multithreaded/test_listener_resume.cpp
@@ -0,0 +1,53 @@
+
+// LLDB C++ API Test: verify the event description as obtained by calling
+// SBEvent::GetCStringFromEvent that is received by an
+// SBListener object registered with a process with a breakpoint.
+
+#include <atomic>
+#include <iostream>
+#include <string>
+#include <thread>
+
+#include "lldb-headers.h"
+
+#include "common.h"
+
+using namespace lldb;
+using namespace std;
+
+// listener thread control
+extern atomic<bool> g_done;
+
+// used by listener thread to communicate a successful process continue command
+// back to the checking thread.
+
+multithreaded_queue<bool> g_process_started;
+
+extern SBListener g_listener;
+
+void listener_func() {
+ while (!g_done) {
+ SBEvent event;
+ bool got_event = g_listener.WaitForEvent(1, event);
+ if (got_event) {
+ if (!event.IsValid())
+ throw Exception("event is not valid in listener thread");
+
+ SBProcess process = SBProcess::GetProcessFromEvent(event);
+ if (process.GetState() == eStateStopped) {
+ SBError error = process.Continue();
+ if (!error.Success())
+ throw Exception(string("Cannot continue process from listener thread: ")
+ + error.GetCString());
+ g_process_started.push(true);
+ }
+ }
+ }
+}
+
+void check_listener(SBDebugger &dbg) {
+ bool got_message = false;
+ while (!got_message)
+ g_process_started.pop(5, got_message);
+ g_done = true;
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/TestEmulations.py b/packages/Python/lldbsuite/test/arm_emulation/TestEmulations.py
new file mode 100644
index 000000000000..8a78d21e7978
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/TestEmulations.py
@@ -0,0 +1,54 @@
+"""
+Test some ARM instruction emulation.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class ARMEmulationTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @no_debug_info_test
+ def test_thumb_emulations (self):
+ current_dir = os.getcwd();
+ test_dir = os.path.join (current_dir, "new-test-files")
+ files = os.listdir (test_dir)
+ thumb_files = list()
+ for f in files:
+ if '-thumb.dat' in f:
+ thumb_files.append (f)
+
+ for f in thumb_files:
+ test_file = os.path.join (test_dir, f)
+ self.run_a_single_test (test_file)
+
+ @no_debug_info_test
+ def test_arm_emulations (self):
+ current_dir = os.getcwd();
+ test_dir = os.path.join (current_dir, "new-test-files")
+ files = os.listdir (test_dir)
+ arm_files = list()
+ for f in files:
+ if '-arm.dat' in f:
+ arm_files.append (f)
+
+ for f in arm_files:
+ test_file = os.path.join (test_dir, f)
+ self.run_a_single_test (test_file)
+
+ def run_a_single_test (self, filename):
+ insn = lldb.SBInstruction ();
+ stream = lldb.SBStream ();
+ success = insn.TestEmulation (stream, filename);
+ output = stream.GetData();
+ if self.TraceOn():
+ print('\nRunning test ' + os.path.basename(filename))
+ print(output)
+
+ self.assertTrue (success, 'Emulation test succeeded.')
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-1-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-1-arm.dat
new file mode 100644
index 000000000000..64b2506f9d56
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-1-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="add r0, r0, r15"
+triple=arm-apple-ios
+opcode=0xe080000f
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00003000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-1-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-1-thumb.dat
new file mode 100644
index 000000000000..daa32d25a41a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-1-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="add r0, r13, #0"
+triple=thumb-apple-ios
+opcode=0xa800
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe50
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-10-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-10-thumb.dat
new file mode 100644
index 000000000000..bb3d760219b4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-10-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="add sp, r13"
+triple=thumb-apple-ios
+opcode=0x44ed
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x5fbffca0
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-11-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-11-thumb.dat
new file mode 100644
index 000000000000..e26f2218cbcd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-11-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="add sp, r15"
+triple=thumb-apple-ios
+opcode=0x44fd
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fe02e50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-12-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-12-thumb.dat
new file mode 100644
index 000000000000..a7f7344e7d97
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-12-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="add sp, r8"
+triple=thumb-apple-ios
+opcode=0x44c5
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-2-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-2-arm.dat
new file mode 100644
index 000000000000..cf6e0a9779a9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-2-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="add r0, r13, #0"
+triple=arm-apple-ios
+opcode=0xe28d0000
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x2fdffe58
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-2-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-2-thumb.dat
new file mode 100644
index 000000000000..9a178a0a159d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-2-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="add r0, sp, r0"
+triple=thumb-apple-ios
+opcode=0x4468
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe50
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-3-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-3-arm.dat
new file mode 100644
index 000000000000..9fc44b79395c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-3-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="add r0, r1, r0, lsl #2"
+triple=arm-apple-ios
+opcode=0xe0810100
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe48
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe48
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000001
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe48
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe48
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-3-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-3-thumb.dat
new file mode 100644
index 000000000000..c8f96ec09d3e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-3-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="add.w r10, r13, #31"
+triple=thumb-apple-ios
+opcode=0xf10d0a1f
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe40
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe40
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe40
+r8=0x00000008
+r9=0x00000009
+r10=0x2fdffe5f
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe40
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-4-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-4-arm.dat
new file mode 100644
index 000000000000..12b40ed76fce
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-4-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="add r0, r2, r7, lsl r1"
+triple=arm-apple-ios
+opcode=0xe0820117
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe40
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe40
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x5fbffc82
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe40
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe40
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-4-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-4-thumb.dat
new file mode 100644
index 000000000000..922b8ecdba53
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-4-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="add r3, r13, #16"
+triple=thumb-apple-ios
+opcode=0xab04
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe48
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe48
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x2fdffe58
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe48
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe48
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-5-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-5-arm.dat
new file mode 100644
index 000000000000..dfb6a87f014d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-5-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="add r10, r13, #31"
+triple=arm-apple-ios
+opcode=0xe28da01f
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x2fdffe6f
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-5-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-5-thumb.dat
new file mode 100644
index 000000000000..16ff517436b0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-5-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="add r3, sp, r3"
+triple=thumb-apple-ios
+opcode=0x446b
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x2fdffe53
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-6-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-6-arm.dat
new file mode 100644
index 000000000000..8a87eff5f002
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-6-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="add r12, r13, #24"
+triple=arm-apple-ios
+opcode=0xe28dc018
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x2fdffe68
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-6-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-6-thumb.dat
new file mode 100644
index 000000000000..e8abd6950f20
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-6-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="add r5, r13, #32"
+triple=thumb-apple-ios
+opcode=0xad08
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe48
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe48
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x2fdffe68
+r6=0x00000006
+r7=0x2fdffe48
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe48
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-7-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-7-arm.dat
new file mode 100644
index 000000000000..312514246e3e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-7-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="add r6, sp, #8"
+triple=arm-apple-ios
+opcode=0xe28d6008
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x2fdffe68
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-7-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-7-thumb.dat
new file mode 100644
index 000000000000..506071309d7c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-7-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="add sp, #16"
+triple=thumb-apple-ios
+opcode=0xb004
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe68
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-8-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-8-arm.dat
new file mode 100644
index 000000000000..44a400f5287a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-8-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="add sp, r8"
+triple=arm-apple-ios
+opcode=0xe08dd008
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe68
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-8-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-8-thumb.dat
new file mode 100644
index 000000000000..8bc6c789a51d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-8-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="add sp, #4"
+triple=thumb-apple-ios
+opcode=0xb001
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe5c
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-9-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-9-thumb.dat
new file mode 100644
index 000000000000..832af4cf0b48
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-add-9-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="add sp, r10"
+triple=thumb-apple-ios
+opcode=0x44d5
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe5a
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-bic-1-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-bic-1-arm.dat
new file mode 100644
index 000000000000..c1cd4f15ab3e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-bic-1-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="bic r4, r9"
+triple=arm-apple-ios
+opcode=0xe1c44009
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-bic-1-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-bic-1-thumb.dat
new file mode 100644
index 000000000000..c62422650182
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-bic-1-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="bics r4, r6"
+triple=thumb-apple-ios
+opcode=0x43b4
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000000
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-1-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-1-arm.dat
new file mode 100644
index 000000000000..e1922d9edb9a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-1-arm.dat
@@ -0,0 +1,119 @@
+InstructionEmulationState={
+assembly_string="ldmia r0!, {r1, r3}"
+triple=arm-apple-ios
+opcode=0xe8b0000a
+before_state={
+memory={
+address=0x2fdffe50
+data_encoding=uint32_t
+data=[
+ 0x0
+ 0x2e7c
+]
+}
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x0000001f
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x2fdffe58
+r1=0x00000000
+r2=0x2fdffe70
+r3=0x00002e7c
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-1-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-1-thumb.dat
new file mode 100644
index 000000000000..60a805e09d83
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-1-thumb.dat
@@ -0,0 +1,119 @@
+InstructionEmulationState={
+assembly_string="ldmia r0!, {r1, r3}"
+triple=thumb-apple-ios
+opcode=0xc80a
+before_state={
+memory={
+address=0x2fdffe40
+data_encoding=uint32_t
+data=[
+0x0
+0x2f84
+]
+}
+registers={
+r0=0x2fdffe40
+r1=0x2fdffe50
+r2=0x2fdffe60
+r3=0x2fdffe70
+r4=0x2fdffe80
+r5=0x2fdffe90
+r6=0x2fdffea0
+r7=0x2fdffe40
+r8=0x2fdffec0
+r9=0x2fdffed0
+r10=0x2fdffee0
+r11=0x2fdffef0
+r12=0x2fdfff00
+r13=0x2fdffe40
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe48
+r1=0x00000000
+r2=0x2fdffe60
+r3=0x00002f84
+r4=0x2fdffe80
+r5=0x2fdffe90
+r6=0x2fdffea0
+r7=0x2fdffe40
+r8=0x2fdffec0
+r9=0x2fdffed0
+r10=0x2fdffee0
+r11=0x2fdffef0
+r12=0x2fdfff00
+r13=0x2fdffe40
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-2-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-2-arm.dat
new file mode 100644
index 000000000000..99401bbd2e21
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-2-arm.dat
@@ -0,0 +1,123 @@
+InstructionEmulationState={
+assembly_string="ldmia r0!, {r2, r4, r6, r8, r10, r12}"
+triple=arm-apple-ios
+opcode=0xe8b01554
+before_state={
+memory={
+address=0x2fdffe20
+data_encoding=uint32_t
+data=[
+0x0
+0x2e7c
+0x1
+0x2fdffe84
+0x0
+0x0
+]
+}
+registers={
+r0=0x2fdffe20
+r1=0x2fdffe30
+r2=0x2fdffe40
+r3=0x0000001f
+r4=0x2fdffe60
+r5=0x2fdffe70
+r6=0x2fdffe80
+r7=0x2fdffe20
+r8=0x2fdffea0
+r9=0x2fdffeb0
+r10=0x2fdffec0
+r11=0x2fdffed0
+r12=0x2fdffee0
+r13=0x2fdffe20
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x2fdffe38
+r1=0x2fdffe30
+r2=0x00000000
+r3=0x0000001f
+r4=0x00002e7c
+r5=0x2fdffe70
+r6=0x00000001
+r7=0x2fdffe20
+r8=0x2fdffe84
+r9=0x2fdffeb0
+r10=0x00000000
+r11=0x2fdffed0
+r12=0x00000000
+r13=0x2fdffe20
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-2-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-2-thumb.dat
new file mode 100644
index 000000000000..39ecf947c6de
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-2-thumb.dat
@@ -0,0 +1,123 @@
+InstructionEmulationState={
+assembly_string="ldmia.w r0!,{r2,r4,r6,r8,r10,r12}"
+triple=thumb-apple-ios
+opcode=0xe8b01554
+before_state={
+memory={
+address=0x2fdffe50
+data_encoding=uint32_t
+data=[
+0x0
+0x2f80
+0x1
+0x2fdffeac
+0x0
+0x0
+]
+}
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe68
+r1=0x2fdffe60
+r2=0x00000000
+r3=0x2fdffe80
+r4=0x00002f80
+r5=0x2fdffea0
+r6=0x00000001
+r7=0x2fdffe50
+r8=0x2fdffeac
+r9=0x2fdffee0
+r10=0x00000000
+r11=0x2fdfff00
+r12=0x00000000
+r13=0x2fdffe50
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-3-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-3-arm.dat
new file mode 100644
index 000000000000..427d7b27485c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-3-arm.dat
@@ -0,0 +1,119 @@
+InstructionEmulationState={
+assembly_string="ldmia r14!, {r1, r3}"
+triple=arm-apple-ios
+opcode=0xe8be000a
+before_state={
+memory={
+address=0x2e7c
+data_encoding=uint32_t
+data=[
+0xe59fc00c
+0xe08fc00c
+]
+}
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x0000001f
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x2fdffe50
+r1=0xe59fc00c
+r2=0x2fdffe70
+r3=0xe08fc00c
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002e84
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-3-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-3-thumb.dat
new file mode 100644
index 000000000000..9738073c038e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldmia-3-thumb.dat
@@ -0,0 +1,119 @@
+InstructionEmulationState={
+assembly_string="ldmia.w r14!, {r1, r3}"
+triple=thumb-apple-ios
+opcode=0xe8be000a
+before_state={
+memory={
+address=0x2f80
+data_encoding=uint32_t
+data=[
+0xe59fc00c
+0xe08fc00c
+]
+}
+registers={
+r0=0x2fdffe78
+r1=0x2fdffe88
+r2=0x2fdffe98
+r3=0x2fdffea8
+r4=0x2fdffeb8
+r5=0x2fdffec8
+r6=0x2fdffed8
+r7=0x2fdffe78
+r8=0x2fdffef8
+r9=0x2fdfff08
+r10=0x2fdfff18
+r11=0x2fdfff28
+r12=0x2fdfff38
+r13=0x2fdffe78
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe78
+r1=0xe59fc00c
+r2=0x2fdffe98
+r3=0xe08fc00c
+r4=0x2fdffeb8
+r5=0x2fdffec8
+r6=0x2fdffed8
+r7=0x2fdffe78
+r8=0x2fdffef8
+r9=0x2fdfff08
+r10=0x2fdfff18
+r11=0x2fdfff28
+r12=0x2fdfff38
+r13=0x2fdffe78
+r14=0x00002f88
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-1-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-1-arm.dat
new file mode 100644
index 000000000000..307402fd2f5c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-1-arm.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldr r0, [pc, #+24]"
+triple=arm-apple-ios
+opcode=0xe59f0018
+before_state={
+memory={
+address=0x3018
+data_encoding=uint32_t
+data=[
+0x3030
+]
+}
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00003030
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-1-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-1-thumb.dat
new file mode 100644
index 000000000000..471669b0cb65
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-1-thumb.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldr r0, [pc, #12]"
+triple=thumb-apple-ios
+opcode=0x4803
+before_state={
+memory={
+address=0x300c
+data_encoding=uint32_t
+data=[
+0x3024
+]
+}
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00003024
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-10-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-10-thumb.dat
new file mode 100644
index 000000000000..bc7693c9a684
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-10-thumb.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldr.w r10,[ pc, #4]"
+triple=thumb-apple-ios
+opcode=0xf8dfa004
+before_state={
+memory={
+address=0x3000
+data_encoding=uint32_t
+data=[
+0x2fe01000
+]
+}
+registers={
+r0=0x2fdffe48
+r1=0x2fdffe58
+r2=0x2fdffe68
+r3=0x2fdffe78
+r4=0x2fdffe88
+r5=0x2fdffe98
+r6=0x2fdffea8
+r7=0x2fdffe48
+r8=0x2fdffec8
+r9=0x2fdffed8
+r10=0x2fdffee8
+r11=0x2fdffef8
+r12=0x2fdfff08
+r13=0x2fdffe48
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe48
+r1=0x2fdffe58
+r2=0x2fdffe68
+r3=0x2fdffe78
+r4=0x2fdffe88
+r5=0x2fdffe98
+r6=0x2fdffea8
+r7=0x2fdffe48
+r8=0x2fdffec8
+r9=0x2fdffed8
+r10=0x2fe01000
+r11=0x2fdffef8
+r12=0x2fdfff08
+r13=0x2fdffe48
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-11-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-11-thumb.dat
new file mode 100644
index 000000000000..b5bf18127cd6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-11-thumb.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldr.w r8, [pc , #0]"
+triple=thumb-apple-ios
+opcode=0xf8df8000
+before_state={
+memory={
+address=0x2ffc
+data_encoding=uint32_t
+data=[
+0xa0e1defe
+]
+}
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0xa0e1defe
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-12-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-12-thumb.dat
new file mode 100644
index 000000000000..5c3a5485f0b3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-12-thumb.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldr.w r9, [pc, #-4]"
+triple=thumb-apple-ios
+opcode=0xf85f9004
+before_state={
+memory={
+address=0x2fec
+data_encoding=uint32_t
+data=[
+0x9004f85f
+]
+}
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x9004f85f
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-2-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-2-arm.dat
new file mode 100644
index 000000000000..068297e3edce
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-2-arm.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldr r0, [pc, #256]"
+triple=arm-apple-ios
+opcode=0xe59f0100
+before_state={
+memory={
+address=0x3100
+data_encoding=uint32_t
+data=[
+0x0
+]
+}
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-2-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-2-thumb.dat
new file mode 100644
index 000000000000..27727831d6d5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-2-thumb.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldr r0, [pc, #+24]"
+triple=thumb-apple-ios
+opcode=0x4806
+before_state={
+memory={
+address=0x3018
+data_encoding=uint32_t
+data=[
+0x3030
+]
+}
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00003030
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-3-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-3-arm.dat
new file mode 100644
index 000000000000..f0d6d8aaba63
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-3-arm.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldr r0, [r13, #+24]"
+triple=arm-apple-ios
+opcode=0xe59d0018
+before_state={
+memory={
+address=0x2fdffe70
+data_encoding=uint32_t
+data=[
+0x2fdffe80
+]
+}
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x2fdffe80
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-3-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-3-thumb.dat
new file mode 100644
index 000000000000..012e1c53e663
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-3-thumb.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldr r0, [pc, #256]"
+triple=thumb-apple-ios
+opcode=0x4840
+before_state={
+memory={
+address=0x3100
+data_encoding=uint32_t
+data=[
+0x0
+]
+}
+registers={
+r0=0x2fdffe48
+r1=0x2fdffe58
+r2=0x2fdffe68
+r3=0x2fdffe78
+r4=0x2fdffe88
+r5=0x2fdffe98
+r6=0x2fdffea8
+r7=0x2fdffe48
+r8=0x2fdffec8
+r9=0x2fdffed8
+r10=0x2fdffee8
+r11=0x2fdffef8
+r12=0x2fdfff08
+r13=0x2fdffe48
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x2fdffe58
+r2=0x2fdffe68
+r3=0x2fdffe78
+r4=0x2fdffe88
+r5=0x2fdffe98
+r6=0x2fdffea8
+r7=0x2fdffe48
+r8=0x2fdffec8
+r9=0x2fdffed8
+r10=0x2fdffee8
+r11=0x2fdffef8
+r12=0x2fdfff08
+r13=0x2fdffe48
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-4-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-4-arm.dat
new file mode 100644
index 000000000000..e2d2aa6aa887
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-4-arm.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldr r1, [r5, #16]"
+triple=arm-apple-ios
+opcode=0xe5951010
+before_state={
+memory={
+address=0x2fdffeb8
+data_encoding=uint32_t
+data=[
+0x7365742d
+]
+}
+registers={
+r0=0x2fdffe58
+r1=0x2fdffe68
+r2=0x2fdffe78
+r3=0x0000001f
+r4=0x2fdffe98
+r5=0x2fdffea8
+r6=0x2fdffeb8
+r7=0x2fdffe58
+r8=0x2fdffed8
+r9=0x2fdffee8
+r10=0x2fdffef8
+r11=0x2fdfff08
+r12=0x2fdfff18
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x2fdffe58
+r1=0x7365742d
+r2=0x2fdffe78
+r3=0x0000001f
+r4=0x2fdffe98
+r5=0x2fdffea8
+r6=0x2fdffeb8
+r7=0x2fdffe58
+r8=0x2fdffed8
+r9=0x2fdffee8
+r10=0x2fdffef8
+r11=0x2fdfff08
+r12=0x2fdfff18
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-4-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-4-thumb.dat
new file mode 100644
index 000000000000..3eb6f167b488
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-4-thumb.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldr r0, [r13, #+24]"
+triple=thumb-apple-ios
+opcode=0x9806
+before_state={
+memory={
+address=0x2fdffe60
+data_encoding=uint32_t
+data=[
+0x2fdffe70
+]
+}
+registers={
+r0=0x2fdffe48
+r1=0x2fdffe58
+r2=0x2fdffe68
+r3=0x2fdffe78
+r4=0x2fdffe88
+r5=0x2fdffe98
+r6=0x2fdffea8
+r7=0x2fdffe48
+r8=0x2fdffec8
+r9=0x2fdffed8
+r10=0x2fdffee8
+r11=0x2fdffef8
+r12=0x2fdfff08
+r13=0x2fdffe48
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe70
+r1=0x2fdffe58
+r2=0x2fdffe68
+r3=0x2fdffe78
+r4=0x2fdffe88
+r5=0x2fdffe98
+r6=0x2fdffea8
+r7=0x2fdffe48
+r8=0x2fdffec8
+r9=0x2fdffed8
+r10=0x2fdffee8
+r11=0x2fdffef8
+r12=0x2fdfff08
+r13=0x2fdffe48
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-5-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-5-arm.dat
new file mode 100644
index 000000000000..45210d9600d9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-5-arm.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldr r2, [r0]"
+triple=arm-apple-ios
+opcode=0xe5902000
+before_state={
+memory={
+address=0x2fdffe60
+data_encoding=uint32_t
+data=[
+0x0
+]
+}
+registers={
+r0=0x2fdffe60
+r1=0x2fdffe70
+r2=0x2fdffe80
+r3=0x0000001f
+r4=0x2fdffea0
+r5=0x2fdffeb0
+r6=0x2fdffec0
+r7=0x2fdffe60
+r8=0x2fdffee0
+r9=0x2fdffef0
+r10=0x2fdfff00
+r11=0x2fdfff10
+r12=0x2fdfff20
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x2fdffe60
+r1=0x2fdffe70
+r2=0x00000000
+r3=0x0000001f
+r4=0x2fdffea0
+r5=0x2fdffeb0
+r6=0x2fdffec0
+r7=0x2fdffe60
+r8=0x2fdffee0
+r9=0x2fdffef0
+r10=0x2fdfff00
+r11=0x2fdfff10
+r12=0x2fdfff20
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-5-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-5-thumb.dat
new file mode 100644
index 000000000000..45289e7e899c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-5-thumb.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldr r1, [pc, #0]"
+triple=thumb-apple-ios
+opcode=0x4900
+before_state={
+memory={
+address=0x3000
+data_encoding=uint32_t
+data=[
+0x2fe01000
+]
+}
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe50
+r1=0x2fe01000
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-6-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-6-arm.dat
new file mode 100644
index 000000000000..0f379fd49809
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-6-arm.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldr r2, [r6], +r8, lsl #2"
+triple=arm-apple-ios
+opcode=0xe6962108
+before_state={
+memory={
+address=0x2fdffea8
+data_encoding=uint32_t
+data=[
+0x7365742d
+]
+}
+registers={
+r0=0x2fdffe48
+r1=0x2fdffe58
+r2=0x2fdffe68
+r3=0x0000001f
+r4=0x2fdffe88
+r5=0x2fdffe98
+r6=0x2fdffea8
+r7=0x2fdffe48
+r8=0x2fdffec8
+r9=0x2fdffed8
+r10=0x2fdffee8
+r11=0x2fdffef8
+r12=0x2fdfff08
+r13=0x2fdffe48
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x2fdffe48
+r1=0x2fdffe58
+r2=0x7365742d
+r3=0x0000001f
+r4=0x2fdffe88
+r5=0x2fdffe98
+r6=0xef5ff9c8
+r7=0x2fdffe48
+r8=0x2fdffec8
+r9=0x2fdffed8
+r10=0x2fdffee8
+r11=0x2fdffef8
+r12=0x2fdfff08
+r13=0x2fdffe48
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-6-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-6-thumb.dat
new file mode 100644
index 000000000000..5b3c119e7437
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-6-thumb.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldr r1, [r5, #16]"
+triple=thumb-apple-ios
+opcode=0x6929
+before_state={
+memory={
+address=0x2fdffeb0
+data_encoding=uint32_t
+data=[
+0x65742d62
+]
+}
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe50
+r1=0x65742d62
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-7-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-7-arm.dat
new file mode 100644
index 000000000000..ff425ef5284f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-7-arm.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldr r2, [sp, #24]"
+triple=arm-apple-ios
+opcode=0xe59d2018
+before_state={
+memory={
+address=0x2fdffe70
+data_encoding=uint32_t
+data=[
+0x0
+]
+}
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000000
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-7-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-7-thumb.dat
new file mode 100644
index 000000000000..db8d58796ca8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-7-thumb.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldr r2, [r0]"
+triple=thumb-apple-ios
+opcode=0x6802
+before_state={
+memory={
+address=0x2fdffe58
+data_encoding=uint32_t
+data=[
+0x0
+]
+}
+registers={
+r0=0x2fdffe58
+r1=0x2fdffe68
+r2=0x2fdffe78
+r3=0x2fdffe88
+r4=0x2fdffe98
+r5=0x2fdffea8
+r6=0x2fdffeb8
+r7=0x2fdffe58
+r8=0x2fdffed8
+r9=0x2fdffee8
+r10=0x2fdffef8
+r11=0x2fdfff08
+r12=0x2fdfff18
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe58
+r1=0x2fdffe68
+r2=0x00000000
+r3=0x2fdffe88
+r4=0x2fdffe98
+r5=0x2fdffea8
+r6=0x2fdffeb8
+r7=0x2fdffe58
+r8=0x2fdffed8
+r9=0x2fdffee8
+r10=0x2fdffef8
+r11=0x2fdfff08
+r12=0x2fdfff18
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-8-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-8-arm.dat
new file mode 100644
index 000000000000..c11dfc133e5b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-8-arm.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldr r3, [r11, #-8]"
+triple=arm-apple-ios
+opcode=0xe51b3008
+before_state={
+memory={
+address=0x2fdfff00
+data_encoding=uint32_t
+data=[
+0x63387830
+]
+}
+registers={
+r0=0x2fdffe58
+r1=0x2fdffe68
+r2=0x2fdffe78
+r3=0x0000001f
+r4=0x2fdffe98
+r5=0x2fdffea8
+r6=0x2fdffeb8
+r7=0x2fdffe58
+r8=0x2fdffed8
+r9=0x2fdffee8
+r10=0x2fdffef8
+r11=0x2fdfff08
+r12=0x2fdfff18
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x2fdffe58
+r1=0x2fdffe68
+r2=0x2fdffe78
+r3=0x63387830
+r4=0x2fdffe98
+r5=0x2fdffea8
+r6=0x2fdffeb8
+r7=0x2fdffe58
+r8=0x2fdffed8
+r9=0x2fdffee8
+r10=0x2fdffef8
+r11=0x2fdfff08
+r12=0x2fdfff18
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-8-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-8-thumb.dat
new file mode 100644
index 000000000000..01d7013ceaaa
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-8-thumb.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldr r2, [sp, #24]"
+triple=thumb-apple-ios
+opcode=0x9a06
+before_state={
+memory={
+address=0x2fdffe68
+data_encoding=uint32_t
+data=[
+0x2fdffe78
+]
+}
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe78
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-9-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-9-thumb.dat
new file mode 100644
index 000000000000..cc3c4db2f4de
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldr-9-thumb.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldr.w r3, [r11, #8]"
+triple=thumb-apple-ios
+opcode=0xf8db3008
+before_state={
+memory={
+address=0x2fdfff08
+data_encoding=uint32_t
+data=[
+0x62343134
+]
+}
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x62343134
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrd-1-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrd-1-arm.dat
new file mode 100644
index 000000000000..970f8aa7c0a4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrd-1-arm.dat
@@ -0,0 +1,119 @@
+InstructionEmulationState={
+assembly_string="ldrd r0, r1, [r12, #+4]"
+triple=arm-apple-ios
+opcode=0xe1cc00d4
+before_state={
+memory={
+address=0x2fdfff14
+data_encoding=uint32_t
+data=[
+0x30313038
+0x31623039
+]
+}
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x0000001f
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x30313038
+r1=0x31623039
+r2=0x2fdffe70
+r3=0x0000001f
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrd-1-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrd-1-thumb.dat
new file mode 100644
index 000000000000..7ab41ce35dbe
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrd-1-thumb.dat
@@ -0,0 +1,119 @@
+InstructionEmulationState={
+assembly_string="ldrd r0, r1, [r12, #+4]"
+triple=thumb-apple-ios
+opcode=0xe9dc0101
+before_state={
+memory={
+address=0x2fdfff3c
+data_encoding=uint32_t
+data=[
+0x0
+0x0
+]
+}
+registers={
+r0=0x2fdffe78
+r1=0x2fdffe88
+r2=0x2fdffe98
+r3=0x2fdffea8
+r4=0x2fdffeb8
+r5=0x2fdffec8
+r6=0x2fdffed8
+r7=0x2fdffe78
+r8=0x2fdffef8
+r9=0x2fdfff08
+r10=0x2fdfff18
+r11=0x2fdfff28
+r12=0x2fdfff38
+r13=0x2fdffe78
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000000
+r2=0x2fdffe98
+r3=0x2fdffea8
+r4=0x2fdffeb8
+r5=0x2fdffec8
+r6=0x2fdffed8
+r7=0x2fdffe78
+r8=0x2fdffef8
+r9=0x2fdfff08
+r10=0x2fdfff18
+r11=0x2fdfff28
+r12=0x2fdfff38
+r13=0x2fdffe78
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrd-2-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrd-2-thumb.dat
new file mode 100644
index 000000000000..70fe6f5cfff7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrd-2-thumb.dat
@@ -0,0 +1,119 @@
+InstructionEmulationState={
+assembly_string="ldrd r4, r5, [pc, #-0]"
+triple=thumb-apple-ios
+opcode=0xe9df4500
+before_state={
+memory={
+address=0x2ffc
+data_encoding=uint32_t
+data=[
+0xa0e1defe
+0x2fe01000
+]
+}
+registers={
+r0=0x2fdffe78
+r1=0x2fdffe88
+r2=0x2fdffe98
+r3=0x2fdffea8
+r4=0x2fdffeb8
+r5=0x2fdffec8
+r6=0x2fdffed8
+r7=0x2fdffe78
+r8=0x2fdffef8
+r9=0x2fdfff08
+r10=0x2fdfff18
+r11=0x2fdfff28
+r12=0x2fdfff38
+r13=0x2fdffe78
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe78
+r1=0x2fdffe88
+r2=0x2fdffe98
+r3=0x2fdffea8
+r4=0xa0e1defe
+r5=0x2fe01000
+r6=0x2fdffed8
+r7=0x2fdffe78
+r8=0x2fdffef8
+r9=0x2fdfff08
+r10=0x2fdfff18
+r11=0x2fdfff28
+r12=0x2fdfff38
+r13=0x2fdffe78
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrh-1-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrh-1-thumb.dat
new file mode 100644
index 000000000000..2a47002fb658
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrh-1-thumb.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldrh r0, [r2, #16]"
+triple=thumb-apple-ios
+opcode=0x8a10
+before_state={
+memory={
+address=0x2fdffe78
+data_encoding=uint32_t
+data=[
+0x762f
+]
+}
+registers={
+r0=0x2fdffe48
+r1=0x2fdffe58
+r2=0x2fdffe68
+r3=0x2fdffe78
+r4=0x2fdffe88
+r5=0x2fdffe98
+r6=0x2fdffea8
+r7=0x2fdffe48
+r8=0x2fdffec8
+r9=0x2fdffed8
+r10=0x2fdffee8
+r11=0x2fdffef8
+r12=0x2fdfff08
+r13=0x2fdffe48
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x0000762f
+r1=0x2fdffe58
+r2=0x2fdffe68
+r3=0x2fdffe78
+r4=0x2fdffe88
+r5=0x2fdffe98
+r6=0x2fdffea8
+r7=0x2fdffe48
+r8=0x2fdffec8
+r9=0x2fdffed8
+r10=0x2fdffee8
+r11=0x2fdffef8
+r12=0x2fdfff08
+r13=0x2fdffe48
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrsh-1-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrsh-1-arm.dat
new file mode 100644
index 000000000000..cecf397f1d49
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrsh-1-arm.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldrsh r0, [r2], #+15"
+triple=arm-apple-ios
+opcode=0xe0d200ff
+before_state={
+memory={
+address=0x2fdffe70
+data_encoding=uint32_t
+data=[
+0xfffffeeb
+]
+}
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x0000001f
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0xfffffeeb
+r1=0x2fdffe60
+r2=0x2fdffe7f
+r3=0x0000001f
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrsh-2-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrsh-2-arm.dat
new file mode 100644
index 000000000000..660b3d3b5db7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-ldrsh-2-arm.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="ldrsh r14, [r2], #+15"
+triple=arm-apple-ios
+opcode=0xe0d2e0ff
+before_state={
+memory={
+address=0x2fdffe70
+data_encoding=uint32_t
+data=[
+0xfffffeec
+]
+}
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x0000001f
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe7f
+r3=0x0000001f
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0xfffffeec
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-1-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-1-arm.dat
new file mode 100644
index 000000000000..232bc967fede
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-1-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r12, #256"
+triple=arm-apple-ios
+opcode=0xe3a0cc01
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x00000100
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-1-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-1-thumb.dat
new file mode 100644
index 000000000000..569510dbd3ba
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-1-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov ip, pc"
+triple=thumb-apple-ios
+opcode=0x46fc
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x00003000
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-10-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-10-thumb.dat
new file mode 100644
index 000000000000..6bf9b0d7ef7e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-10-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r0, r15"
+triple=thumb-apple-ios
+opcode=0x4678
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00003000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-11-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-11-thumb.dat
new file mode 100644
index 000000000000..82043ef335b1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-11-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r0, r7"
+triple=thumb-apple-ios
+opcode=0x4638
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe58
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-12-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-12-thumb.dat
new file mode 100644
index 000000000000..1fce18af917c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-12-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov.w r12, #256"
+triple=thumb-apple-ios
+opcode=0xf44f7c80
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x00000100
+r13=0x2fdffe50
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-13-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-13-thumb.dat
new file mode 100644
index 000000000000..d1c1a4428c9f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-13-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r12, r13"
+triple=thumb-apple-ios
+opcode=0x46ec
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x2fdffe50
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-14-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-14-thumb.dat
new file mode 100644
index 000000000000..dfd89c265fbd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-14-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r14, r2"
+triple=thumb-apple-ios
+opcode=0x4696
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00000002
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-15-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-15-thumb.dat
new file mode 100644
index 000000000000..0ff8e5d7dc5c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-15-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r1, r14"
+triple=thumb-apple-ios
+opcode=0x4671
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00002f84
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-16-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-16-thumb.dat
new file mode 100644
index 000000000000..1baf42dfc56c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-16-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r2, ip"
+triple=thumb-apple-ios
+opcode=0x4662
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x0000000c
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-17-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-17-thumb.dat
new file mode 100644
index 000000000000..70cee03fb54f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-17-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r2, r13"
+triple=thumb-apple-ios
+opcode=0x466a
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x2fdffe50
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-18-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-18-thumb.dat
new file mode 100644
index 000000000000..1893e188b0d0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-18-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r2, r9"
+triple=thumb-apple-ios
+opcode=0x464a
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000009
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-19-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-19-thumb.dat
new file mode 100644
index 000000000000..238e16b4aa42
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-19-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r3, r12"
+triple=thumb-apple-ios
+opcode=0x4663
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000000c
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-2-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-2-arm.dat
new file mode 100644
index 000000000000..6d6c0cbf80c5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-2-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r12, r13"
+triple=arm-apple-ios
+opcode=0xe1a0c00d
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x2fdffe58
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-2-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-2-thumb.dat
new file mode 100644
index 000000000000..ad6854427fbf
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-2-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov ip, r8"
+triple=thumb-apple-ios
+opcode=0x46c4
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x00000008
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-20-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-20-thumb.dat
new file mode 100644
index 000000000000..15ecd2ebfa0a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-20-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r3, r13"
+triple=thumb-apple-ios
+opcode=0x466b
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x2fdffe50
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-21-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-21-thumb.dat
new file mode 100644
index 000000000000..6a38f1671b7c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-21-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r3, sp"
+triple=thumb-apple-ios
+opcode=0x466b
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x2fdffe58
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-22-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-22-thumb.dat
new file mode 100644
index 000000000000..242b56824194
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-22-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r4, r11"
+triple=thumb-apple-ios
+opcode=0x465c
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x0000000b
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-23-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-23-thumb.dat
new file mode 100644
index 000000000000..7f57440a8421
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-23-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r5, r10"
+triple=thumb-apple-ios
+opcode=0x4655
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x0000000a
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-24-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-24-thumb.dat
new file mode 100644
index 000000000000..9a1756e8473b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-24-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r6, r9"
+triple=thumb-apple-ios
+opcode=0x464e
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000009
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-25-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-25-thumb.dat
new file mode 100644
index 000000000000..c2fd6a739644
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-25-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r7, lr"
+triple=thumb-apple-ios
+opcode=0x4677
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x00002f84
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-26-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-26-thumb.dat
new file mode 100644
index 000000000000..2cc155d8071c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-26-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r7, r8"
+triple=thumb-apple-ios
+opcode=0x4647
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x00000008
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-27-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-27-thumb.dat
new file mode 100644
index 000000000000..0b35377b08ee
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-27-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r9, pc"
+triple=thumb-apple-ios
+opcode=0x46f9
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00003000
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-28-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-28-thumb.dat
new file mode 100644
index 000000000000..f7d7778a2512
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-28-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov sp, ip"
+triple=thumb-apple-ios
+opcode=0x46e5
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x0000000c
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-29-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-29-thumb.dat
new file mode 100644
index 000000000000..5e9098f99d2f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-29-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov sp, pc"
+triple=thumb-apple-ios
+opcode=0x46fd
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x00003000
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-3-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-3-arm.dat
new file mode 100644
index 000000000000..1fe7155bd3a3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-3-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r14, r2"
+triple=arm-apple-ios
+opcode=0xe1a0e002
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00000002
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-3-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-3-thumb.dat
new file mode 100644
index 000000000000..8ce129682bf9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-3-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov ip, sp"
+triple=thumb-apple-ios
+opcode=0x46ec
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x2fdffe58
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-30-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-30-thumb.dat
new file mode 100644
index 000000000000..a0dddad6b5a1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-30-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov sp, r7"
+triple=thumb-apple-ios
+opcode=0x46bd
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-31-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-31-thumb.dat
new file mode 100644
index 000000000000..20d8dc7c06f6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-31-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="movs r3, #1"
+triple=thumb-apple-ios
+opcode=0x2301
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000001
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x20000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-4-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-4-arm.dat
new file mode 100644
index 000000000000..8ef83b268055
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-4-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r2, r9"
+triple=arm-apple-ios
+opcode=0xe1a02009
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000009
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-4-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-4-thumb.dat
new file mode 100644
index 000000000000..f854ba26641e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-4-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov lr, pc"
+triple=thumb-apple-ios
+opcode=0x46fe
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00003000
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-5-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-5-arm.dat
new file mode 100644
index 000000000000..ee85779083f6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-5-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r3, #2147483648"
+triple=arm-apple-ios
+opcode=0xe3a03102
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe38
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe38
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x80000000
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe38
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe38
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-5-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-5-thumb.dat
new file mode 100644
index 000000000000..d6140bdb92d7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-5-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov lr, r2"
+triple=thumb-apple-ios
+opcode=0x4696
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00000002
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-6-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-6-arm.dat
new file mode 100644
index 000000000000..863a6d3e9bd8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-6-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov r3, r13"
+triple=arm-apple-ios
+opcode=0xe1a0300d
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x2fdffe60
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-6-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-6-thumb.dat
new file mode 100644
index 000000000000..fac96bf5a5a8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-6-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov pc, ip"
+triple=thumb-apple-ios
+opcode=0x46e7
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x0000000c
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-7-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-7-thumb.dat
new file mode 100644
index 000000000000..c537d30cb249
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-7-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov pc, lr"
+triple=thumb-apple-ios
+opcode=0x46f7
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002f84
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-8-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-8-thumb.dat
new file mode 100644
index 000000000000..b724c79a0d56
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-8-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov pc, r4"
+triple=thumb-apple-ios
+opcode=0x46a7
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00000004
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-9-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-9-thumb.dat
new file mode 100644
index 000000000000..ccf7ea6c3423
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mov-9-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mov pc, sp"
+triple=thumb-apple-ios
+opcode=0x46ef
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x2fdffe58
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-moveq-1-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-moveq-1-arm.dat
new file mode 100644
index 000000000000..f46b1bfd6e87
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-moveq-1-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="moveq r3, #1"
+triple=arm-apple-ios
+opcode=0x3a03001
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000001
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-movs-1-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-movs-1-arm.dat
new file mode 100644
index 000000000000..38292508d43c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-movs-1-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="movs r12, r13"
+triple=arm-apple-ios
+opcode=0xe1b0c00d
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x2fdffe58
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x20000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-1-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-1-arm.dat
new file mode 100644
index 000000000000..024dd9fa4bcb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-1-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mvn r14, #1"
+triple=arm-apple-ios
+opcode=0xe3e0e001
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0xfffffffe
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-1-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-1-thumb.dat
new file mode 100644
index 000000000000..c5c385c8522d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-1-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mvn r0, #1"
+triple=thumb-apple-ios
+opcode=0xf06f0001
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe98
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe98
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0xfffffffe
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe98
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe98
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-2-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-2-arm.dat
new file mode 100644
index 000000000000..10df542fcad5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-2-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mvn r0, #1"
+triple=arm-apple-ios
+opcode=0xe3e00001
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe68
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe68
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0xfffffffe
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe68
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe68
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-2-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-2-thumb.dat
new file mode 100644
index 000000000000..3c2f6f4da279
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-2-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mvn r0, #31"
+triple=thumb-apple-ios
+opcode=0xf06f001f
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe90
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe90
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0xffffffe0
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe90
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe90
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-3-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-3-arm.dat
new file mode 100644
index 000000000000..742708978b6d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-3-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mvn r0, #31"
+triple=arm-apple-ios
+opcode=0xe3e0001f
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0xffffffe0
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-3-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-3-thumb.dat
new file mode 100644
index 000000000000..ff4ca7331a9f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-3-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mvn r14, #1"
+triple=thumb-apple-ios
+opcode=0xf06f0e01
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe90
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe90
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe90
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe90
+r14=0xfffffffe
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-4-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-4-arm.dat
new file mode 100644
index 000000000000..4efc18cc5f28
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-4-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mvn r3, r8"
+triple=arm-apple-ios
+opcode=0xe1e03008
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0xfffffff7
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-4-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-4-thumb.dat
new file mode 100644
index 000000000000..f8b1569e9063
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-mvn-4-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="mvns r3, r8"
+triple=thumb-apple-ios
+opcode=0xea7f0308
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe90
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe90
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0xfffffff7
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe90
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe90
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0xa0000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-pop-1-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-pop-1-arm.dat
new file mode 100644
index 000000000000..07163f80aeb6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-pop-1-arm.dat
@@ -0,0 +1,121 @@
+InstructionEmulationState={
+assembly_string="pop {r3, r4, r8, r10}"
+triple=arm-apple-ios
+opcode=0xe8bd0518
+before_state={
+memory={
+address=0x2fdffe50
+data_encoding=uint32_t
+data=[
+0x0
+0x2e7c
+0x1
+0x2fdffeac
+]
+}
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000000
+r4=0x00002e7c
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000001
+r9=0x00000009
+r10=0x2fdffeac
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-pop-1-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-pop-1-thumb.dat
new file mode 100644
index 000000000000..fad6765be9a8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-pop-1-thumb.dat
@@ -0,0 +1,121 @@
+InstructionEmulationState={
+assembly_string="pop.w {r3, r4, r8, r10}"
+triple=thumb-apple-ios
+opcode=0xe8bd0518
+before_state={
+memory={
+address=0x2fdffe38
+data_encoding=uint32_t
+data=[
+0x0
+0x2f80
+0x1000
+0x1
+]
+}
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe38
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe38
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000000
+r4=0x00002f80
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe38
+r8=0x00001000
+r9=0x00000009
+r10=0x00000001
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe48
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-pop-2-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-pop-2-arm.dat
new file mode 100644
index 000000000000..4b6ae43ca285
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-pop-2-arm.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="pop {r9}"
+triple=arm-apple-ios
+opcode=0xe8bd0200
+before_state={
+memory={
+address=0x2fdffe70
+data_encoding=uint32_t
+data=[
+0x0
+]
+}
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe70
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe70
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe70
+r8=0x00000008
+r9=0x00000000
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe74
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-pop-2-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-pop-2-thumb.dat
new file mode 100644
index 000000000000..9f3efe57e9d2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-pop-2-thumb.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="pop {r3}"
+triple=thumb-apple-ios
+opcode=0xbc08
+before_state={
+memory={
+address=0x2fdffe60
+data_encoding=uint32_t
+data=[
+0x0
+]
+}
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000000
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe64
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-pop-3-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-pop-3-thumb.dat
new file mode 100644
index 000000000000..a2adc418c4a5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-pop-3-thumb.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="pop {r6}"
+triple=thumb-apple-ios
+opcode=0xbc40
+before_state={
+memory={
+address=0x2fdffe60
+data_encoding=uint32_t
+data=[
+0x0
+]
+}
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000000
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe64
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-1-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-1-arm.dat
new file mode 100644
index 000000000000..b2f6e0965ab9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-1-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="push {r0, r1, r2, r3, r7, r14}"
+triple=arm-apple-ios
+opcode=0xe92d408f
+before_state={
+registers={
+r0=0x2fdffe30
+r1=0x2fdffe40
+r2=0x2fdffe50
+r3=0x0000001f
+r4=0x2fdffe70
+r5=0x2fdffe80
+r6=0x2fdffe90
+r7=0x2fdffe30
+r8=0x2fdffeb0
+r9=0x2fdffec0
+r10=0x2fdffed0
+r11=0x2fdffee0
+r12=0x2fdffef0
+r13=0x2fdffe30
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x2fdffe30
+r1=0x2fdffe40
+r2=0x2fdffe50
+r3=0x0000001f
+r4=0x2fdffe70
+r5=0x2fdffe80
+r6=0x2fdffe90
+r7=0x2fdffe30
+r8=0x2fdffeb0
+r9=0x2fdffec0
+r10=0x2fdffed0
+r11=0x2fdffee0
+r12=0x2fdffef0
+r13=0x2fdffe18
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-1-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-1-thumb.dat
new file mode 100644
index 000000000000..6f5b29ed1990
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-1-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="push {r0, r1, r2, r3, r7, r14}"
+triple=thumb-apple-ios
+opcode=0xb58f
+before_state={
+registers={
+r0=0x2fdffe28
+r1=0x2fdffe38
+r2=0x2fdffe48
+r3=0x2fdffe58
+r4=0x2fdffe68
+r5=0x2fdffe78
+r6=0x2fdffe88
+r7=0x2fdffe28
+r8=0x2fdffea8
+r9=0x2fdffeb8
+r10=0x2fdffec8
+r11=0x2fdffed8
+r12=0x2fdffee8
+r13=0x2fdffe28
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe28
+r1=0x2fdffe38
+r2=0x2fdffe48
+r3=0x2fdffe58
+r4=0x2fdffe68
+r5=0x2fdffe78
+r6=0x2fdffe88
+r7=0x2fdffe28
+r8=0x2fdffea8
+r9=0x2fdffeb8
+r10=0x2fdffec8
+r11=0x2fdffed8
+r12=0x2fdffee8
+r13=0x2fdffe10
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-2-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-2-arm.dat
new file mode 100644
index 000000000000..6f1f4389e80e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-2-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="push {r6}"
+triple=arm-apple-ios
+opcode=0xe92d0040
+before_state={
+registers={
+r0=0x2fdffe68
+r1=0x2fdffe78
+r2=0x2fdffe88
+r3=0x0000001f
+r4=0x2fdffea8
+r5=0x2fdffeb8
+r6=0x2fdffec8
+r7=0x2fdffe68
+r8=0x2fdffee8
+r9=0x2fdffef8
+r10=0x2fdfff08
+r11=0x2fdfff18
+r12=0x2fdfff28
+r13=0x2fdffe68
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x2fdffe68
+r1=0x2fdffe78
+r2=0x2fdffe88
+r3=0x0000001f
+r4=0x2fdffea8
+r5=0x2fdffeb8
+r6=0x2fdffec8
+r7=0x2fdffe68
+r8=0x2fdffee8
+r9=0x2fdffef8
+r10=0x2fdfff08
+r11=0x2fdfff18
+r12=0x2fdfff28
+r13=0x2fdffe64
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-2-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-2-thumb.dat
new file mode 100644
index 000000000000..23e4df446bf4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-2-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="push {r6}"
+triple=thumb-apple-ios
+opcode=0xb440
+before_state={
+registers={
+r0=0x2fdffe58
+r1=0x2fdffe68
+r2=0x2fdffe78
+r3=0x2fdffe88
+r4=0x2fdffe98
+r5=0x2fdffea8
+r6=0x2fdffeb8
+r7=0x2fdffe58
+r8=0x2fdffed8
+r9=0x2fdffee8
+r10=0x2fdffef8
+r11=0x2fdfff08
+r12=0x2fdfff18
+r13=0x2fdffe58
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe58
+r1=0x2fdffe68
+r2=0x2fdffe78
+r3=0x2fdffe88
+r4=0x2fdffe98
+r5=0x2fdffea8
+r6=0x2fdffeb8
+r7=0x2fdffe58
+r8=0x2fdffed8
+r9=0x2fdffee8
+r10=0x2fdffef8
+r11=0x2fdfff08
+r12=0x2fdfff18
+r13=0x2fdffe54
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-3-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-3-arm.dat
new file mode 100644
index 000000000000..06847a5ff3ba
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-3-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="push {r7, r14}"
+triple=arm-apple-ios
+opcode=0xe92d4080
+before_state={
+registers={
+r0=0x2fdffe58
+r1=0x2fdffe68
+r2=0x2fdffe78
+r3=0x0000001f
+r4=0x2fdffe98
+r5=0x2fdffea8
+r6=0x2fdffeb8
+r7=0x2fdffe58
+r8=0x2fdffed8
+r9=0x2fdffee8
+r10=0x2fdffef8
+r11=0x2fdfff08
+r12=0x2fdfff18
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x2fdffe58
+r1=0x2fdffe68
+r2=0x2fdffe78
+r3=0x0000001f
+r4=0x2fdffe98
+r5=0x2fdffea8
+r6=0x2fdffeb8
+r7=0x2fdffe58
+r8=0x2fdffed8
+r9=0x2fdffee8
+r10=0x2fdffef8
+r11=0x2fdfff08
+r12=0x2fdfff18
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-3-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-3-thumb.dat
new file mode 100644
index 000000000000..e3330f537cb6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-push-3-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="push {r7, r14}"
+triple=thumb-apple-ios
+opcode=0xb580
+before_state={
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe48
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-1-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-1-arm.dat
new file mode 100644
index 000000000000..70a5be3cb69c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-1-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="str r0, [r13]"
+triple=arm-apple-ios
+opcode=0xe58d0000
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-1-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-1-thumb.dat
new file mode 100644
index 000000000000..3559652ce6c1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-1-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="str r0, [r13]"
+triple=thumb-apple-ios
+opcode=0x9000
+before_state={
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-2-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-2-arm.dat
new file mode 100644
index 000000000000..3d77724b4f96
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-2-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="str r1, [r0, #+4]"
+triple=arm-apple-ios
+opcode=0xe5801004
+before_state={
+registers={
+r0=0x2fdffe60
+r1=0x2fdffe70
+r2=0x2fdffe80
+r3=0x0000001f
+r4=0x2fdffea0
+r5=0x2fdffeb0
+r6=0x2fdffec0
+r7=0x2fdffe60
+r8=0x2fdffee0
+r9=0x2fdffef0
+r10=0x2fdfff00
+r11=0x2fdfff10
+r12=0x2fdfff20
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x2fdffe60
+r1=0x2fdffe70
+r2=0x2fdffe80
+r3=0x0000001f
+r4=0x2fdffea0
+r5=0x2fdffeb0
+r6=0x2fdffec0
+r7=0x2fdffe60
+r8=0x2fdffee0
+r9=0x2fdffef0
+r10=0x2fdfff00
+r11=0x2fdfff10
+r12=0x2fdfff20
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-2-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-2-thumb.dat
new file mode 100644
index 000000000000..73e8cd3e548e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-2-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="str r0, [sp, #0]"
+triple=thumb-apple-ios
+opcode=0x9000
+before_state={
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-3-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-3-arm.dat
new file mode 100644
index 000000000000..97c90a0050c3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-3-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="str r2, [r0]"
+triple=arm-apple-ios
+opcode=0xe5802000
+before_state={
+registers={
+r0=0x2fdffe60
+r1=0x2fdffe70
+r2=0x2fdffe80
+r3=0x0000001f
+r4=0x2fdffea0
+r5=0x2fdffeb0
+r6=0x2fdffec0
+r7=0x2fdffe60
+r8=0x2fdffee0
+r9=0x2fdffef0
+r10=0x2fdfff00
+r11=0x2fdfff10
+r12=0x2fdfff20
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x2fdffe60
+r1=0x2fdffe70
+r2=0x2fdffe80
+r3=0x0000001f
+r4=0x2fdffea0
+r5=0x2fdffeb0
+r6=0x2fdffec0
+r7=0x2fdffe60
+r8=0x2fdffee0
+r9=0x2fdffef0
+r10=0x2fdfff00
+r11=0x2fdfff10
+r12=0x2fdfff20
+r13=0x2fdffe60
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-3-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-3-thumb.dat
new file mode 100644
index 000000000000..8e891c042879
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-3-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="str r1, [sp, #32]"
+triple=thumb-apple-ios
+opcode=0x9108
+before_state={
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x2fdffe80
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-4-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-4-arm.dat
new file mode 100644
index 000000000000..ed3b54eaf38a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-4-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="str r2, [r13, #+4]"
+triple=arm-apple-ios
+opcode=0xe58d2004
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-4-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-4-thumb.dat
new file mode 100644
index 000000000000..ec9e2dc1e549
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-4-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="str.w r7, [r13, #-12]!"
+triple=thumb-apple-ios
+opcode=0xf84d7d0c
+before_state={
+registers={
+r0=0x2fdffe48
+r1=0x2fdffe58
+r2=0x2fdffe68
+r3=0x2fdffe78
+r4=0x2fdffe88
+r5=0x2fdffe98
+r6=0x2fdffea8
+r7=0x2fdffe48
+r8=0x2fdffec8
+r9=0x2fdffed8
+r10=0x2fdffee8
+r11=0x2fdffef8
+r12=0x2fdfff08
+r13=0x2fdffe48
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe48
+r1=0x2fdffe58
+r2=0x2fdffe68
+r3=0x2fdffe78
+r4=0x2fdffe88
+r5=0x2fdffe98
+r6=0x2fdffea8
+r7=0x2fdffe48
+r8=0x2fdffec8
+r9=0x2fdffed8
+r10=0x2fdffee8
+r11=0x2fdffef8
+r12=0x2fdfff08
+r13=0x2fdffe3c
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-5-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-5-arm.dat
new file mode 100644
index 000000000000..98b8dfb16b37
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-str-5-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="str r7, [r13, #-12]!"
+triple=arm-apple-ios
+opcode=0xe52d700c
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe4c
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-strb-1-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-strb-1-arm.dat
new file mode 100644
index 000000000000..2f7320d007ad
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-strb-1-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="strb r0, [r2], #+15"
+triple=arm-apple-ios
+opcode=0xe4c2000f
+before_state={
+registers={
+r0=0x2fdffe58
+r1=0x2fdffe68
+r2=0x2fdffe78
+r3=0x0000001f
+r4=0x2fdffe98
+r5=0x2fdffea8
+r6=0x2fdffeb8
+r7=0x2fdffe58
+r8=0x2fdffed8
+r9=0x2fdffee8
+r10=0x2fdffef8
+r11=0x2fdfff08
+r12=0x2fdfff18
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x2fdffe58
+r1=0x2fdffe68
+r2=0x2fdffe87
+r3=0x0000001f
+r4=0x2fdffe98
+r5=0x2fdffea8
+r6=0x2fdffeb8
+r7=0x2fdffe58
+r8=0x2fdffed8
+r9=0x2fdffee8
+r10=0x2fdffef8
+r11=0x2fdfff08
+r12=0x2fdfff18
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-strb-2-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-strb-2-arm.dat
new file mode 100644
index 000000000000..495c8e720a11
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-strb-2-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="strb r3, [r0, #+8]"
+triple=arm-apple-ios
+opcode=0xe5c03008
+before_state={
+registers={
+r0=0x2fdffe58
+r1=0x2fdffe68
+r2=0x2fdffe78
+r3=0x0000001f
+r4=0x2fdffe98
+r5=0x2fdffea8
+r6=0x2fdffeb8
+r7=0x2fdffe58
+r8=0x2fdffed8
+r9=0x2fdffee8
+r10=0x2fdffef8
+r11=0x2fdfff08
+r12=0x2fdfff18
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x2fdffe58
+r1=0x2fdffe68
+r2=0x2fdffe78
+r3=0x0000001f
+r4=0x2fdffe98
+r5=0x2fdffea8
+r6=0x2fdffeb8
+r7=0x2fdffe58
+r8=0x2fdffed8
+r9=0x2fdffee8
+r10=0x2fdffef8
+r11=0x2fdfff08
+r12=0x2fdfff18
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-strbt-1-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-strbt-1-arm.dat
new file mode 100644
index 000000000000..494c49af9527
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-strbt-1-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="strbt r14, [r2], #+15"
+triple=arm-apple-ios
+opcode=0xe4e2e00f
+before_state={
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe70
+r3=0x0000001f
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x2fdffe50
+r1=0x2fdffe60
+r2=0x2fdffe7f
+r3=0x0000001f
+r4=0x2fdffe90
+r5=0x2fdffea0
+r6=0x2fdffeb0
+r7=0x2fdffe50
+r8=0x2fdffed0
+r9=0x2fdffee0
+r10=0x2fdffef0
+r11=0x2fdfff00
+r12=0x2fdfff10
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-strd-1-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-strd-1-thumb.dat
new file mode 100644
index 000000000000..4876f8741b0e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-strd-1-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="strd r10, r11, [r6, #+28]"
+triple=thumb-apple-ios
+opcode=0xe9c6ab07
+before_state={
+registers={
+r0=0x2fdffe70
+r1=0x2fdffe80
+r2=0x2fdffe90
+r3=0x2fdffea0
+r4=0x2fdffeb0
+r5=0x2fdffec0
+r6=0x2fdffed0
+r7=0x2fdffe70
+r8=0x2fdffef0
+r9=0x2fdfff00
+r10=0x2fdfff10
+r11=0x2fdfff20
+r12=0x2fdfff30
+r13=0x2fdffe70
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe70
+r1=0x2fdffe80
+r2=0x2fdffe90
+r3=0x2fdffea0
+r4=0x2fdffeb0
+r5=0x2fdffec0
+r6=0x2fdffed0
+r7=0x2fdffe70
+r8=0x2fdffef0
+r9=0x2fdfff00
+r10=0x2fdfff10
+r11=0x2fdfff20
+r12=0x2fdfff30
+r13=0x2fdffe70
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-strt-1-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-strt-1-arm.dat
new file mode 100644
index 000000000000..9fc311565eaa
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-strt-1-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="strt r0, [r2], #+15"
+triple=arm-apple-ios
+opcode=0xe4a2000f
+before_state={
+registers={
+r0=0x2fdffe58
+r1=0x2fdffe68
+r2=0x2fdffe78
+r3=0x0000001f
+r4=0x2fdffe98
+r5=0x2fdffea8
+r6=0x2fdffeb8
+r7=0x2fdffe58
+r8=0x2fdffed8
+r9=0x2fdffee8
+r10=0x2fdffef8
+r11=0x2fdfff08
+r12=0x2fdfff18
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x2fdffe58
+r1=0x2fdffe68
+r2=0x2fdffe87
+r3=0x0000001f
+r4=0x2fdffe98
+r5=0x2fdffea8
+r6=0x2fdffeb8
+r7=0x2fdffe58
+r8=0x2fdffed8
+r9=0x2fdffee8
+r10=0x2fdffef8
+r11=0x2fdfff08
+r12=0x2fdfff18
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-1-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-1-arm.dat
new file mode 100644
index 000000000000..98c435d616a5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-1-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="sub r0, sp, r8"
+triple=arm-apple-ios
+opcode=0xe04d0008
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x2fdffe50
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-1-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-1-thumb.dat
new file mode 100644
index 000000000000..482480d0cd43
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-1-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="sub.w r10, sp, #16"
+triple=thumb-apple-ios
+opcode=0xf1ad0a10
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe40
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe40
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe40
+r8=0x00000008
+r9=0x00000009
+r10=0x2fdffe30
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe40
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-10-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-10-arm.dat
new file mode 100644
index 000000000000..9f07a947f7db
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-10-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="sub r7, r12, #8"
+triple=arm-apple-ios
+opcode=0xe24c7008
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x00000004
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-2-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-2-arm.dat
new file mode 100644
index 000000000000..9a67268196e2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-2-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="sub r10, r12, #31"
+triple=arm-apple-ios
+opcode=0xe24ca01f
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0xffffffed
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-2-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-2-thumb.dat
new file mode 100644
index 000000000000..11d213803e2e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-2-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="sub.w r10, sp, #31"
+triple=thumb-apple-ios
+opcode=0xf1ad0a1f
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe40
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe40
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe40
+r8=0x00000008
+r9=0x00000009
+r10=0x2fdffe21
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe40
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-3-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-3-arm.dat
new file mode 100644
index 000000000000..4dfe680ce470
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-3-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="sub r12, r13, #12"
+triple=arm-apple-ios
+opcode=0xe24dc00c
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x2fdffe44
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-3-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-3-thumb.dat
new file mode 100644
index 000000000000..a017f5284302
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-3-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="sub.w r12, sp, #31"
+triple=thumb-apple-ios
+opcode=0xf1ad0c1f
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe40
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe40
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe40
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x2fdffe21
+r13=0x2fdffe40
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-4-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-4-arm.dat
new file mode 100644
index 000000000000..50d13c994755
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-4-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="sub r13, r13, #24"
+triple=arm-apple-ios
+opcode=0xe24dd018
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe38
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-4-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-4-thumb.dat
new file mode 100644
index 000000000000..214808d6a429
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-4-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="sub.w r1, sp, r3, lsl #2"
+triple=thumb-apple-ios
+opcode=0xebad0183
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe30
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe30
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x2fdffe24
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe30
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe30
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-5-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-5-arm.dat
new file mode 100644
index 000000000000..58de27b5d4e2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-5-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="sub r13, r13, #4"
+triple=arm-apple-ios
+opcode=0xe24dd004
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe54
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-5-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-5-thumb.dat
new file mode 100644
index 000000000000..126882866859
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-5-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="sub.w r7, sp, #1"
+triple=thumb-apple-ios
+opcode=0xf1ad0701
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe4f
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-6-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-6-arm.dat
new file mode 100644
index 000000000000..be6891307dbe
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-6-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="sub r1, r13, #4"
+triple=arm-apple-ios
+opcode=0xe24d1004
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x2fdffe54
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-6-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-6-thumb.dat
new file mode 100644
index 000000000000..d48c42eb8d8c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-6-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="sub.w sp, sp, #4"
+triple=thumb-apple-ios
+opcode=0xf1ad0d04
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe4c
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-8-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-8-arm.dat
new file mode 100644
index 000000000000..21b17dfbcd80
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-8-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="sub r2, r2, r3"
+triple=arm-apple-ios
+opcode=0xe0422003
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0xffffffe3
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-9-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-9-arm.dat
new file mode 100644
index 000000000000..06888ad3a4b7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-sub-9-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="sub r4, r12, r7"
+triple=arm-apple-ios
+opcode=0xe04c4007
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0xd02001b4
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe58
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe58
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-1-arm.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-1-arm.dat
new file mode 100644
index 000000000000..856a55749b18
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-1-arm.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="subs r10, r13, #31"
+triple=arm-apple-ios
+opcode=0xe25da01f
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ff8
+cpsr=0x60000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x0000001f
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x2fdffe31
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002e7c
+r15=0x00002ffc
+cpsr=0x20000010
+s0=0x00000000
+s1=0x00000001
+s2=0x00000002
+s3=0x00000003
+s4=0x00000004
+s5=0x00000005
+s6=0x00000006
+s7=0x00000007
+s8=0x00000008
+s9=0x00000009
+s10=0x0000000a
+s11=0x0000000b
+s12=0x0000000c
+s13=0x0000000d
+s14=0x0000000e
+s15=0x0000000f
+s16=0x00000010
+s17=0x00000011
+s18=0x00000012
+s19=0x00000013
+s20=0x00000014
+s21=0x00000015
+s22=0x00000016
+s23=0x00000017
+s24=0x00000018
+s25=0x00000019
+s26=0x0000001a
+s27=0x0000001b
+s28=0x0000001c
+s29=0x0000001d
+s30=0x0000001e
+s31=0x0000001f
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-1-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-1-thumb.dat
new file mode 100644
index 000000000000..63aa7b8ed13f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-1-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="subs r0, r6, #0"
+triple=thumb-apple-ios
+opcode=0x1e30
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000006
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x20000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-10-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-10-thumb.dat
new file mode 100644
index 000000000000..75938b4e1d5b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-10-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="subs.w r1, sp, #4"
+triple=thumb-apple-ios
+opcode=0xf1bd0104
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe48
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe48
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x2fdffe44
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe48
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe48
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x20000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-2-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-2-thumb.dat
new file mode 100644
index 000000000000..74bddcea97cb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-2-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="subs r0, r7, r5"
+triple=thumb-apple-ios
+opcode=0x1b78
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe48
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe48
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x2fdffe43
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe48
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe48
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x20000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-3-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-3-thumb.dat
new file mode 100644
index 000000000000..965ebf370176
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-3-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="subs.w r10, r13, #31"
+triple=thumb-apple-ios
+opcode=0xf1bd0a1f
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe38
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe38
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe38
+r8=0x00000008
+r9=0x00000009
+r10=0x2fdffe19
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe38
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x20000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-4-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-4-thumb.dat
new file mode 100644
index 000000000000..068724170d57
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-4-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="subs r1, r3, #4"
+triple=thumb-apple-ios
+opcode=0x1f19
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0xffffffff
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x80000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-5-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-5-thumb.dat
new file mode 100644
index 000000000000..72ed2ef25c0f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-5-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="subs r4, r2, r6"
+triple=thumb-apple-ios
+opcode=0x1b94
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe48
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe48
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0xfffffffc
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe48
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe48
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x80000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-6-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-6-thumb.dat
new file mode 100644
index 000000000000..67133b2832e5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-6-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="subs r7, r5, #7"
+triple=thumb-apple-ios
+opcode=0x1fef
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe50
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0xfffffffe
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f84
+r15=0x00002ffe
+cpsr=0x80000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-8-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-8-thumb.dat
new file mode 100644
index 000000000000..965ebf370176
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-8-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="subs.w r10, r13, #31"
+triple=thumb-apple-ios
+opcode=0xf1bd0a1f
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe38
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe38
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe38
+r8=0x00000008
+r9=0x00000009
+r10=0x2fdffe19
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe38
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x20000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-9-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-9-thumb.dat
new file mode 100644
index 000000000000..ea1597743162
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-subs-9-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="subs.w r10, sp, #31"
+triple=thumb-apple-ios
+opcode=0xf1bd0a1f
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe38
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe38
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe38
+r8=0x00000008
+r9=0x00000009
+r10=0x2fdffe19
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe38
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x20000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpop-1-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpop-1-thumb.dat
new file mode 100644
index 000000000000..22dd9d88b4b6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpop-1-thumb.dat
@@ -0,0 +1,125 @@
+InstructionEmulationState={
+assembly_string="vpop {d11, d12, d13, d14}"
+triple=thumb-apple-ios
+opcode=0xecbdbb08
+before_state={
+memory={
+address=0x2fdffe60
+data_encoding=uint32_t
+data=[
+0x0
+0x2f80
+0x1000
+0x1
+0x2fdffebc
+0x0
+0x0
+0x2fdffe8c
+]
+}
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe80
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00002f80
+s24=0x00001000
+s25=0x00000001
+s26=0x2fdffebc
+s27=0x00000000
+s28=0x00000000
+s29=0x2fdffe8c
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpop-2-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpop-2-thumb.dat
new file mode 100644
index 000000000000..e69cd9eef2d5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpop-2-thumb.dat
@@ -0,0 +1,118 @@
+InstructionEmulationState={
+assembly_string="vpop {s0}"
+triple=thumb-apple-ios
+opcode=0xecbd0a01
+before_state={
+memory={
+address=0x2fdffe98
+data_encoding=uint32_t
+data=[
+0x0
+]
+}
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe98
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe98
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe98
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe9c
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpop-3-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpop-3-thumb.dat
new file mode 100644
index 000000000000..375a92eaaab5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpop-3-thumb.dat
@@ -0,0 +1,121 @@
+InstructionEmulationState={
+assembly_string="vpop {s11, s12, s13, s14}"
+triple=thumb-apple-ios
+opcode=0xecfd5a04
+before_state={
+memory={
+address=0x2fdffe60
+data_encoding=uint32_t
+data=[
+0x0
+0x2f80
+0x1000
+0x1
+]
+}
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe70
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00002f80
+s13=0x00001000
+s14=0x00000001
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpush-1-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpush-1-thumb.dat
new file mode 100644
index 000000000000..ac4ef56be665
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpush-1-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="vpush {d11, d12, d13, d14}"
+triple=thumb-apple-ios
+opcode=0xed2dbb08
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe40
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpush-2-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpush-2-thumb.dat
new file mode 100644
index 000000000000..58055d6539ce
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpush-2-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="vpush {s0}"
+triple=thumb-apple-ios
+opcode=0xed2d0a01
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe90
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe90
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe90
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe8c
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpush-3-thumb.dat b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpush-3-thumb.dat
new file mode 100644
index 000000000000..2658b43bc883
--- /dev/null
+++ b/packages/Python/lldbsuite/test/arm_emulation/new-test-files/test-vpush-3-thumb.dat
@@ -0,0 +1,111 @@
+InstructionEmulationState={
+assembly_string="vpush {s11, s12, s13, s14}"
+triple=thumb-apple-ios
+opcode=0xed6d5a04
+before_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe60
+r14=0x00002f80
+r15=0x00002ff8
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+after_state={
+registers={
+r0=0x00000000
+r1=0x00000001
+r2=0x00000002
+r3=0x00000003
+r4=0x00000004
+r5=0x00000005
+r6=0x00000006
+r7=0x2fdffe60
+r8=0x00000008
+r9=0x00000009
+r10=0x0000000a
+r11=0x0000000b
+r12=0x0000000c
+r13=0x2fdffe50
+r14=0x00002f80
+r15=0x00002ffc
+cpsr=0x60000030
+s0=0x00000000
+s1=0x00000000
+s2=0x00000000
+s3=0x00000000
+s4=0x00000000
+s5=0x00000000
+s6=0x00000000
+s7=0x00000000
+s8=0x00000000
+s9=0x00000000
+s10=0x00000000
+s11=0x00000000
+s12=0x00000000
+s13=0x00000000
+s14=0x00000000
+s15=0x00000000
+s16=0x00000000
+s17=0x00000000
+s18=0x00000000
+s19=0x00000000
+s20=0x00000000
+s21=0x00000000
+s22=0x00000000
+s23=0x00000000
+s24=0x00000000
+s25=0x00000000
+s26=0x00000000
+s27=0x00000000
+s28=0x00000000
+s29=0x00000000
+s30=0x00000000
+s31=0x00000000
+}
+}
+}
diff --git a/packages/Python/lldbsuite/test/attic/dotest.pl b/packages/Python/lldbsuite/test/attic/dotest.pl
new file mode 100644
index 000000000000..f093ed8f8f22
--- /dev/null
+++ b/packages/Python/lldbsuite/test/attic/dotest.pl
@@ -0,0 +1,44 @@
+#!/usr/bin/perl -w
+
+#
+# Use this script to visit each python test case under the specified directory
+# and invoke unittest.main() on each test case.
+#
+
+use strict;
+use FindBin;
+use File::Find;
+use File::Basename;
+use Cwd;
+use Cwd 'abs_path';
+
+scalar(@ARGV) == 1 or die "Usage: dotest.pl testdir";
+
+my $scriptDir = $FindBin::Bin;
+my $baseDir = abs_path("$scriptDir/..");
+my $pluginDir = "$baseDir/test/plugins";
+my $testDir = $ARGV[0];
+
+my $dbgPath = "$baseDir/build/Debug/LLDB.framework/Resources/Python";
+my $relPath = "$baseDir/build/Release/LLDB.framework/Resources/Python";
+if (-d $dbgPath) {
+ $ENV{'PYTHONPATH'} = "$dbgPath:$scriptDir:$pluginDir";
+} elsif (-d $relPath) {
+ $ENV{'PYTHONPATH'} = "$relPath:$scriptDir:$pluginDir";
+}
+#print("ENV{PYTHONPATH}=$ENV{'PYTHONPATH'}\n");
+
+# Traverse the directory to find our python test cases.
+find(\&handleFind, $testDir);
+
+sub handleFind {
+ my $foundFile = $File::Find::name;
+ my $dir = getcwd;
+ #print("foundFile: $foundFile\n");
+
+ # Test*.py is the naming pattern for our test cases.
+ if ($foundFile =~ /.*\/(Test.*\.py)$/) {
+ print("Running python $1 (cwd = $dir)...\n");
+ system("python $1");
+ }
+}
diff --git a/packages/Python/lldbsuite/test/attic/tester.py b/packages/Python/lldbsuite/test/attic/tester.py
new file mode 100644
index 000000000000..5c1a2370ced8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/attic/tester.py
@@ -0,0 +1,115 @@
+#!/usr/bin/env python
+# -*- coding: utf8 -*-
+
+from __future__ import print_function
+
+import math, os.path, re, sys, time, unittest
+
+def setupSysPath():
+ testPath = sys.path[0]
+ rem = re.match("(^.*/)test$", testPath)
+ if not rem:
+ print("This script expects to reside in .../test.")
+ sys.exit(-1)
+ lldbBasePath = rem.group(1)
+ lldbDebugPythonPath = "build/Debug/LLDB.framework/Resources/Python"
+ lldbReleasePythonPath = "build/Release/LLDB.framework/Resources/Python"
+ lldbPythonPath = None
+ if os.path.isfile(lldbDebugPythonPath + "/lldb.py"):
+ lldbPythonPath = lldbDebugPythonPath
+ if os.path.isfile(lldbReleasePythonPath + "/lldb.py"):
+ lldbPythonPath = lldbReleasePythonPath
+ if not lldbPythonPath:
+ print("This script requires lldb.py to be in either " + lldbDebugPythonPath, end='')
+ print("or" + lldbReleasePythonPath)
+ sys.exit(-1)
+ sys.path.append(lldbPythonPath)
+
+def prettyTime(t):
+ if t == 0.0:
+ return "0s"
+ if t < 0.000001:
+ return ("%.3f" % (t * 1000000000.0)) + "ns"
+ if t < 0.001:
+ return ("%.3f" % (t * 1000000.0)) + "µs"
+ if t < 1:
+ return ("%.3f" % (t * 1000.0)) + "ms"
+ return str(t) + "s"
+
+class ExecutionTimes:
+ @classmethod
+ def executionTimes(cls):
+ if cls.m_executionTimes == None:
+ cls.m_executionTimes = ExecutionTimes()
+ for i in range(100):
+ cls.m_executionTimes.start()
+ cls.m_executionTimes.end("null")
+ return cls.m_executionTimes
+ def __init__(self):
+ self.m_times = dict()
+ def start(self):
+ self.m_start = time.time()
+ def end(self, component):
+ e = time.time()
+ if component not in self.m_times:
+ self.m_times[component] = list()
+ self.m_times[component].append(e - self.m_start)
+ def dumpStats(self):
+ for key in list(self.m_times.keys()):
+ if len(self.m_times[key]):
+ sampleMin = float('inf')
+ sampleMax = float('-inf')
+ sampleSum = 0.0
+ sampleCount = 0.0
+ for time in self.m_times[key]:
+ if time > sampleMax:
+ sampleMax = time
+ if time < sampleMin:
+ sampleMin = time
+ sampleSum += time
+ sampleCount += 1.0
+ sampleMean = sampleSum / sampleCount
+ sampleVariance = 0
+ for time in self.m_times[key]:
+ sampleVariance += (time - sampleMean) ** 2
+ sampleVariance /= sampleCount
+ sampleStandardDeviation = math.sqrt(sampleVariance)
+ print(key + ": [" + prettyTime(sampleMin) + ", " + prettyTime(sampleMax) + "] ", end='')
+ print("µ " + prettyTime(sampleMean) + ", σ " + prettyTime(sampleStandardDeviation))
+ m_executionTimes = None
+
+setupSysPath()
+
+import lldb
+
+class LLDBTestCase(unittest.TestCase):
+ def setUp(self):
+ debugger = lldb.SBDebugger.Create()
+ debugger.SetAsync(True)
+ self.m_commandInterpreter = debugger.GetCommandInterpreter()
+ if not self.m_commandInterpreter:
+ print("Couldn't get the command interpreter")
+ sys.exit(-1)
+ def runCommand(self, command, component):
+ res = lldb.SBCommandReturnObject()
+ ExecutionTimes.executionTimes().start()
+ self.m_commandInterpreter.HandleCommand(command, res, False)
+ ExecutionTimes.executionTimes().end(component)
+ if res.Succeeded():
+ return res.GetOutput()
+ else:
+ self.fail("Command " + command + " returned an error")
+ return None
+ def getCategories(self):
+ return []
+
+class SanityCheckTestCase(LLDBTestCase):
+ def runTest(self):
+ ret = self.runCommand("show arch", "show-arch")
+ #print(ret)
+ def getCategories(self):
+ return []
+
+suite = unittest.TestLoader().loadTestsFromTestCase(SanityCheckTestCase)
+unittest.TextTestRunner(verbosity=2).run(suite)
+ExecutionTimes.executionTimes().dumpStats()
diff --git a/packages/Python/lldbsuite/test/bench-history b/packages/Python/lldbsuite/test/bench-history
new file mode 100644
index 000000000000..471332b25221
--- /dev/null
+++ b/packages/Python/lldbsuite/test/bench-history
@@ -0,0 +1,206 @@
+config: MacBook Pro (10.7.2)
+ 2.8 GHz Intel Core 2 Duo
+ 4 GB 1067 MHz DDR3
+
+r142707 (Oct 21, 2011):
+[17:45:55] johnny:/Volumes/data/lldb/svn/trunk/test $ ./bench.py 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.104274 (Laps: 30, Total Elapsed Time: 3.128214)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.102216 (Laps: 30, Total Elapsed Time: 3.066470)
+lldb frame variable benchmark: Avg: 1.649162 (Laps: 20, Total Elapsed Time: 32.983245)
+lldb stepping benchmark: Avg: 0.104409 (Laps: 50, Total Elapsed Time: 5.220461)
+lldb expr cmd benchmark: Avg: 0.206774 (Laps: 25, Total Elapsed Time: 5.169350)
+lldb disassembly benchmark: Avg: 0.089086 (Laps: 10, Total Elapsed Time: 0.890859)
+
+r142868 (Oct 24, 2011):
+[15:53:34] johnny:/Volumes/data/lldb/svn/trunk/test $ ./bench.py 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.105384 (Laps: 30, Total Elapsed Time: 3.161530)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.102334 (Laps: 30, Total Elapsed Time: 3.070012)
+lldb frame variable benchmark: Avg: 1.661701 (Laps: 20, Total Elapsed Time: 33.234026)
+lldb stepping benchmark: Avg: 0.107101 (Laps: 50, Total Elapsed Time: 5.355043)
+lldb expr cmd benchmark: Avg: 0.209475 (Laps: 25, Total Elapsed Time: 5.236863)
+lldb disassembly benchmark: Avg: 0.005543 (Laps: 10, Total Elapsed Time: 0.055426)
+[16:09:20] johnny:/Volumes/data/lldb/svn/trunk/test $ ./bench.py 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.103826 (Laps: 30, Total Elapsed Time: 3.114768)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.102312 (Laps: 30, Total Elapsed Time: 3.069371)
+lldb frame variable benchmark: Avg: 1.602898 (Laps: 20, Total Elapsed Time: 32.057950)
+lldb stepping benchmark: Avg: 0.104091 (Laps: 50, Total Elapsed Time: 5.204557)
+lldb expr cmd benchmark: Avg: 0.207095 (Laps: 25, Total Elapsed Time: 5.177363)
+lldb disassembly benchmark: Avg: 0.001531 (Laps: 10, Total Elapsed Time: 0.015311)
+
+r143065 (Oct 26, 2011):
+# Establish a baseline by using a fixed lldb executable as the inferior program
+# for the lldb debugger to operate on. The fixed lldb executable corresponds to
+# r142902.
+[15:50:34] johnny:/Volumes/data/lldb/svn/trunk/test $ ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.103774 (Laps: 30, Total Elapsed Time: 3.113226)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.102230 (Laps: 30, Total Elapsed Time: 3.066896)
+lldb startup delay (run to breakpoint) benchmark: Avg: 0.448635 (Laps: 30, Total Elapsed Time: 13.459048)
+lldb frame variable benchmark: Avg: 1.615647 (Laps: 20, Total Elapsed Time: 32.312934)
+lldb stepping benchmark: Avg: 0.138386 (Laps: 50, Total Elapsed Time: 6.919313)
+lldb expr cmd benchmark: Avg: 0.218967 (Laps: 25, Total Elapsed Time: 5.474171)
+lldb disassembly benchmark: Avg: 0.092677 (Laps: 10, Total Elapsed Time: 0.926766)
+
+# With patch to lldbbench.py to display min and max of samples.
+[17:27:09] johnny:/Volumes/data/lldb/svn/trunk/test $ ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.103625 (Laps: 30, Total Elapsed Time: 3.108748, min=0.101225, max=0.136308)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.102321 (Laps: 30, Total Elapsed Time: 3.069623, min=0.101270, max=0.102824)
+lldb startup delay (run to breakpoint) benchmark: Avg: 0.445943 (Laps: 30, Total Elapsed Time: 13.378290, min=0.438535, max=0.475691)
+lldb frame variable benchmark: Avg: 1.612034 (Laps: 20, Total Elapsed Time: 32.240689, min=1.591328, max=1.649720)
+lldb stepping benchmark: Avg: 0.155064 (Laps: 50, Total Elapsed Time: 7.753182, min=0.101287, max=2.028978)
+lldb expr cmd benchmark: Avg: 0.206160 (Laps: 25, Total Elapsed Time: 5.154005, min=0.203282, max=0.224982)
+lldb disassembly benchmark: Avg: 0.032946 (Laps: 10, Total Elapsed Time: 0.329464, min=0.031380, max=0.039198)
+
+r143118 (Oct 27, 2011):
+# No performance regression.
+[11:30:10] johnny:/Volumes/data/lldb/svn/trunk/test $ ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.109056 (Laps: 30, Total Elapsed Time: 3.271690, min=0.101212, max=0.296496)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.102844 (Laps: 30, Total Elapsed Time: 3.085306, min=0.101028, max=0.112504)
+lldb startup delay (run to breakpoint) benchmark: Avg: 0.467196 (Laps: 30, Total Elapsed Time: 14.015870, min=0.430639, max=1.059366)
+lldb frame variable benchmark: Avg: 1.615098 (Laps: 20, Total Elapsed Time: 32.301958, min=1.599064, max=1.665124)
+lldb stepping benchmark: Avg: 0.158506 (Laps: 50, Total Elapsed Time: 7.925285, min=0.101469, max=1.724667)
+lldb expr cmd benchmark: Avg: 0.232584 (Laps: 25, Total Elapsed Time: 5.814609, min=0.202931, max=0.782470)
+lldb disassembly benchmark: Avg: 0.090124 (Laps: 10, Total Elapsed Time: 0.901241, min=0.087497, max=0.099313)
+[11:37:23] johnny:/Volumes/data/lldb/svn/trunk/test $ ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.103782 (Laps: 30, Total Elapsed Time: 3.113456, min=0.101887, max=0.136767)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.102348 (Laps: 30, Total Elapsed Time: 3.070431, min=0.101648, max=0.102756)
+lldb startup delay (run to breakpoint) benchmark: Avg: 0.445628 (Laps: 30, Total Elapsed Time: 13.368829, min=0.438276, max=0.455466)
+lldb frame variable benchmark: Avg: 1.583635 (Laps: 20, Total Elapsed Time: 31.672710, min=0.133858, max=2.073698)
+lldb stepping benchmark: Avg: 0.157824 (Laps: 50, Total Elapsed Time: 7.891186, min=0.101352, max=2.172388)
+lldb expr cmd benchmark: Avg: 0.207600 (Laps: 25, Total Elapsed Time: 5.189992, min=0.203037, max=0.241189)
+lldb disassembly benchmark: Avg: 0.006725 (Laps: 10, Total Elapsed Time: 0.067249, min=0.002470, max=0.042690)
+
+r143199 (Oct 28, 2011):
+# No performance regression.
+[11:11:54] johnny:/Volumes/data/lldb/svn/trunk/test $ ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.104717 (Laps: 30, Total Elapsed Time: 3.141521, min=0.101881, max=0.162480)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.116985 (Laps: 30, Total Elapsed Time: 3.509554, min=0.101890, max=0.537634)
+lldb startup delay (run to breakpoint) benchmark: Avg: 0.462864 (Laps: 30, Total Elapsed Time: 13.885922, min=0.434867, max=0.877184)
+lldb frame variable benchmark: Avg: 1.749605 (Laps: 20, Total Elapsed Time: 34.992090, min=1.604043, max=2.365440)
+lldb stepping benchmark: Avg: 0.147439 (Laps: 50, Total Elapsed Time: 7.371955, min=0.101088, max=2.360912)
+lldb expr cmd benchmark: Avg: 0.210252 (Laps: 25, Total Elapsed Time: 5.256302, min=0.202591, max=0.258185)
+lldb disassembly benchmark: Avg: 0.028243 (Laps: 10, Total Elapsed Time: 0.282434, min=0.027451, max=0.031222)
+[11:16:16] johnny:/Volumes/data/lldb/svn/trunk/test $ ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.103913 (Laps: 30, Total Elapsed Time: 3.117384, min=0.101510, max=0.136605)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.102452 (Laps: 30, Total Elapsed Time: 3.073559, min=0.101508, max=0.105250)
+lldb startup delay (run to breakpoint) benchmark: Avg: 0.461532 (Laps: 30, Total Elapsed Time: 13.845950, min=0.436977, max=0.676502)
+lldb frame variable benchmark: Avg: 1.640990 (Laps: 20, Total Elapsed Time: 32.819801, min=1.583961, max=2.031209)
+lldb stepping benchmark: Avg: 0.104966 (Laps: 50, Total Elapsed Time: 5.248294, min=0.101296, max=0.240781)
+lldb expr cmd benchmark: Avg: 0.211872 (Laps: 25, Total Elapsed Time: 5.296811, min=0.203827, max=0.259524)
+lldb disassembly benchmark: Avg: 0.104108 (Laps: 10, Total Elapsed Time: 1.041076, min=0.089751, max=0.227173)
+
+r143260
+# No performance regression.
+[16:51:27] johnny:/Volumes/data/lldb/svn/trunk/test $ ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.103818 (Laps: 30, Total Elapsed Time: 3.114534, min=0.101654, max=0.135579)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.102786 (Laps: 30, Total Elapsed Time: 3.083594, min=0.101567, max=0.115159)
+lldb startup delay (run to breakpoint) benchmark: Avg: 0.444478 (Laps: 30, Total Elapsed Time: 13.334348, min=0.429840, max=0.514523)
+lldb frame variable benchmark: Avg: 1.627282 (Laps: 20, Total Elapsed Time: 32.545639, min=1.596098, max=1.768229)
+lldb stepping benchmark: Avg: 0.134925 (Laps: 50, Total Elapsed Time: 6.746272, min=0.101132, max=1.743882)
+lldb expr cmd benchmark: Avg: 0.209595 (Laps: 25, Total Elapsed Time: 5.239863, min=0.203182, max=0.255394)
+lldb disassembly benchmark: Avg: 0.091296 (Laps: 10, Total Elapsed Time: 0.912963, min=0.089690, max=0.103690)
+[17:31:27] johnny:/Volumes/data/lldb/svn/trunk/test $ ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.104030 (Laps: 30, Total Elapsed Time: 3.120891, min=0.101980, max=0.136737)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.102375 (Laps: 30, Total Elapsed Time: 3.071264, min=0.101454, max=0.103283)
+lldb startup delay (run to breakpoint) benchmark: Avg: 0.443155 (Laps: 30, Total Elapsed Time: 13.294637, min=0.434646, max=0.459273)
+lldb frame variable benchmark: Avg: 1.608266 (Laps: 20, Total Elapsed Time: 32.165314, min=1.596172, max=1.620366)
+lldb stepping benchmark: Avg: 0.104140 (Laps: 50, Total Elapsed Time: 5.207003, min=0.101436, max=0.196166)
+lldb expr cmd benchmark: Avg: 0.208264 (Laps: 25, Total Elapsed Time: 5.206604, min=0.204082, max=0.258287)
+lldb disassembly benchmark: Avg: 0.091677 (Laps: 10, Total Elapsed Time: 0.916773, min=0.090101, max=0.099648)
+
+r143359
+# No performance regression.
+[13:20:01] johnny:/Volumes/data/lldb/svn/trunk/test $ ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.106920 (Laps: 30, Total Elapsed Time: 3.207593, min=0.101197, max=0.197640)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.147324 (Laps: 30, Total Elapsed Time: 4.419733, min=0.101534, max=0.900991)
+lldb startup delay (run to breakpoint) benchmark: Avg: 0.463680 (Laps: 30, Total Elapsed Time: 13.910386, min=0.429071, max=0.872424)
+lldb frame variable benchmark: Avg: 1.655778 (Laps: 20, Total Elapsed Time: 33.115570, min=1.597218, max=1.779512)
+lldb stepping benchmark: Avg: 0.145967 (Laps: 50, Total Elapsed Time: 7.298373, min=0.101121, max=2.288423)
+lldb expr cmd benchmark: Avg: 0.207389 (Laps: 25, Total Elapsed Time: 5.184725, min=0.203226, max=0.240773)
+lldb disassembly benchmark: Avg: 0.091902 (Laps: 10, Total Elapsed Time: 0.919019, min=0.088413, max=0.115076)
+[13:24:24] johnny:/Volumes/data/lldb/svn/trunk/test $ ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.150258 (Laps: 30, Total Elapsed Time: 4.507753, min=0.101110, max=1.296165)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.192823 (Laps: 30, Total Elapsed Time: 5.784686, min=0.101897, max=0.697168)
+lldb startup delay (run to breakpoint) benchmark: Avg: 0.451879 (Laps: 30, Total Elapsed Time: 13.556380, min=0.428884, max=0.536964)
+lldb frame variable benchmark: Avg: 1.725232 (Laps: 20, Total Elapsed Time: 34.504649, min=1.596926, max=2.303283)
+lldb stepping benchmark: Avg: 0.111959 (Laps: 50, Total Elapsed Time: 5.597941, min=0.101375, max=0.586357)
+lldb expr cmd benchmark: Avg: 0.207557 (Laps: 25, Total Elapsed Time: 5.188913, min=0.203918, max=0.241022)
+lldb disassembly benchmark: Avg: 0.092959 (Laps: 10, Total Elapsed Time: 0.929594, min=0.089094, max=0.109135)
+
+r143469
+# No performance regression.
+[11:45:27] johnny:/Volumes/data/lldb/svn/trunk/test $ ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.112890 (Laps: 30, Total Elapsed Time: 3.386693, min=0.101696, max=0.414717)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.133955 (Laps: 30, Total Elapsed Time: 4.018643, min=0.101611, max=1.050222)
+lldb startup delay (run to breakpoint) benchmark: Avg: 0.470838 (Laps: 30, Total Elapsed Time: 14.125148, min=0.425866, max=1.437070)
+lldb frame variable benchmark: Avg: 1.608339 (Laps: 20, Total Elapsed Time: 32.166771, min=1.579538, max=1.721902)
+lldb stepping benchmark: Avg: 0.136881 (Laps: 50, Total Elapsed Time: 6.844043, min=0.101149, max=1.835094)
+lldb expr cmd benchmark: Avg: 0.207529 (Laps: 25, Total Elapsed Time: 5.188236, min=0.203476, max=0.241281)
+lldb disassembly benchmark: Avg: 0.036412 (Laps: 10, Total Elapsed Time: 0.364124, min=0.031895, max=0.069457)
+[12:14:54] johnny:/Volumes/data/lldb/svn/trunk/test $ ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.103313 (Laps: 30, Total Elapsed Time: 3.099402, min=0.101813, max=0.126989)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.102558 (Laps: 30, Total Elapsed Time: 3.076735, min=0.101576, max=0.107419)
+lldb startup delay (run to breakpoint) benchmark: Avg: 0.438302 (Laps: 30, Total Elapsed Time: 13.149063, min=0.431972, max=0.449742)
+lldb frame variable benchmark: Avg: 1.610409 (Laps: 20, Total Elapsed Time: 32.208184, min=1.575063, max=1.724046)
+lldb stepping benchmark: Avg: 0.103874 (Laps: 50, Total Elapsed Time: 5.193698, min=0.101364, max=0.186751)
+lldb expr cmd benchmark: Avg: 0.207476 (Laps: 25, Total Elapsed Time: 5.186895, min=0.203365, max=0.240869)
+lldb disassembly benchmark: Avg: 0.090917 (Laps: 10, Total Elapsed Time: 0.909167, min=0.089431, max=0.099787)
+
+r144546
+# Observed possible performance regression in lldb startup delay (run to breakpoint)?
+# Need more investigation.
+[11:27:23] johnny:/Volumes/data/lldb/svn/trunk/test $ ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.112386 (Laps: 30, Total Elapsed Time: 3.371577, min=0.101772, max=0.393109)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.108774 (Laps: 30, Total Elapsed Time: 3.263209, min=0.101605, max=0.292425)
+lldb startup delay (run to breakpoint) benchmark: Avg: 0.529530 (Laps: 30, Total Elapsed Time: 15.885899, min=0.468891, max=1.747227)
+lldb frame variable benchmark: Avg: 1.631610 (Laps: 20, Total Elapsed Time: 32.632193, min=1.575342, max=1.775941)
+lldb stepping benchmark: Avg: 0.146749 (Laps: 50, Total Elapsed Time: 7.337451, min=0.100780, max=2.165057)
+lldb expr cmd benchmark: Avg: 0.217782 (Laps: 25, Total Elapsed Time: 5.444553, min=0.203476, max=0.467801)
+lldb disassembly benchmark: Avg: 0.091264 (Laps: 10, Total Elapsed Time: 0.912644, min=0.088928, max=0.101681)
+[14:58:21] johnny:/Volumes/data/lldb/svn/trunk/test $ ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.105535 (Laps: 30, Total Elapsed Time: 3.166062, min=0.101935, max=0.147107)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.102372 (Laps: 30, Total Elapsed Time: 3.071164, min=0.100945, max=0.102721)
+lldb startup delay (run to breakpoint) benchmark: Avg: 0.483826 (Laps: 30, Total Elapsed Time: 14.514786, min=0.471770, max=0.532260)
+lldb frame variable benchmark: Avg: 1.576992 (Laps: 20, Total Elapsed Time: 31.539838, min=0.102487, max=2.098732)
+lldb stepping benchmark: Avg: 0.102836 (Laps: 50, Total Elapsed Time: 5.141815, min=0.101461, max=0.122378)
+lldb expr cmd benchmark: Avg: 0.206334 (Laps: 25, Total Elapsed Time: 5.158355, min=0.203804, max=0.241043)
+lldb disassembly benchmark: Avg: 0.033536 (Laps: 10, Total Elapsed Time: 0.335359, min=0.031975, max=0.041612)
+[15:01:59] johnny:/Volumes/data/lldb/svn/trunk/test $
+
+# Redid the r143469 measurements (svn/regress dir) right before the r145371 measurements (svn/trunk dir) on 10.7.2 (build 11C74).
+# The lldb startup delay (run to breakpoint) in avg is not as significant. The min still shows some possible regression.
+# The frame variable benchmark shows some possible regression.
+[10:51:56] johnny:/Volumes/data/lldb/svn/regress/test $ ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.109821 (Laps: 30, Total Elapsed Time: 3.294643, min=0.101836, max=0.297468)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.121465 (Laps: 30, Total Elapsed Time: 3.643950, min=0.100776, max=0.665900)
+lldb startup delay (run to breakpoint) benchmark: Avg: 0.501870 (Laps: 30, Total Elapsed Time: 15.056112, min=0.469871, max=0.718775)
+lldb frame variable benchmark: Avg: 1.663890 (Laps: 20, Total Elapsed Time: 33.277791, min=1.584265, max=1.999998)
+lldb stepping benchmark: Avg: 0.105434 (Laps: 50, Total Elapsed Time: 5.271683, min=0.101120, max=0.256289)
+lldb expr cmd benchmark: Avg: 0.240440 (Laps: 25, Total Elapsed Time: 6.011000, min=0.203547, max=0.956405)
+lldb disassembly benchmark: Avg: 0.096988 (Laps: 10, Total Elapsed Time: 0.969877, min=0.089511, max=0.147797)
+[10:55:38] johnny:/Volumes/data/lldb/svn/regress/test $ ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.107368 (Laps: 30, Total Elapsed Time: 3.221026, min=0.101374, max=0.163785)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.153588 (Laps: 30, Total Elapsed Time: 4.607645, min=0.101554, max=0.776372)
+lldb startup delay (run to breakpoint) benchmark: Avg: 0.510726 (Laps: 30, Total Elapsed Time: 15.321779, min=0.468395, max=0.643357)
+lldb frame variable benchmark: Avg: 1.715136 (Laps: 20, Total Elapsed Time: 34.302718, min=1.527872, max=3.125777)
+lldb stepping benchmark: Avg: 0.116140 (Laps: 50, Total Elapsed Time: 5.807012, min=0.100857, max=0.796673)
+lldb expr cmd benchmark: Avg: 0.206397 (Laps: 25, Total Elapsed Time: 5.159914, min=0.203491, max=0.241283)
+lldb disassembly benchmark: Avg: 0.036542 (Laps: 10, Total Elapsed Time: 0.365422, min=0.031872, max=0.060183)
+[10:59:43] johnny:/Volumes/data/lldb/svn/regress/test $ pushd +1
+/Volumes/data/lldb/svn/trunk/test /Volumes/data/lldb/llvm /Volumes/data/lldb/svn/regress/test
+[10:59:48] johnny:/Volumes/data/lldb/svn/trunk/test $ ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.103919 (Laps: 30, Total Elapsed Time: 3.117560, min=0.101766, max=0.137548)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.102705 (Laps: 30, Total Elapsed Time: 3.081165, min=0.101311, max=0.114192)
+lldb startup delay (run to breakpoint) benchmark: Avg: 0.504830 (Laps: 30, Total Elapsed Time: 15.144906, min=0.483528, max=0.627122)
+lldb frame variable benchmark: Avg: 1.924774 (Laps: 20, Total Elapsed Time: 38.495475, min=1.798745, max=2.248269)
+lldb stepping benchmark: Avg: 0.102595 (Laps: 50, Total Elapsed Time: 5.129757, min=0.100690, max=0.125930)
+lldb expr cmd benchmark: Avg: 0.205395 (Laps: 25, Total Elapsed Time: 5.134883, min=0.202864, max=0.210484)
+lldb disassembly benchmark: Avg: 0.033576 (Laps: 10, Total Elapsed Time: 0.335765, min=0.032021, max=0.039222)
+[11:03:46] johnny:/Volumes/data/lldb/svn/trunk/test $ ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:'
+lldb startup delay (create fresh target) benchmark: Avg: 0.103371 (Laps: 30, Total Elapsed Time: 3.101121, min=0.101556, max=0.127819)
+lldb startup delay (set first breakpoint) benchmark: Avg: 0.103174 (Laps: 30, Total Elapsed Time: 3.095230, min=0.101763, max=0.114733)
+lldb startup delay (run to breakpoint) benchmark: Avg: 0.513848 (Laps: 30, Total Elapsed Time: 15.415439, min=0.490004, max=0.748310)
+lldb frame variable benchmark: Avg: 1.906068 (Laps: 20, Total Elapsed Time: 38.121364, min=1.872328, max=2.044472)
+lldb stepping benchmark: Avg: 0.254817 (Laps: 50, Total Elapsed Time: 12.740872, min=0.100743, max=7.628899)
+lldb expr cmd benchmark: Avg: 0.207850 (Laps: 25, Total Elapsed Time: 5.196255, min=0.203986, max=0.257482)
+lldb disassembly benchmark: Avg: 0.092003 (Laps: 10, Total Elapsed Time: 0.920026, min=0.089568, max=0.100374)
+[11:07:53] johnny:/Volumes/data/lldb/svn/trunk/test $
diff --git a/packages/Python/lldbsuite/test/bench.py b/packages/Python/lldbsuite/test/bench.py
new file mode 100644
index 000000000000..ce9c2e75d711
--- /dev/null
+++ b/packages/Python/lldbsuite/test/bench.py
@@ -0,0 +1,74 @@
+#!/usr/bin/env python
+
+"""
+A simple bench runner which delegates to the ./dotest.py test driver to run the
+benchmarks defined in the list named 'benches'.
+
+You need to hand edit 'benches' to modify/change the command lines passed to the
+test driver.
+
+Use the following to get only the benchmark results in your terminal output:
+
+ ./bench.py -e /Volumes/data/lldb/svn/regression/build/Debug/lldb -x '-F Driver::MainLoop()' 2>&1 | grep -P '^lldb.*benchmark:'
+
+See also bench-history.
+"""
+
+from __future__ import print_function
+from __future__ import absolute_import
+
+import os, sys
+import re
+from optparse import OptionParser
+
+# dotest.py invocation with no '-e exe-path' uses lldb as the inferior program,
+# unless there is a mentioning of custom executable program.
+benches = [
+ # Measure startup delays creating a target, setting a breakpoint, and run to breakpoint stop.
+ './dotest.py -v +b %E %X -n -p TestStartupDelays.py',
+
+ # Measure 'frame variable' response after stopping at a breakpoint.
+ './dotest.py -v +b %E %X -n -p TestFrameVariableResponse.py',
+
+ # Measure stepping speed after stopping at a breakpoint.
+ './dotest.py -v +b %E %X -n -p TestSteppingSpeed.py',
+
+ # Measure expression cmd response with a simple custom executable program.
+ './dotest.py +b -n -p TestExpressionCmd.py',
+
+ # Attach to a spawned process then run disassembly benchmarks.
+ './dotest.py -v +b -n %E -p TestDoAttachThenDisassembly.py'
+]
+
+def main():
+ """Read the items from 'benches' and run the command line one by one."""
+ parser = OptionParser(usage="""\
+%prog [options]
+Run the standard benchmarks defined in the list named 'benches'.\
+""")
+ parser.add_option('-e', '--executable',
+ type='string', action='store',
+ dest='exe',
+ help='The target program launched by lldb.')
+ parser.add_option('-x', '--breakpoint-spec',
+ type='string', action='store',
+ dest='break_spec',
+ help='The lldb breakpoint spec for the target program.')
+
+ # Parses the options, if any.
+ opts, args = parser.parse_args()
+
+ print("Starting bench runner....")
+
+ for item in benches:
+ command = item.replace('%E',
+ '-e "%s"' % opts.exe if opts.exe else '')
+ command = command.replace('%X',
+ '-x "%s"' % opts.break_spec if opts.break_spec else '')
+ print("Running %s" % (command))
+ os.system(command)
+
+ print("Bench runner done.")
+
+if __name__ == '__main__':
+ main()
diff --git a/packages/Python/lldbsuite/test/benchmarks/continue/Makefile b/packages/Python/lldbsuite/test/benchmarks/continue/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/benchmarks/continue/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/benchmarks/continue/TestBenchmarkContinue.py b/packages/Python/lldbsuite/test/benchmarks/continue/TestBenchmarkContinue.py
new file mode 100644
index 000000000000..25ca13a3bfd9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/benchmarks/continue/TestBenchmarkContinue.py
@@ -0,0 +1,66 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbbench import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TestBenchmarkContinue(BenchBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @benchmarks_test
+ def test_run_command(self):
+ """Benchmark different ways to continue a process"""
+ self.build()
+ self.data_formatter_commands()
+
+ def setUp(self):
+ # Call super's setUp().
+ BenchBase.setUp(self)
+
+ def data_formatter_commands(self):
+ """Benchmark different ways to continue a process"""
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ bkpt = self.target().FindBreakpointByID(lldbutil.run_break_set_by_source_regexp (self, "// break here"))
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ runCmd_sw = Stopwatch()
+ lldbutil_sw = Stopwatch()
+
+ for i in range(0,15):
+ runCmd_sw.start()
+ self.runCmd("continue")
+ runCmd_sw.stop()
+
+ for i in range(0,15):
+ lldbutil_sw.start()
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+ lldbutil_sw.stop()
+
+ print("runCmd: %s\nlldbutil: %s" % (runCmd_sw,lldbutil_sw))
diff --git a/packages/Python/lldbsuite/test/benchmarks/continue/main.cpp b/packages/Python/lldbsuite/test/benchmarks/continue/main.cpp
new file mode 100644
index 000000000000..d715a1150d06
--- /dev/null
+++ b/packages/Python/lldbsuite/test/benchmarks/continue/main.cpp
@@ -0,0 +1,36 @@
+#include <map>
+
+#define intint_map std::map<int, int>
+
+int g_the_foo = 0;
+
+int thefoo_rw(int arg = 1)
+{
+ if (arg < 0)
+ arg = 0;
+ if (!arg)
+ arg = 1;
+ g_the_foo += arg;
+ return g_the_foo;
+}
+
+int main()
+{
+ intint_map ii;
+
+ for (int i = 0; i < 15; i++)
+ {
+ ii[i] = i + 1;
+ thefoo_rw(i); // break here
+ }
+
+ ii.clear();
+
+ for (int j = 0; j < 15; j++)
+ {
+ ii[j] = j + 1;
+ thefoo_rw(j); // break here
+ }
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/benchmarks/disassembly/TestDisassembly.py b/packages/Python/lldbsuite/test/benchmarks/disassembly/TestDisassembly.py
new file mode 100644
index 000000000000..a18cb2a64c76
--- /dev/null
+++ b/packages/Python/lldbsuite/test/benchmarks/disassembly/TestDisassembly.py
@@ -0,0 +1,155 @@
+"""Disassemble lldb's Driver::MainLoop() functions comparing lldb against gdb."""
+
+from __future__ import print_function
+
+
+
+import os, sys
+import lldb
+from lldbsuite.test import configuration
+from lldbsuite.test.lldbbench import *
+
+def is_exe(fpath):
+ """Returns true if fpath is an executable."""
+ return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
+
+class DisassembleDriverMainLoop(BenchBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ """
+ Note that lldbtest_config.lldbExec can be specified with the LLDB_EXEC env variable (see
+ dotest.py), and gdbExec can be specified with the GDB_EXEC env variable.
+ This provides a flexibility in specifying different versions of gdb for
+ comparison purposes.
+ """
+ BenchBase.setUp(self)
+ # If env var GDB_EXEC is specified, use it; otherwise, use gdb in your
+ # PATH env var.
+ if "GDB_EXEC" in os.environ and is_exe(os.environ["GDB_EXEC"]):
+ self.gdbExec = os.environ["GDB_EXEC"]
+ else:
+ self.gdbExec = "gdb"
+
+ self.exe = lldbtest_config.lldbExec
+ self.function = 'Driver::MainLoop()'
+ self.lldb_avg = None
+ self.gdb_avg = None
+ self.count = 5
+
+ @benchmarks_test
+ @no_debug_info_test
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ def test_run_lldb_then_gdb(self):
+ """Test disassembly on a large function with lldb vs. gdb."""
+ print()
+ print("lldb path: %s" % lldbtest_config.lldbExec)
+ print("gdb path: %s" % self.gdbExec)
+
+ print()
+ self.run_lldb_disassembly(self.exe, self.function, self.count)
+ print("lldb benchmark:", self.stopwatch)
+ self.run_gdb_disassembly(self.exe, self.function, self.count)
+ print("gdb benchmark:", self.stopwatch)
+ print("lldb_avg/gdb_avg: %f" % (self.lldb_avg/self.gdb_avg))
+
+ @benchmarks_test
+ @no_debug_info_test
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ def test_run_gdb_then_lldb(self):
+ """Test disassembly on a large function with lldb vs. gdb."""
+ print()
+ print("lldb path: %s" % lldbtest_config.lldbExec)
+ print("gdb path: %s" % self.gdbExec)
+
+ print()
+ self.run_gdb_disassembly(self.exe, self.function, self.count)
+ print("gdb benchmark:", self.stopwatch)
+ self.run_lldb_disassembly(self.exe, self.function, self.count)
+ print("lldb benchmark:", self.stopwatch)
+ print("lldb_avg/gdb_avg: %f" % (self.lldb_avg/self.gdb_avg))
+
+ def run_lldb_disassembly(self, exe, function, count):
+ import pexpect
+ # Set self.child_prompt, which is "(lldb) ".
+ self.child_prompt = '(lldb) '
+ prompt = self.child_prompt
+
+ # So that the child gets torn down after the test.
+ self.child = pexpect.spawn('%s %s %s' % (lldbtest_config.lldbExec, self.lldbOption, exe))
+ child = self.child
+
+ # Turn on logging for what the child sends back.
+ if self.TraceOn():
+ child.logfile_read = sys.stdout
+
+ child.expect_exact(prompt)
+ child.sendline('breakpoint set -F %s' % function)
+ child.expect_exact(prompt)
+ child.sendline('run')
+ child.expect_exact(prompt)
+
+ # Reset the stopwatch now.
+ self.stopwatch.reset()
+ for i in range(count):
+ with self.stopwatch:
+ # Disassemble the function.
+ child.sendline('disassemble -f')
+ child.expect_exact(prompt)
+ child.sendline('next')
+ child.expect_exact(prompt)
+
+ child.sendline('quit')
+ try:
+ self.child.expect(pexpect.EOF)
+ except:
+ pass
+
+ self.lldb_avg = self.stopwatch.avg()
+ if self.TraceOn():
+ print("lldb disassembly benchmark:", str(self.stopwatch))
+ self.child = None
+
+ def run_gdb_disassembly(self, exe, function, count):
+ import pexpect
+ # Set self.child_prompt, which is "(gdb) ".
+ self.child_prompt = '(gdb) '
+ prompt = self.child_prompt
+
+ # So that the child gets torn down after the test.
+ self.child = pexpect.spawn('%s --nx %s' % (self.gdbExec, exe))
+ child = self.child
+
+ # Turn on logging for what the child sends back.
+ if self.TraceOn():
+ child.logfile_read = sys.stdout
+
+ child.expect_exact(prompt)
+ child.sendline('break %s' % function)
+ child.expect_exact(prompt)
+ child.sendline('run')
+ child.expect_exact(prompt)
+
+ # Reset the stopwatch now.
+ self.stopwatch.reset()
+ for i in range(count):
+ with self.stopwatch:
+ # Disassemble the function.
+ child.sendline('disassemble')
+ child.expect_exact(prompt)
+ child.sendline('next')
+ child.expect_exact(prompt)
+
+ child.sendline('quit')
+ child.expect_exact('The program is running. Exit anyway?')
+ child.sendline('y')
+ try:
+ self.child.expect(pexpect.EOF)
+ except:
+ pass
+
+ self.gdb_avg = self.stopwatch.avg()
+ if self.TraceOn():
+ print("gdb disassembly benchmark:", str(self.stopwatch))
+ self.child = None
diff --git a/packages/Python/lldbsuite/test/benchmarks/disassembly/TestDoAttachThenDisassembly.py b/packages/Python/lldbsuite/test/benchmarks/disassembly/TestDoAttachThenDisassembly.py
new file mode 100644
index 000000000000..b7b07090959e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/benchmarks/disassembly/TestDoAttachThenDisassembly.py
@@ -0,0 +1,67 @@
+"""Test lldb's disassemblt speed. This bench deliberately attaches to an lldb
+inferior and traverses the stack for thread0 to arrive at frame with function
+'MainLoop'. It is important to specify an lldb executable as the inferior."""
+
+from __future__ import print_function
+
+
+
+import os, sys
+import lldb
+from lldbsuite.test.lldbbench import *
+from lldbsuite.test import configuration
+
+class AttachThenDisassemblyBench(BenchBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ BenchBase.setUp(self)
+ self.exe = lldbtest_config.lldbExec
+ self.count = 10
+
+ @benchmarks_test
+ @no_debug_info_test
+ def test_attach_then_disassembly(self):
+ """Attach to a spawned lldb process then run disassembly benchmarks."""
+ print()
+ self.run_lldb_attach_then_disassembly(self.exe, self.count)
+ print("lldb disassembly benchmark:", self.stopwatch)
+
+ def run_lldb_attach_then_disassembly(self, exe, count):
+ target = self.dbg.CreateTarget(exe)
+
+ # Spawn a new process and don't display the stdout if not in TraceOn() mode.
+ import subprocess
+ popen = subprocess.Popen([exe, self.lldbOption],
+ stdout = open(os.devnull, 'w') if not self.TraceOn() else None)
+ if self.TraceOn():
+ print("pid of spawned process: %d" % popen.pid)
+
+ # Attach to the launched lldb process.
+ listener = lldb.SBListener("my.attach.listener")
+ error = lldb.SBError()
+ process = target.AttachToProcessWithID(listener, popen.pid, error)
+
+ # Set thread0 as the selected thread, followed by the 'MainLoop' frame
+ # as the selected frame. Then do disassembly on the function.
+ thread0 = process.GetThreadAtIndex(0)
+ process.SetSelectedThread(thread0)
+ i = 0
+ found = False
+ for f in thread0:
+ #print("frame#%d %s" % (i, f.GetFunctionName()))
+ if "MainLoop" in f.GetFunctionName():
+ found = True
+ thread0.SetSelectedFrame(i)
+ if self.TraceOn():
+ print("Found frame#%d for function 'MainLoop'" % i)
+ break
+ i += 1
+
+ # Reset the stopwatch now.
+ self.stopwatch.reset()
+ for i in range(count):
+ with self.stopwatch:
+ # Disassemble the function.
+ self.runCmd("disassemble -f")
diff --git a/packages/Python/lldbsuite/test/benchmarks/disassembly/TestXcode41Vs42GDBDisassembly.py b/packages/Python/lldbsuite/test/benchmarks/disassembly/TestXcode41Vs42GDBDisassembly.py
new file mode 100644
index 000000000000..745e7b6a8c3b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/benchmarks/disassembly/TestXcode41Vs42GDBDisassembly.py
@@ -0,0 +1,94 @@
+"""Disassemble lldb's Driver::MainLoop() functions comparing Xcode 4.1 vs. 4.2's gdb."""
+
+from __future__ import print_function
+
+
+
+import os, sys
+import lldb
+from lldbsuite.test import configuration
+from lldbsuite.test.lldbbench import *
+
+class XCode41Vs42GDBDisassembly(BenchBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ BenchBase.setUp(self)
+ self.gdb_41_exe = '/Xcode41/usr/bin/gdb'
+ self.gdb_42_exe = '/Developer/usr/bin/gdb'
+ self.exe = lldbtest_config.lldbExec
+ self.function = 'Driver::MainLoop()'
+ self.gdb_41_avg = None
+ self.gdb_42_avg = None
+ self.count = 5
+
+ @benchmarks_test
+ @no_debug_info_test
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ def test_run_41_then_42(self):
+ """Test disassembly on a large function with 4.1 vs. 4.2's gdb."""
+ print()
+ self.run_gdb_disassembly(self.gdb_41_exe, self.exe, self.function, self.count)
+ print("4.1 gdb benchmark:", self.stopwatch)
+ self.gdb_41_avg = self.stopwatch.avg()
+ self.run_gdb_disassembly(self.gdb_42_exe, self.exe, self.function, self.count)
+ print("4.2 gdb benchmark:", self.stopwatch)
+ self.gdb_42_avg = self.stopwatch.avg()
+ print("gdb_42_avg/gdb_41_avg: %f" % (self.gdb_42_avg/self.gdb_41_avg))
+
+ @benchmarks_test
+ @no_debug_info_test
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ def test_run_42_then_41(self):
+ """Test disassembly on a large function with 4.1 vs. 4.2's gdb."""
+ print()
+ self.run_gdb_disassembly(self.gdb_42_exe, self.exe, self.function, self.count)
+ print("4.2 gdb benchmark:", self.stopwatch)
+ self.gdb_42_avg = self.stopwatch.avg()
+ self.run_gdb_disassembly(self.gdb_41_exe, self.exe, self.function, self.count)
+ print("4.1 gdb benchmark:", self.stopwatch)
+ self.gdb_41_avg = self.stopwatch.avg()
+ print("gdb_42_avg/gdb_41_avg: %f" % (self.gdb_42_avg/self.gdb_41_avg))
+
+ def run_gdb_disassembly(self, gdb_exe_path, exe, function, count):
+ import pexpect
+ # Set self.child_prompt, which is "(gdb) ".
+ self.child_prompt = '(gdb) '
+ prompt = self.child_prompt
+
+ # So that the child gets torn down after the test.
+ self.child = pexpect.spawn('%s --nx %s' % (gdb_exe_path, exe))
+ child = self.child
+
+ # Turn on logging for what the child sends back.
+ if self.TraceOn():
+ child.logfile_read = sys.stdout
+
+ child.expect_exact(prompt)
+ child.sendline('break %s' % function)
+ child.expect_exact(prompt)
+ child.sendline('run')
+ child.expect_exact(prompt)
+
+ # Reset the stopwatch now.
+ self.stopwatch.reset()
+ for i in range(count):
+ with self.stopwatch:
+ # Disassemble the function.
+ child.sendline('disassemble')
+ child.expect_exact(prompt)
+ child.sendline('next')
+ child.expect_exact(prompt)
+
+ child.sendline('quit')
+ child.expect_exact('The program is running. Exit anyway?')
+ child.sendline('y')
+ try:
+ self.child.expect(pexpect.EOF)
+ except:
+ pass
+
+ if self.TraceOn():
+ print("gdb disassembly benchmark:", str(self.stopwatch))
+ self.child = None
diff --git a/packages/Python/lldbsuite/test/benchmarks/expression/Makefile b/packages/Python/lldbsuite/test/benchmarks/expression/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/benchmarks/expression/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/benchmarks/expression/TestExpressionCmd.py b/packages/Python/lldbsuite/test/benchmarks/expression/TestExpressionCmd.py
new file mode 100644
index 000000000000..abf45147d636
--- /dev/null
+++ b/packages/Python/lldbsuite/test/benchmarks/expression/TestExpressionCmd.py
@@ -0,0 +1,72 @@
+"""Test lldb's expression evaluations and collect statistics."""
+
+from __future__ import print_function
+
+
+
+import os, sys
+import lldb
+from lldbsuite.test import configuration
+from lldbsuite.test.lldbbench import *
+
+class ExpressionEvaluationCase(BenchBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ BenchBase.setUp(self)
+ self.source = 'main.cpp'
+ self.line_to_break = line_number(self.source, '// Set breakpoint here.')
+ self.count = 25
+
+ @benchmarks_test
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ def test_expr_cmd(self):
+ """Test lldb's expression commands and collect statistics."""
+ self.build()
+ self.exe_name = 'a.out'
+
+ print()
+ self.run_lldb_repeated_exprs(self.exe_name, self.count)
+ print("lldb expr cmd benchmark:", self.stopwatch)
+
+ def run_lldb_repeated_exprs(self, exe_name, count):
+ import pexpect
+ exe = os.path.join(os.getcwd(), exe_name)
+
+ # Set self.child_prompt, which is "(lldb) ".
+ self.child_prompt = '(lldb) '
+ prompt = self.child_prompt
+
+ # Reset the stopwatch now.
+ self.stopwatch.reset()
+ for i in range(count):
+ # So that the child gets torn down after the test.
+ self.child = pexpect.spawn('%s %s %s' % (lldbtest_config.lldbExec, self.lldbOption, exe))
+ child = self.child
+
+ # Turn on logging for what the child sends back.
+ if self.TraceOn():
+ child.logfile_read = sys.stdout
+
+ child.expect_exact(prompt)
+ child.sendline('breakpoint set -f %s -l %d' % (self.source, self.line_to_break))
+ child.expect_exact(prompt)
+ child.sendline('run')
+ child.expect_exact(prompt)
+ expr_cmd1 = 'expr ptr[j]->point.x'
+ expr_cmd2 = 'expr ptr[j]->point.y'
+
+ with self.stopwatch:
+ child.sendline(expr_cmd1)
+ child.expect_exact(prompt)
+ child.sendline(expr_cmd2)
+ child.expect_exact(prompt)
+
+ child.sendline('quit')
+ try:
+ self.child.expect(pexpect.EOF)
+ except:
+ pass
+
+ self.child = None
diff --git a/packages/Python/lldbsuite/test/benchmarks/expression/TestRepeatedExprs.py b/packages/Python/lldbsuite/test/benchmarks/expression/TestRepeatedExprs.py
new file mode 100644
index 000000000000..e5cada3563fa
--- /dev/null
+++ b/packages/Python/lldbsuite/test/benchmarks/expression/TestRepeatedExprs.py
@@ -0,0 +1,130 @@
+"""Test evaluating expressions repeatedly comparing lldb against gdb."""
+
+from __future__ import print_function
+
+
+
+import os, sys
+import lldb
+from lldbsuite.test import configuration
+from lldbsuite.test.lldbbench import *
+
+class RepeatedExprsCase(BenchBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ BenchBase.setUp(self)
+ self.source = 'main.cpp'
+ self.line_to_break = line_number(self.source, '// Set breakpoint here.')
+ self.lldb_avg = None
+ self.gdb_avg = None
+ self.count = 100
+
+ @benchmarks_test
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ def test_compare_lldb_to_gdb(self):
+ """Test repeated expressions with lldb vs. gdb."""
+ self.build()
+ self.exe_name = 'a.out'
+
+ print()
+ self.run_lldb_repeated_exprs(self.exe_name, self.count)
+ print("lldb benchmark:", self.stopwatch)
+ self.run_gdb_repeated_exprs(self.exe_name, self.count)
+ print("gdb benchmark:", self.stopwatch)
+ print("lldb_avg/gdb_avg: %f" % (self.lldb_avg/self.gdb_avg))
+
+ def run_lldb_repeated_exprs(self, exe_name, count):
+ import pexpect
+ exe = os.path.join(os.getcwd(), exe_name)
+
+ # Set self.child_prompt, which is "(lldb) ".
+ self.child_prompt = '(lldb) '
+ prompt = self.child_prompt
+
+ # So that the child gets torn down after the test.
+ self.child = pexpect.spawn('%s %s %s' % (lldbtest_config.lldbExec, self.lldbOption, exe))
+ child = self.child
+
+ # Turn on logging for what the child sends back.
+ if self.TraceOn():
+ child.logfile_read = sys.stdout
+
+ child.expect_exact(prompt)
+ child.sendline('breakpoint set -f %s -l %d' % (self.source, self.line_to_break))
+ child.expect_exact(prompt)
+ child.sendline('run')
+ child.expect_exact(prompt)
+ expr_cmd1 = 'expr ptr[j]->point.x'
+ expr_cmd2 = 'expr ptr[j]->point.y'
+
+ # Reset the stopwatch now.
+ self.stopwatch.reset()
+ for i in range(count):
+ with self.stopwatch:
+ child.sendline(expr_cmd1)
+ child.expect_exact(prompt)
+ child.sendline(expr_cmd2)
+ child.expect_exact(prompt)
+ child.sendline('process continue')
+ child.expect_exact(prompt)
+
+ child.sendline('quit')
+ try:
+ self.child.expect(pexpect.EOF)
+ except:
+ pass
+
+ self.lldb_avg = self.stopwatch.avg()
+ if self.TraceOn():
+ print("lldb expression benchmark:", str(self.stopwatch))
+ self.child = None
+
+ def run_gdb_repeated_exprs(self, exe_name, count):
+ import pexpect
+ exe = os.path.join(os.getcwd(), exe_name)
+
+ # Set self.child_prompt, which is "(gdb) ".
+ self.child_prompt = '(gdb) '
+ prompt = self.child_prompt
+
+ # So that the child gets torn down after the test.
+ self.child = pexpect.spawn('gdb --nx %s' % exe)
+ child = self.child
+
+ # Turn on logging for what the child sends back.
+ if self.TraceOn():
+ child.logfile_read = sys.stdout
+
+ child.expect_exact(prompt)
+ child.sendline('break %s:%d' % (self.source, self.line_to_break))
+ child.expect_exact(prompt)
+ child.sendline('run')
+ child.expect_exact(prompt)
+ expr_cmd1 = 'print ptr[j]->point.x'
+ expr_cmd2 = 'print ptr[j]->point.y'
+
+ # Reset the stopwatch now.
+ self.stopwatch.reset()
+ for i in range(count):
+ with self.stopwatch:
+ child.sendline(expr_cmd1)
+ child.expect_exact(prompt)
+ child.sendline(expr_cmd2)
+ child.expect_exact(prompt)
+ child.sendline('continue')
+ child.expect_exact(prompt)
+
+ child.sendline('quit')
+ child.expect_exact('The program is running. Exit anyway?')
+ child.sendline('y')
+ try:
+ self.child.expect(pexpect.EOF)
+ except:
+ pass
+
+ self.gdb_avg = self.stopwatch.avg()
+ if self.TraceOn():
+ print("gdb expression benchmark:", str(self.stopwatch))
+ self.child = None
diff --git a/packages/Python/lldbsuite/test/benchmarks/expression/main.cpp b/packages/Python/lldbsuite/test/benchmarks/expression/main.cpp
new file mode 100644
index 000000000000..8f2706e26388
--- /dev/null
+++ b/packages/Python/lldbsuite/test/benchmarks/expression/main.cpp
@@ -0,0 +1,51 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+class Point {
+public:
+ int x;
+ int y;
+ Point(int a, int b):
+ x(a),
+ y(b)
+ {}
+};
+
+class Data {
+public:
+ int id;
+ Point point;
+ Data(int i):
+ id(i),
+ point(0, 0)
+ {}
+};
+
+int main(int argc, char const *argv[]) {
+ Data *data[1000];
+ Data **ptr = data;
+ for (int i = 0; i < 1000; ++i) {
+ ptr[i] = new Data(i);
+ ptr[i]->point.x = i;
+ ptr[i]->point.y = i+1;
+ }
+
+ printf("Finished populating data.\n");
+ for (int j = 0; j < 1000; ++j) {
+ bool dump = argc > 1; // Set breakpoint here.
+ // Evaluate a couple of expressions (2*1000 = 2000 exprs):
+ // expr ptr[j]->point.x
+ // expr ptr[j]->point.y
+ if (dump) {
+ printf("data[%d] = %d (%d, %d)\n", j, ptr[j]->id, ptr[j]->point.x, ptr[j]->point.y);
+ }
+ }
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/benchmarks/frame_variable/TestFrameVariableResponse.py b/packages/Python/lldbsuite/test/benchmarks/frame_variable/TestFrameVariableResponse.py
new file mode 100644
index 000000000000..5fdf05763fd1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/benchmarks/frame_variable/TestFrameVariableResponse.py
@@ -0,0 +1,70 @@
+"""Test lldb's response time for 'frame variable' command."""
+
+from __future__ import print_function
+
+
+
+import os, sys
+import lldb
+from lldbsuite.test import configuration
+from lldbsuite.test import lldbtest_config
+from lldbsuite.test.lldbbench import *
+
+class FrameVariableResponseBench(BenchBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ BenchBase.setUp(self)
+ self.exe = lldbtest_config.lldbExec
+ self.break_spec = '-n main'
+ self.count = 20
+
+ @benchmarks_test
+ @no_debug_info_test
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ def test_startup_delay(self):
+ """Test response time for the 'frame variable' command."""
+ print()
+ self.run_frame_variable_bench(self.exe, self.break_spec, self.count)
+ print("lldb frame variable benchmark:", self.stopwatch)
+
+ def run_frame_variable_bench(self, exe, break_spec, count):
+ import pexpect
+ # Set self.child_prompt, which is "(lldb) ".
+ self.child_prompt = '(lldb) '
+ prompt = self.child_prompt
+
+ # Reset the stopwatchs now.
+ self.stopwatch.reset()
+ for i in range(count):
+ # So that the child gets torn down after the test.
+ self.child = pexpect.spawn('%s %s %s' % (lldbtest_config.lldbExec, self.lldbOption, exe))
+ child = self.child
+
+ # Turn on logging for what the child sends back.
+ if self.TraceOn():
+ child.logfile_read = sys.stdout
+
+ # Set our breakpoint.
+ child.sendline('breakpoint set %s' % break_spec)
+ child.expect_exact(prompt)
+
+ # Run the target and expect it to be stopped due to breakpoint.
+ child.sendline('run') # Aka 'process launch'.
+ child.expect_exact(prompt)
+
+ with self.stopwatch:
+ # Measure the 'frame variable' response time.
+ child.sendline('frame variable')
+ child.expect_exact(prompt)
+
+ child.sendline('quit')
+ try:
+ self.child.expect(pexpect.EOF)
+ except:
+ pass
+
+ # The test is about to end and if we come to here, the child process has
+ # been terminated. Mark it so.
+ self.child = None
diff --git a/packages/Python/lldbsuite/test/benchmarks/libcxxlist/Makefile b/packages/Python/lldbsuite/test/benchmarks/libcxxlist/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/benchmarks/libcxxlist/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/benchmarks/libcxxlist/TestBenchmarkLibcxxList.py b/packages/Python/lldbsuite/test/benchmarks/libcxxlist/TestBenchmarkLibcxxList.py
new file mode 100644
index 000000000000..7606bd1d3e8b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/benchmarks/libcxxlist/TestBenchmarkLibcxxList.py
@@ -0,0 +1,59 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbbench import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TestBenchmarkLibcxxList(BenchBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @benchmarks_test
+ def test_run_command(self):
+ """Benchmark the std::list data formatter (libc++)"""
+ self.build()
+ self.data_formatter_commands()
+
+ def setUp(self):
+ # Call super's setUp().
+ BenchBase.setUp(self)
+
+ def data_formatter_commands(self):
+ """Benchmark the std::list data formatter (libc++)"""
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ bkpt = self.target().FindBreakpointByID(lldbutil.run_break_set_by_source_regexp (self, "break here"))
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ sw = Stopwatch()
+
+ sw.start()
+ self.expect('frame variable -A list', substrs=['[300]', '300'])
+ sw.stop()
+
+ print("time to print: %s" % (sw))
diff --git a/packages/Python/lldbsuite/test/benchmarks/libcxxlist/main.cpp b/packages/Python/lldbsuite/test/benchmarks/libcxxlist/main.cpp
new file mode 100644
index 000000000000..9c4113ad0514
--- /dev/null
+++ b/packages/Python/lldbsuite/test/benchmarks/libcxxlist/main.cpp
@@ -0,0 +1,11 @@
+#include <list>
+
+int main()
+{
+ std::list<int> list;
+ for (int i = 0;
+ i < 1500;
+ i++)
+ list.push_back(i);
+ return list.size(); // break here
+}
diff --git a/packages/Python/lldbsuite/test/benchmarks/libcxxmap/Makefile b/packages/Python/lldbsuite/test/benchmarks/libcxxmap/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/benchmarks/libcxxmap/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/benchmarks/libcxxmap/TestBenchmarkLibcxxMap.py b/packages/Python/lldbsuite/test/benchmarks/libcxxmap/TestBenchmarkLibcxxMap.py
new file mode 100644
index 000000000000..806bc0ee29e2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/benchmarks/libcxxmap/TestBenchmarkLibcxxMap.py
@@ -0,0 +1,59 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbbench import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TestBenchmarkLibcxxMap(BenchBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @benchmarks_test
+ def test_run_command(self):
+ """Benchmark the std::map data formatter (libc++)"""
+ self.build()
+ self.data_formatter_commands()
+
+ def setUp(self):
+ # Call super's setUp().
+ BenchBase.setUp(self)
+
+ def data_formatter_commands(self):
+ """Benchmark the std::map data formatter (libc++)"""
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ bkpt = self.target().FindBreakpointByID(lldbutil.run_break_set_by_source_regexp (self, "break here"))
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ sw = Stopwatch()
+
+ sw.start()
+ self.expect('frame variable -A map', substrs=['[300]', '300'])
+ sw.stop()
+
+ print("time to print: %s" % (sw))
diff --git a/packages/Python/lldbsuite/test/benchmarks/libcxxmap/main.cpp b/packages/Python/lldbsuite/test/benchmarks/libcxxmap/main.cpp
new file mode 100644
index 000000000000..45efb26b6b04
--- /dev/null
+++ b/packages/Python/lldbsuite/test/benchmarks/libcxxmap/main.cpp
@@ -0,0 +1,11 @@
+#include <map>
+
+int main()
+{
+ std::map<int, int> map;
+ for (int i = 0;
+ i < 1500;
+ i++)
+ map[i] = i;
+ return map.size(); // break here
+}
diff --git a/packages/Python/lldbsuite/test/benchmarks/startup/TestStartupDelays.py b/packages/Python/lldbsuite/test/benchmarks/startup/TestStartupDelays.py
new file mode 100644
index 000000000000..a215721ed52f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/benchmarks/startup/TestStartupDelays.py
@@ -0,0 +1,80 @@
+"""Test lldb's startup delays creating a target, setting a breakpoint, and run to breakpoint stop."""
+
+from __future__ import print_function
+
+
+
+import os, sys
+import lldb
+from lldbsuite.test import configuration
+from lldbsuite.test import lldbtest_config
+from lldbsuite.test.lldbbench import *
+
+class StartupDelaysBench(BenchBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ BenchBase.setUp(self)
+ # Create self.stopwatch2 for measuring "set first breakpoint".
+ # The default self.stopwatch is for "create fresh target".
+ self.stopwatch2 = Stopwatch()
+ # Create self.stopwatch3 for measuring "run to breakpoint".
+ self.stopwatch3 = Stopwatch()
+ self.exe = lldbtest_config.lldbExec
+ self.break_spec = '-n main'
+ self.count = 30
+
+ @benchmarks_test
+ @no_debug_info_test
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ def test_startup_delay(self):
+ """Test start up delays creating a target, setting a breakpoint, and run to breakpoint stop."""
+ print()
+ self.run_startup_delays_bench(self.exe, self.break_spec, self.count)
+ print("lldb startup delay (create fresh target) benchmark:", self.stopwatch)
+ print("lldb startup delay (set first breakpoint) benchmark:", self.stopwatch2)
+ print("lldb startup delay (run to breakpoint) benchmark:", self.stopwatch3)
+
+ def run_startup_delays_bench(self, exe, break_spec, count):
+ import pexpect
+ # Set self.child_prompt, which is "(lldb) ".
+ self.child_prompt = '(lldb) '
+ prompt = self.child_prompt
+
+ # Reset the stopwatchs now.
+ self.stopwatch.reset()
+ self.stopwatch2.reset()
+ for i in range(count):
+ # So that the child gets torn down after the test.
+ self.child = pexpect.spawn('%s %s' % (lldbtest_config.lldbExec, self.lldbOption))
+ child = self.child
+
+ # Turn on logging for what the child sends back.
+ if self.TraceOn():
+ child.logfile_read = sys.stdout
+
+ with self.stopwatch:
+ # Create a fresh target.
+ child.sendline('file %s' % exe) # Aka 'target create'.
+ child.expect_exact(prompt)
+
+ with self.stopwatch2:
+ # Read debug info and set the first breakpoint.
+ child.sendline('breakpoint set %s' % break_spec)
+ child.expect_exact(prompt)
+
+ with self.stopwatch3:
+ # Run to the breakpoint just set.
+ child.sendline('run')
+ child.expect_exact(prompt)
+
+ child.sendline('quit')
+ try:
+ self.child.expect(pexpect.EOF)
+ except:
+ pass
+
+ # The test is about to end and if we come to here, the child process has
+ # been terminated. Mark it so.
+ self.child = None
diff --git a/packages/Python/lldbsuite/test/benchmarks/stepping/TestSteppingSpeed.py b/packages/Python/lldbsuite/test/benchmarks/stepping/TestSteppingSpeed.py
new file mode 100644
index 000000000000..14738a978e86
--- /dev/null
+++ b/packages/Python/lldbsuite/test/benchmarks/stepping/TestSteppingSpeed.py
@@ -0,0 +1,67 @@
+"""Test lldb's stepping speed."""
+
+from __future__ import print_function
+
+import os, sys
+import lldb
+from lldbsuite.test import configuration
+from lldbsuite.test import lldbtest_config
+from lldbsuite.test.lldbbench import *
+
+class SteppingSpeedBench(BenchBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ BenchBase.setUp(self)
+ self.exe = lldbtest_config.lldbExec
+ self.break_spec = '-n main'
+ self.count = 50
+
+ #print("self.exe=%s" % self.exe)
+ #print("self.break_spec=%s" % self.break_spec)
+
+ @benchmarks_test
+ @no_debug_info_test
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ def test_run_lldb_steppings(self):
+ """Test lldb steppings on a large executable."""
+ print()
+ self.run_lldb_steppings(self.exe, self.break_spec, self.count)
+ print("lldb stepping benchmark:", self.stopwatch)
+
+ def run_lldb_steppings(self, exe, break_spec, count):
+ import pexpect
+ # Set self.child_prompt, which is "(lldb) ".
+ self.child_prompt = '(lldb) '
+ prompt = self.child_prompt
+
+ # So that the child gets torn down after the test.
+ self.child = pexpect.spawn('%s %s %s' % (lldbtest_config.lldbExec, self.lldbOption, exe))
+ child = self.child
+
+ # Turn on logging for what the child sends back.
+ if self.TraceOn():
+ child.logfile_read = sys.stdout
+
+ child.expect_exact(prompt)
+ child.sendline('breakpoint set %s' % break_spec)
+ child.expect_exact(prompt)
+ child.sendline('run')
+ child.expect_exact(prompt)
+
+ # Reset the stopwatch now.
+ self.stopwatch.reset()
+ for i in range(count):
+ with self.stopwatch:
+ # Disassemble the function.
+ child.sendline('next') # Aka 'thread step-over'.
+ child.expect_exact(prompt)
+
+ child.sendline('quit')
+ try:
+ self.child.expect(pexpect.EOF)
+ except:
+ pass
+
+ self.child = None
diff --git a/packages/Python/lldbsuite/test/benchmarks/turnaround/TestCompileRunToBreakpointTurnaround.py b/packages/Python/lldbsuite/test/benchmarks/turnaround/TestCompileRunToBreakpointTurnaround.py
new file mode 100644
index 000000000000..731eb13bbcfb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/benchmarks/turnaround/TestCompileRunToBreakpointTurnaround.py
@@ -0,0 +1,119 @@
+"""Benchmark the turnaround time starting a debugger and run to the breakpont with lldb vs. gdb."""
+
+from __future__ import print_function
+
+
+
+import os, sys
+import lldb
+from lldbsuite.test import configuration
+from lldbsuite.test.lldbbench import *
+
+class CompileRunToBreakpointBench(BenchBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ BenchBase.setUp(self)
+ self.exe = lldbtest_config.lldbExec
+ self.function = 'Driver::MainLoop()'
+ self.count = 3
+
+ self.lldb_avg = None
+ self.gdb_avg = None
+
+ @benchmarks_test
+ @no_debug_info_test
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ def test_run_lldb_then_gdb(self):
+ """Benchmark turnaround time with lldb vs. gdb."""
+ print()
+ self.run_lldb_turnaround(self.exe, self.function, self.count)
+ print("lldb turnaround benchmark:", self.stopwatch)
+ self.run_gdb_turnaround(self.exe, self.function, self.count)
+ print("gdb turnaround benchmark:", self.stopwatch)
+ print("lldb_avg/gdb_avg: %f" % (self.lldb_avg/self.gdb_avg))
+
+ def run_lldb_turnaround(self, exe, function, count):
+ import pexpect
+ def run_one_round():
+ prompt = self.child_prompt
+
+ # So that the child gets torn down after the test.
+ self.child = pexpect.spawn('%s %s %s' % (lldbtest_config.lldbExec, self.lldbOption, exe))
+ child = self.child
+
+ # Turn on logging for what the child sends back.
+ if self.TraceOn():
+ child.logfile_read = sys.stdout
+
+ child.expect_exact(prompt)
+ child.sendline('breakpoint set -F %s' % function)
+ child.expect_exact(prompt)
+ child.sendline('run')
+ child.expect_exact(prompt)
+
+ # Set self.child_prompt, which is "(lldb) ".
+ self.child_prompt = '(lldb) '
+ # Reset the stopwatch now.
+ self.stopwatch.reset()
+
+ for i in range(count + 1):
+ # Ignore the first invoke lldb and run to the breakpoint turnaround time.
+ if i == 0:
+ run_one_round()
+ else:
+ with self.stopwatch:
+ run_one_round()
+
+ self.child.sendline('quit')
+ try:
+ self.child.expect(pexpect.EOF)
+ except:
+ pass
+
+ self.lldb_avg = self.stopwatch.avg()
+ self.child = None
+
+ def run_gdb_turnaround(self, exe, function, count):
+ import pexpect
+ def run_one_round():
+ prompt = self.child_prompt
+
+ # So that the child gets torn down after the test.
+ self.child = pexpect.spawn('gdb --nx %s' % exe)
+ child = self.child
+
+ # Turn on logging for what the child sends back.
+ if self.TraceOn():
+ child.logfile_read = sys.stdout
+
+ child.expect_exact(prompt)
+ child.sendline('break %s' % function)
+ child.expect_exact(prompt)
+ child.sendline('run')
+ child.expect_exact(prompt)
+
+ # Set self.child_prompt, which is "(gdb) ".
+ self.child_prompt = '(gdb) '
+ # Reset the stopwatch now.
+ self.stopwatch.reset()
+
+ for i in range(count+1):
+ # Ignore the first invoke lldb and run to the breakpoint turnaround time.
+ if i == 0:
+ run_one_round()
+ else:
+ with self.stopwatch:
+ run_one_round()
+
+ self.child.sendline('quit')
+ self.child.expect_exact('The program is running. Exit anyway?')
+ self.child.sendline('y')
+ try:
+ self.child.expect(pexpect.EOF)
+ except:
+ pass
+
+ self.gdb_avg = self.stopwatch.avg()
+ self.child = None
diff --git a/packages/Python/lldbsuite/test/configuration.py b/packages/Python/lldbsuite/test/configuration.py
new file mode 100644
index 000000000000..69ed9fc32e2b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/configuration.py
@@ -0,0 +1,161 @@
+"""
+ The LLVM Compiler Infrastructure
+
+This file is distributed under the University of Illinois Open Source
+License. See LICENSE.TXT for details.
+
+Provides the configuration class, which holds all information related to
+how this invocation of the test suite should be run.
+"""
+
+from __future__ import absolute_import
+from __future__ import print_function
+
+# System modules
+import os
+import platform
+import subprocess
+
+
+# Third-party modules
+import unittest2
+
+# LLDB Modules
+import lldbsuite
+
+def __setCrashInfoHook_Mac(text):
+ from . import crashinfo
+ crashinfo.setCrashReporterDescription(text)
+
+def setupCrashInfoHook():
+ if platform.system() == "Darwin":
+ from . import lock
+ test_dir = os.environ['LLDB_TEST']
+ if not test_dir or not os.path.exists(test_dir):
+ return
+ dylib_lock = os.path.join(test_dir,"crashinfo.lock")
+ dylib_src = os.path.join(test_dir,"crashinfo.c")
+ dylib_dst = os.path.join(test_dir,"crashinfo.so")
+ try:
+ compile_lock = lock.Lock(dylib_lock)
+ compile_lock.acquire()
+ if not os.path.isfile(dylib_dst) or os.path.getmtime(dylib_dst) < os.path.getmtime(dylib_src):
+ # we need to compile
+ cmd = "SDKROOT= xcrun clang %s -o %s -framework Python -Xlinker -dylib -iframework /System/Library/Frameworks/ -Xlinker -F /System/Library/Frameworks/" % (dylib_src,dylib_dst)
+ if subprocess.call(cmd,shell=True) != 0 or not os.path.isfile(dylib_dst):
+ raise Exception('command failed: "{}"'.format(cmd))
+ finally:
+ compile_lock.release()
+ del compile_lock
+
+ setCrashInfoHook = __setCrashInfoHook_Mac
+
+ else:
+ pass
+
+# The test suite.
+suite = unittest2.TestSuite()
+
+# The list of categories we said we care about
+categoriesList = None
+# set to true if we are going to use categories for cherry-picking test cases
+useCategories = False
+# Categories we want to skip
+skipCategories = []
+# use this to track per-category failures
+failuresPerCategory = {}
+
+# The path to LLDB.framework is optional.
+lldbFrameworkPath = None
+
+# Test suite repeat count. Can be overwritten with '-# count'.
+count = 1
+
+# The 'archs' and 'compilers' can be specified via command line. The corresponding
+# options can be specified more than once. For example, "-A x86_64 -A i386"
+# => archs=['x86_64', 'i386'] and "-C gcc -C clang" => compilers=['gcc', 'clang'].
+archs = None # Must be initialized after option parsing
+compilers = None # Must be initialized after option parsing
+
+# The arch might dictate some specific CFLAGS to be passed to the toolchain to build
+# the inferior programs. The global variable cflags_extras provides a hook to do
+# just that.
+cflags_extras = ''
+
+# The filters (testclass.testmethod) used to admit tests into our test suite.
+filters = []
+
+# By default, we skip long running test case. Use '-l' option to override.
+skip_long_running_test = True
+
+# Parsable mode silences headers, and any other output this script might generate, and instead
+# prints machine-readable output similar to what clang tests produce.
+parsable = False
+
+# The regular expression pattern to match against eligible filenames as our test cases.
+regexp = None
+
+# By default, recorded session info for errored/failed test are dumped into its
+# own file under a session directory named after the timestamp of the test suite
+# run. Use '-s session-dir-name' to specify a specific dir name.
+sdir_name = None
+
+# Set this flag if there is any session info dumped during the test run.
+sdir_has_content = False
+
+# svn_info stores the output from 'svn info lldb.base.dir'.
+svn_info = ''
+
+# Default verbosity is 0.
+verbose = 0
+
+# By default, search from the script directory.
+# We can't use sys.path[0] to determine the script directory
+# because it doesn't work under a debugger
+testdirs = [ os.path.dirname(os.path.realpath(__file__)) ]
+
+# Separator string.
+separator = '-' * 70
+
+failed = False
+
+# LLDB Remote platform setting
+lldb_platform_name = None
+lldb_platform_url = None
+lldb_platform_working_dir = None
+
+# Parallel execution settings
+is_inferior_test_runner = False
+multiprocess_test_subdir = None
+num_threads = None
+no_multiprocess_test_runner = False
+test_runner_name = None
+
+# Test results handling globals
+results_filename = None
+results_port = None
+results_formatter_name = None
+results_formatter_object = None
+results_formatter_options = None
+test_result = None
+
+# Test rerun configuration vars
+rerun_all_issues = False
+rerun_max_file_threhold = 0
+
+# The names of all tests. Used to assert we don't have two tests with the same base name.
+all_tests = set()
+
+# safe default
+setCrashInfoHook = lambda x : None
+
+def shouldSkipBecauseOfCategories(test_categories):
+ if useCategories:
+ if len(test_categories) == 0 or len(categoriesList & set(test_categories)) == 0:
+ return True
+
+ for category in skipCategories:
+ if category in test_categories:
+ return True
+
+ return False
diff --git a/packages/Python/lldbsuite/test/crashinfo.c b/packages/Python/lldbsuite/test/crashinfo.c
new file mode 100644
index 000000000000..19013468bb26
--- /dev/null
+++ b/packages/Python/lldbsuite/test/crashinfo.c
@@ -0,0 +1,64 @@
+/******************************************************************************
+ The LLVM Compiler Infrastructure
+
+ This file is distributed under the University of Illinois Open Source
+ License. See LICENSE.TXT for details.
+ ******************************************************************************
+
+* This C file vends a simple interface to set the Application Specific Info
+* on Mac OS X through Python. To use, compile as a dylib, import crashinfo
+* and call crashinfo.setCrashReporterDescription("hello world")
+* The testCrashReporterDescription() API is simply there to let you test that this
+* is doing what it is intended to do without having to actually cons up a crash
+******************************************************************************/
+
+#include <Python/Python.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+
+void *__crashreporter_info__ = NULL;
+
+asm(".desc ___crashreporter_info__, 0x10");
+
+static PyObject* setCrashReporterDescription(PyObject* self, PyObject* string)
+{
+ if (__crashreporter_info__)
+ {
+ free(__crashreporter_info__);
+ __crashreporter_info__ = NULL;
+ }
+
+ if (string && PyString_Check(string))
+ {
+ Py_ssize_t size = PyString_Size(string);
+ char* data = PyString_AsString(string);
+ if (size > 0 && data)
+ {
+ ++size; // Include the NULL terminateor in allocation and memcpy()
+ __crashreporter_info__ = malloc(size);
+ memcpy(__crashreporter_info__, data, size);
+ return Py_True;
+ }
+ }
+ return Py_False;
+}
+
+static PyObject* testCrashReporterDescription(PyObject*self, PyObject* arg)
+{
+ int* ptr = 0;
+ *ptr = 1;
+ return Py_None;
+}
+
+static PyMethodDef crashinfo_methods[] = {
+ {"setCrashReporterDescription", setCrashReporterDescription, METH_O},
+ {"testCrashReporterDescription", testCrashReporterDescription, METH_O},
+ {NULL, NULL}
+};
+
+void initcrashinfo()
+{
+ (void) Py_InitModule("crashinfo", crashinfo_methods);
+}
+
diff --git a/packages/Python/lldbsuite/test/curses_results.py b/packages/Python/lldbsuite/test/curses_results.py
new file mode 100644
index 000000000000..9d480b946ea2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/curses_results.py
@@ -0,0 +1,224 @@
+#!/usr/bin/env python
+
+"""
+ The LLVM Compiler Infrastructure
+
+ This file is distributed under the University of Illinois Open Source
+ License. See LICENSE.TXT for details.
+
+Configuration options for lldbtest.py set by dotest.py during initialization
+"""
+
+from __future__ import print_function
+from __future__ import absolute_import
+
+# System modules
+import curses
+import datetime
+import math
+import sys
+import time
+
+# Third-party modules
+
+# LLDB modules
+from . import lldbcurses
+from . import result_formatter
+from .result_formatter import EventBuilder
+
+
+class Curses(result_formatter.ResultsFormatter):
+ """Receives live results from tests that are running and reports them to the terminal in a curses GUI"""
+
+ def __init__(self, out_file, options):
+ # Initialize the parent
+ super(Curses, self).__init__(out_file, options)
+ self.using_terminal = True
+ self.have_curses = True
+ self.initialize_event = None
+ self.jobs = [None] * 64
+ self.job_tests = [None] * 64
+ self.results = list()
+ try:
+ self.main_window = lldbcurses.intialize_curses()
+ self.main_window.add_key_action('\t', self.main_window.select_next_first_responder, "Switch between views that can respond to keyboard input")
+ self.main_window.refresh()
+ self.job_panel = None
+ self.results_panel = None
+ self.status_panel = None
+ self.info_panel = None
+ self.hide_status_list = list()
+ self.start_time = time.time()
+ except:
+ self.have_curses = False
+ lldbcurses.terminate_curses()
+ self.using_terminal = False
+ print("Unexpected error:", sys.exc_info()[0])
+ raise
+
+ self.line_dict = dict()
+ # self.events_file = open("/tmp/events.txt", "w")
+ # self.formatters = list()
+ # if tee_results_formatter:
+ # self.formatters.append(tee_results_formatter)
+
+ def status_to_short_str(self, status):
+ if status == EventBuilder.STATUS_SUCCESS:
+ return '.'
+ elif status == EventBuilder.STATUS_FAILURE:
+ return 'F'
+ elif status == EventBuilder.STATUS_UNEXPECTED_SUCCESS:
+ return '?'
+ elif status == EventBuilder.STATUS_EXPECTED_FAILURE:
+ return 'X'
+ elif status == EventBuilder.STATUS_SKIP:
+ return 'S'
+ elif status == EventBuilder.STATUS_ERROR:
+ return 'E'
+ else:
+ return status
+
+ def show_info_panel(self):
+ selected_idx = self.results_panel.get_selected_idx()
+ if selected_idx >= 0 and selected_idx < len(self.results):
+ if self.info_panel is None:
+ info_frame = self.results_panel.get_contained_rect(top_inset=10, left_inset=10, right_inset=10, height=30)
+ self.info_panel = lldbcurses.BoxedPanel(info_frame, "Result Details")
+ # Add a key action for any key that will hide this panel when any key is pressed
+ self.info_panel.add_key_action(-1, self.hide_info_panel, 'Hide the info panel')
+ self.info_panel.top()
+ else:
+ self.info_panel.show()
+
+ self.main_window.push_first_responder(self.info_panel)
+ test_start = self.results[selected_idx][0]
+ test_result = self.results[selected_idx][1]
+ self.info_panel.set_line(0, "File: %s" % (test_start['test_filename']))
+ self.info_panel.set_line(1, "Test: %s.%s" % (test_start['test_class'], test_start['test_name']))
+ self.info_panel.set_line(2, "Time: %s" % (test_result['elapsed_time']))
+ self.info_panel.set_line(3, "Status: %s" % (test_result['status']))
+
+ def hide_info_panel(self):
+ self.main_window.pop_first_responder(self.info_panel)
+ self.info_panel.hide()
+ self.main_window.refresh()
+
+ def toggle_status(self, status):
+ if status:
+ # Toggle showing and hiding results whose status matches "status" in "Results" window
+ if status in self.hide_status_list:
+ self.hide_status_list.remove(status)
+ else:
+ self.hide_status_list.append(status)
+ self.update_results()
+
+ def update_results(self, update=True):
+ '''Called after a category of test have been show/hidden to update the results list with
+ what the user desires to see.'''
+ self.results_panel.clear(update=False)
+ for result in self.results:
+ test_result = result[1]
+ status = test_result['status']
+ if status in self.hide_status_list:
+ continue
+ name = test_result['test_class'] + '.' + test_result['test_name']
+ self.results_panel.append_line('%s (%6.2f sec) %s' % (self.status_to_short_str(status), test_result['elapsed_time'], name))
+ if update:
+ self.main_window.refresh()
+
+ def handle_event(self, test_event):
+ with self.lock:
+ super(Curses, self).handle_event(test_event)
+ # for formatter in self.formatters:
+ # formatter.process_event(test_event)
+ if self.have_curses:
+ worker_index = -1
+ if 'worker_index' in test_event:
+ worker_index = test_event['worker_index']
+ if 'event' in test_event:
+ check_for_one_key = True
+ #print(str(test_event), file=self.events_file)
+ event = test_event['event']
+ if self.status_panel:
+ self.status_panel.update_status('time', str(datetime.timedelta(seconds=math.floor(time.time() - self.start_time))))
+ if event == 'test_start':
+ name = test_event['test_class'] + '.' + test_event['test_name']
+ self.job_tests[worker_index] = test_event
+ if 'pid' in test_event:
+ line = 'pid: %5d ' % (test_event['pid']) + name
+ else:
+ line = name
+ self.job_panel.set_line(worker_index, line)
+ self.main_window.refresh()
+ elif event == 'test_result':
+ status = test_event['status']
+ self.status_panel.increment_status(status)
+ if 'pid' in test_event:
+ line = 'pid: %5d ' % (test_event['pid'])
+ else:
+ line = ''
+ self.job_panel.set_line(worker_index, line)
+ name = test_event['test_class'] + '.' + test_event['test_name']
+ elapsed_time = test_event['event_time'] - self.job_tests[worker_index]['event_time']
+ if not status in self.hide_status_list:
+ self.results_panel.append_line('%s (%6.2f sec) %s' % (self.status_to_short_str(status), elapsed_time, name))
+ self.main_window.refresh()
+ # Append the result pairs
+ test_event['elapsed_time'] = elapsed_time
+ self.results.append([self.job_tests[worker_index], test_event])
+ self.job_tests[worker_index] = ''
+ elif event == 'job_begin':
+ self.jobs[worker_index] = test_event
+ if 'pid' in test_event:
+ line = 'pid: %5d ' % (test_event['pid'])
+ else:
+ line = ''
+ self.job_panel.set_line(worker_index, line)
+ elif event == 'job_end':
+ self.jobs[worker_index] = ''
+ self.job_panel.set_line(worker_index, '')
+ elif event == 'initialize':
+ self.initialize_event = test_event
+ num_jobs = test_event['worker_count']
+ job_frame = self.main_window.get_contained_rect(height=num_jobs+2)
+ results_frame = self.main_window.get_contained_rect(top_inset=num_jobs+2, bottom_inset=1)
+ status_frame = self.main_window.get_contained_rect(height=1, top_inset=self.main_window.get_size().h-1)
+ self.job_panel = lldbcurses.BoxedPanel(frame=job_frame, title="Jobs")
+ self.results_panel = lldbcurses.BoxedPanel(frame=results_frame, title="Results")
+
+ self.results_panel.add_key_action(curses.KEY_UP, self.results_panel.select_prev , "Select the previous list entry")
+ self.results_panel.add_key_action(curses.KEY_DOWN, self.results_panel.select_next , "Select the next list entry")
+ self.results_panel.add_key_action(curses.KEY_HOME, self.results_panel.scroll_begin , "Scroll to the start of the list")
+ self.results_panel.add_key_action(curses.KEY_END, self.results_panel.scroll_end , "Scroll to the end of the list")
+ self.results_panel.add_key_action(curses.KEY_ENTER, self.show_info_panel , "Display info for the selected result item")
+ self.results_panel.add_key_action('.', lambda : self.toggle_status(EventBuilder.STATUS_SUCCESS) , "Toggle showing/hiding tests whose status is 'success'")
+ self.results_panel.add_key_action('e', lambda : self.toggle_status(EventBuilder.STATUS_ERROR) , "Toggle showing/hiding tests whose status is 'error'")
+ self.results_panel.add_key_action('f', lambda : self.toggle_status(EventBuilder.STATUS_FAILURE) , "Toggle showing/hiding tests whose status is 'failure'")
+ self.results_panel.add_key_action('s', lambda : self.toggle_status(EventBuilder.STATUS_SKIP) , "Toggle showing/hiding tests whose status is 'skip'")
+ self.results_panel.add_key_action('x', lambda : self.toggle_status(EventBuilder.STATUS_EXPECTED_FAILURE) , "Toggle showing/hiding tests whose status is 'expected_failure'")
+ self.results_panel.add_key_action('?', lambda : self.toggle_status(EventBuilder.STATUS_UNEXPECTED_SUCCESS), "Toggle showing/hiding tests whose status is 'unexpected_success'")
+ self.status_panel = lldbcurses.StatusPanel(frame=status_frame)
+
+ self.main_window.add_child(self.job_panel)
+ self.main_window.add_child(self.results_panel)
+ self.main_window.add_child(self.status_panel)
+ self.main_window.set_first_responder(self.results_panel)
+
+ self.status_panel.add_status_item(name="time", title="Elapsed", format="%s", width=20, value="0:00:00", update=False)
+ self.status_panel.add_status_item(name=EventBuilder.STATUS_SUCCESS, title="Success", format="%u", width=20, value=0, update=False)
+ self.status_panel.add_status_item(name=EventBuilder.STATUS_FAILURE, title="Failure", format="%u", width=20, value=0, update=False)
+ self.status_panel.add_status_item(name=EventBuilder.STATUS_ERROR, title="Error", format="%u", width=20, value=0, update=False)
+ self.status_panel.add_status_item(name=EventBuilder.STATUS_SKIP, title="Skipped", format="%u", width=20, value=0, update=True)
+ self.status_panel.add_status_item(name=EventBuilder.STATUS_EXPECTED_FAILURE, title="Expected Failure", format="%u", width=30, value=0, update=False)
+ self.status_panel.add_status_item(name=EventBuilder.STATUS_UNEXPECTED_SUCCESS, title="Unexpected Success", format="%u", width=30, value=0, update=False)
+ self.main_window.refresh()
+ elif event == 'terminate':
+ #self.main_window.key_event_loop()
+ lldbcurses.terminate_curses()
+ check_for_one_key = False
+ self.using_terminal = False
+ # Check for 1 keypress with no delay
+
+ # Check for 1 keypress with no delay
+ if check_for_one_key:
+ self.main_window.key_event_loop(0, 1)
diff --git a/packages/Python/lldbsuite/test/dosep.py b/packages/Python/lldbsuite/test/dosep.py
new file mode 100644
index 000000000000..51275d55c178
--- /dev/null
+++ b/packages/Python/lldbsuite/test/dosep.py
@@ -0,0 +1,1680 @@
+"""
+Run the test suite using a separate process for each test file.
+
+Each test will run with a time limit of 10 minutes by default.
+
+Override the default time limit of 10 minutes by setting
+the environment variable LLDB_TEST_TIMEOUT.
+
+E.g., export LLDB_TEST_TIMEOUT=10m
+
+Override the time limit for individual tests by setting
+the environment variable LLDB_[TEST NAME]_TIMEOUT.
+
+E.g., export LLDB_TESTCONCURRENTEVENTS_TIMEOUT=2m
+
+Set to "0" to run without time limit.
+
+E.g., export LLDB_TEST_TIMEOUT=0
+or export LLDB_TESTCONCURRENTEVENTS_TIMEOUT=0
+
+To collect core files for timed out tests,
+do the following before running dosep.py
+
+OSX
+ulimit -c unlimited
+sudo sysctl -w kern.corefile=core.%P
+
+Linux:
+ulimit -c unlimited
+echo core.%p | sudo tee /proc/sys/kernel/core_pattern
+"""
+
+from __future__ import print_function
+from __future__ import absolute_import
+
+# system packages and modules
+import asyncore
+import distutils.version
+import fnmatch
+import multiprocessing
+import multiprocessing.pool
+import os
+import platform
+import re
+import signal
+import sys
+import threading
+
+from six.moves import queue
+
+# Our packages and modules
+import lldbsuite
+import lldbsuite.support.seven as seven
+
+from . import configuration
+from . import dotest_channels
+from . import dotest_args
+from . import result_formatter
+
+from .result_formatter import EventBuilder
+
+
+# Todo: Convert this folder layout to be relative-import friendly and
+# don't hack up sys.path like this
+sys.path.append(os.path.join(os.path.dirname(__file__), "test_runner", "lib"))
+import lldb_utils
+import process_control
+
+# Status codes for running command with timeout.
+eTimedOut, ePassed, eFailed = 124, 0, 1
+
+output_lock = None
+test_counter = None
+total_tests = None
+test_name_len = None
+dotest_options = None
+RESULTS_FORMATTER = None
+RUNNER_PROCESS_ASYNC_MAP = None
+RESULTS_LISTENER_CHANNEL = None
+
+"""Contains an optional function pointer that can return the worker index
+ for the given thread/process calling it. Returns a 0-based index."""
+GET_WORKER_INDEX = None
+
+
+def setup_global_variables(
+ lock, counter, total, name_len, options, worker_index_map):
+ global output_lock, test_counter, total_tests, test_name_len
+ global dotest_options
+ output_lock = lock
+ test_counter = counter
+ total_tests = total
+ test_name_len = name_len
+ dotest_options = options
+
+ if worker_index_map is not None:
+ # We'll use the output lock for this to avoid sharing another lock.
+ # This won't be used much.
+ index_lock = lock
+
+ def get_worker_index_use_pid():
+ """Returns a 0-based, process-unique index for the worker."""
+ pid = os.getpid()
+ with index_lock:
+ if pid not in worker_index_map:
+ worker_index_map[pid] = len(worker_index_map)
+ return worker_index_map[pid]
+
+ global GET_WORKER_INDEX
+ GET_WORKER_INDEX = get_worker_index_use_pid
+
+def report_test_failure(name, command, output):
+ global output_lock
+ with output_lock:
+ if not (RESULTS_FORMATTER and RESULTS_FORMATTER.is_using_terminal()):
+ print(file=sys.stderr)
+ print(output, file=sys.stderr)
+ print("[%s FAILED]" % name, file=sys.stderr)
+ print("Command invoked: %s" % ' '.join(command), file=sys.stderr)
+ update_progress(name)
+
+
+def report_test_pass(name, output):
+ global output_lock
+ with output_lock:
+ update_progress(name)
+
+
+def update_progress(test_name=""):
+ global output_lock, test_counter, total_tests, test_name_len
+ with output_lock:
+ counter_len = len(str(total_tests))
+ if not (RESULTS_FORMATTER and RESULTS_FORMATTER.is_using_terminal()):
+ sys.stderr.write(
+ "\r%*d out of %d test suites processed - %-*s" %
+ (counter_len, test_counter.value, total_tests,
+ test_name_len.value, test_name))
+ if len(test_name) > test_name_len.value:
+ test_name_len.value = len(test_name)
+ test_counter.value += 1
+ sys.stdout.flush()
+ sys.stderr.flush()
+
+
+def parse_test_results(output):
+ passes = 0
+ failures = 0
+ unexpected_successes = 0
+ for result in output:
+ pass_count = re.search("^RESULT:.*([0-9]+) passes",
+ result, re.MULTILINE)
+ fail_count = re.search("^RESULT:.*([0-9]+) failures",
+ result, re.MULTILINE)
+ error_count = re.search("^RESULT:.*([0-9]+) errors",
+ result, re.MULTILINE)
+ unexpected_success_count = re.search("^RESULT:.*([0-9]+) unexpected successes",
+ result, re.MULTILINE)
+ if pass_count is not None:
+ passes = passes + int(pass_count.group(1))
+ if fail_count is not None:
+ failures = failures + int(fail_count.group(1))
+ if unexpected_success_count is not None:
+ unexpected_successes = unexpected_successes + int(unexpected_success_count.group(1))
+ if error_count is not None:
+ failures = failures + int(error_count.group(1))
+ return passes, failures, unexpected_successes
+
+
+class DoTestProcessDriver(process_control.ProcessDriver):
+ """Drives the dotest.py inferior process and handles bookkeeping."""
+ def __init__(self, output_file, output_file_lock, pid_events, file_name,
+ soft_terminate_timeout):
+ super(DoTestProcessDriver, self).__init__(
+ soft_terminate_timeout=soft_terminate_timeout)
+ self.output_file = output_file
+ self.output_lock = lldb_utils.OptionalWith(output_file_lock)
+ self.pid_events = pid_events
+ self.results = None
+ self.file_name = file_name
+
+ def write(self, content):
+ with self.output_lock:
+ self.output_file.write(content)
+
+ def on_process_started(self):
+ if self.pid_events:
+ self.pid_events.put_nowait(('created', self.process.pid))
+
+ def on_process_exited(self, command, output, was_timeout, exit_status):
+ if self.pid_events:
+ # No point in culling out those with no exit_status (i.e.
+ # those we failed to kill). That would just cause
+ # downstream code to try to kill it later on a Ctrl-C. At
+ # this point, a best-effort-to-kill already took place. So
+ # call it destroyed here.
+ self.pid_events.put_nowait(('destroyed', self.process.pid))
+
+ # Override the exit status if it was a timeout.
+ if was_timeout:
+ exit_status = eTimedOut
+
+ # If we didn't end up with any output, call it empty for
+ # stdout/stderr.
+ if output is None:
+ output = ('', '')
+
+ # Now parse the output.
+ passes, failures, unexpected_successes = parse_test_results(output)
+ if exit_status == 0:
+ # stdout does not have any useful information from 'dotest.py',
+ # only stderr does.
+ report_test_pass(self.file_name, output[1])
+ else:
+ report_test_failure(self.file_name, command, output[1])
+
+ # Save off the results for the caller.
+ self.results = (
+ self.file_name,
+ exit_status,
+ passes,
+ failures,
+ unexpected_successes)
+
+ def is_exceptional_exit(self):
+ """Returns whether the process returned a timeout.
+
+ Not valid to call until after on_process_exited() completes.
+
+ @return True if the exit is an exceptional exit (e.g. signal on
+ POSIX); False otherwise.
+ """
+ if self.results is None:
+ raise Exception(
+ "exit status checked before results are available")
+ return self.process_helper.is_exceptional_exit(
+ self.results[1])
+
+ def exceptional_exit_details(self):
+ if self.results is None:
+ raise Exception(
+ "exit status checked before results are available")
+ return self.process_helper.exceptional_exit_details(self.results[1])
+
+ def is_timeout(self):
+ if self.results is None:
+ raise Exception(
+ "exit status checked before results are available")
+ return self.results[1] == eTimedOut
+
+
+def get_soft_terminate_timeout():
+ # Defaults to 10 seconds, but can set
+ # LLDB_TEST_SOFT_TERMINATE_TIMEOUT to a floating point
+ # number in seconds. This value indicates how long
+ # the test runner will wait for the dotest inferior to
+ # handle a timeout via a soft terminate before it will
+ # assume that failed and do a hard terminate.
+
+ # TODO plumb through command-line option
+ return float(os.environ.get('LLDB_TEST_SOFT_TERMINATE_TIMEOUT', 10.0))
+
+
+def want_core_on_soft_terminate():
+ # TODO plumb through command-line option
+ if platform.system() == 'Linux':
+ return True
+ else:
+ return False
+
+
+def send_events_to_collector(events, command):
+ """Sends the given events to the collector described in the command line.
+
+ @param events the list of events to send to the test event collector.
+ @param command the inferior command line which contains the details on
+ how to connect to the test event collector.
+ """
+ if events is None or len(events) == 0:
+ # Nothing to do.
+ return
+
+ # Find the port we need to connect to from the --results-port option.
+ try:
+ arg_index = command.index("--results-port") + 1
+ except ValueError:
+ # There is no results port, so no way to communicate back to
+ # the event collector. This is not a problem if we're not
+ # using event aggregation.
+ # TODO flag as error once we always use the event system
+ print(
+ "INFO: no event collector, skipping post-inferior test "
+ "event reporting")
+ return
+
+ if arg_index >= len(command):
+ raise Exception(
+ "expected collector port at index {} in {}".format(
+ arg_index, command))
+ event_port = int(command[arg_index])
+
+ # Create results formatter connected back to collector via socket.
+ config = result_formatter.FormatterConfig()
+ config.port = event_port
+ formatter_spec = result_formatter.create_results_formatter(config)
+ if formatter_spec is None or formatter_spec.formatter is None:
+ raise Exception(
+ "Failed to create socket-based ResultsFormatter "
+ "back to test event collector")
+
+ # Send the events: the port-based event just pickles the content
+ # and sends over to the server side of the socket.
+ for event in events:
+ formatter_spec.formatter.handle_event(event)
+
+ # Cleanup
+ if formatter_spec.cleanup_func is not None:
+ formatter_spec.cleanup_func()
+
+
+def send_inferior_post_run_events(
+ command, worker_index, process_driver, test_filename):
+ """Sends any test events that should be generated after the inferior runs.
+
+ These events would include timeouts and exceptional (i.e. signal-returning)
+ process completion results.
+
+ @param command the list of command parameters passed to subprocess.Popen().
+ @param worker_index the worker index (possibly None) used to run
+ this process
+ @param process_driver the ProcessDriver-derived instance that was used
+ to run the inferior process.
+ @param test_filename the full path to the Python test file that is being
+ run.
+ """
+ if process_driver is None:
+ raise Exception("process_driver must not be None")
+ if process_driver.results is None:
+ # Invalid condition - the results should have been set one way or
+ # another, even in a timeout.
+ raise Exception("process_driver.results were not set")
+
+ # The code below fills in the post events struct. If there are any post
+ # events to fire up, we'll try to make a connection to the socket and
+ # provide the results.
+ post_events = []
+
+ # Handle signal/exceptional exits.
+ if process_driver.is_exceptional_exit():
+ (code, desc) = process_driver.exceptional_exit_details()
+ post_events.append(
+ EventBuilder.event_for_job_exceptional_exit(
+ process_driver.pid,
+ worker_index,
+ code,
+ desc,
+ test_filename,
+ command))
+
+ # Handle timeouts.
+ if process_driver.is_timeout():
+ post_events.append(EventBuilder.event_for_job_timeout(
+ process_driver.pid,
+ worker_index,
+ test_filename,
+ command))
+
+ if len(post_events) > 0:
+ send_events_to_collector(post_events, command)
+
+
+def call_with_timeout(
+ command, timeout, name, inferior_pid_events, test_filename):
+ # Add our worker index (if we have one) to all test events
+ # from this inferior.
+ worker_index = None
+ if GET_WORKER_INDEX is not None:
+ try:
+ worker_index = GET_WORKER_INDEX()
+ command.extend([
+ "--event-add-entries",
+ "worker_index={}:int".format(worker_index)])
+ except: # pylint: disable=bare-except
+ # Ctrl-C does bad things to multiprocessing.Manager.dict()
+ # lookup. Just swallow it.
+ pass
+
+ # Create the inferior dotest.py ProcessDriver.
+ soft_terminate_timeout = get_soft_terminate_timeout()
+ want_core = want_core_on_soft_terminate()
+
+ process_driver = DoTestProcessDriver(
+ sys.stdout,
+ output_lock,
+ inferior_pid_events,
+ name,
+ soft_terminate_timeout)
+
+ # Run it with a timeout.
+ process_driver.run_command_with_timeout(command, timeout, want_core)
+
+ # Return the results.
+ if not process_driver.results:
+ # This is truly exceptional. Even a failing or timed out
+ # binary should have called the results-generation code.
+ raise Exception("no test results were generated whatsoever")
+
+ # Handle cases where the test inferior cannot adequately provide
+ # meaningful results to the test event system.
+ send_inferior_post_run_events(
+ command,
+ worker_index,
+ process_driver,
+ test_filename)
+
+ return process_driver.results
+
+
+def process_dir(root, files, dotest_argv, inferior_pid_events):
+ """Examine a directory for tests, and invoke any found within it."""
+ results = []
+ for (base_name, full_test_path) in files:
+ import __main__ as main
+ script_file = main.__file__
+ command = ([sys.executable, script_file] +
+ dotest_argv +
+ ["--inferior", "-p", base_name, root])
+
+ timeout_name = os.path.basename(os.path.splitext(base_name)[0]).upper()
+
+ timeout = (os.getenv("LLDB_%s_TIMEOUT" % timeout_name) or
+ getDefaultTimeout(dotest_options.lldb_platform_name))
+
+ results.append(call_with_timeout(
+ command, timeout, base_name, inferior_pid_events, full_test_path))
+
+ # result = (name, status, passes, failures, unexpected_successes)
+ timed_out = [name for name, status, _, _, _ in results
+ if status == eTimedOut]
+ passed = [name for name, status, _, _, _ in results
+ if status == ePassed]
+ failed = [name for name, status, _, _, _ in results
+ if status != ePassed]
+ unexpected_passes = [
+ name for name, _, _, _, unexpected_successes in results
+ if unexpected_successes > 0]
+
+ pass_count = sum([result[2] for result in results])
+ fail_count = sum([result[3] for result in results])
+
+ return (
+ timed_out, passed, failed, unexpected_passes, pass_count, fail_count)
+
+in_q = None
+out_q = None
+
+
+def process_dir_worker_multiprocessing(
+ a_output_lock, a_test_counter, a_total_tests, a_test_name_len,
+ a_dotest_options, job_queue, result_queue, inferior_pid_events,
+ worker_index_map):
+ """Worker thread main loop when in multiprocessing mode.
+ Takes one directory specification at a time and works on it."""
+
+ # Shut off interrupt handling in the child process.
+ signal.signal(signal.SIGINT, signal.SIG_IGN)
+ if hasattr(signal, 'SIGHUP'):
+ signal.signal(signal.SIGHUP, signal.SIG_IGN)
+
+ # Setup the global state for the worker process.
+ setup_global_variables(
+ a_output_lock, a_test_counter, a_total_tests, a_test_name_len,
+ a_dotest_options, worker_index_map)
+
+ # Keep grabbing entries from the queue until done.
+ while not job_queue.empty():
+ try:
+ job = job_queue.get(block=False)
+ result = process_dir(job[0], job[1], job[2],
+ inferior_pid_events)
+ result_queue.put(result)
+ except queue.Empty:
+ # Fine, we're done.
+ pass
+
+
+def process_dir_worker_multiprocessing_pool(args):
+ return process_dir(*args)
+
+
+def process_dir_worker_threading(job_queue, result_queue, inferior_pid_events):
+ """Worker thread main loop when in threading mode.
+
+ This one supports the hand-rolled pooling support.
+
+ Takes one directory specification at a time and works on it."""
+
+ # Keep grabbing entries from the queue until done.
+ while not job_queue.empty():
+ try:
+ job = job_queue.get(block=False)
+ result = process_dir(job[0], job[1], job[2],
+ inferior_pid_events)
+ result_queue.put(result)
+ except queue.Empty:
+ # Fine, we're done.
+ pass
+
+
+def process_dir_worker_threading_pool(args):
+ return process_dir(*args)
+
+
+def process_dir_mapper_inprocess(args):
+ """Map adapter for running the subprocess-based, non-threaded test runner.
+
+ @param args the process work item tuple
+ @return the test result tuple
+ """
+ return process_dir(*args)
+
+
+def collect_active_pids_from_pid_events(event_queue):
+ """
+ Returns the set of what should be active inferior pids based on
+ the event stream.
+
+ @param event_queue a multiprocessing.Queue containing events of the
+ form:
+ ('created', pid)
+ ('destroyed', pid)
+
+ @return set of inferior dotest.py pids activated but never completed.
+ """
+ active_pid_set = set()
+ while not event_queue.empty():
+ pid_event = event_queue.get_nowait()
+ if pid_event[0] == 'created':
+ active_pid_set.add(pid_event[1])
+ elif pid_event[0] == 'destroyed':
+ active_pid_set.remove(pid_event[1])
+ return active_pid_set
+
+
+def kill_all_worker_processes(workers, inferior_pid_events):
+ """
+ Kills all specified worker processes and their process tree.
+
+ @param workers a list of multiprocess.Process worker objects.
+ @param inferior_pid_events a multiprocess.Queue that contains
+ all inferior create and destroy events. Used to construct
+ the list of child pids still outstanding that need to be killed.
+ """
+ for worker in workers:
+ worker.terminate()
+ worker.join()
+
+ # Add all the child test pids created.
+ active_pid_set = collect_active_pids_from_pid_events(
+ inferior_pid_events)
+ for inferior_pid in active_pid_set:
+ print("killing inferior pid {}".format(inferior_pid))
+ os.kill(inferior_pid, signal.SIGKILL)
+
+
+def kill_all_worker_threads(workers, inferior_pid_events):
+ """
+ Kills all specified worker threads and their process tree.
+
+ @param workers a list of multiprocess.Process worker objects.
+ @param inferior_pid_events a multiprocess.Queue that contains
+ all inferior create and destroy events. Used to construct
+ the list of child pids still outstanding that need to be killed.
+ """
+
+ # Add all the child test pids created.
+ active_pid_set = collect_active_pids_from_pid_events(
+ inferior_pid_events)
+ for inferior_pid in active_pid_set:
+ print("killing inferior pid {}".format(inferior_pid))
+ os.kill(inferior_pid, signal.SIGKILL)
+
+ # We don't have a way to nuke the threads. However, since we killed
+ # all the inferiors, and we drained the job queue, this will be
+ # good enough. Wait cleanly for each worker thread to wrap up.
+ for worker in workers:
+ worker.join()
+
+
+def find_test_files_in_dir_tree(dir_root, found_func):
+ """Calls found_func for all the test files in the given dir hierarchy.
+
+ @param dir_root the path to the directory to start scanning
+ for test files. All files in this directory and all its children
+ directory trees will be searched.
+
+ @param found_func a callable object that will be passed
+ the parent directory (relative to dir_root) and the list of
+ test files from within that directory.
+ """
+ for root, _, files in os.walk(dir_root, topdown=False):
+ def is_test_filename(test_dir, base_filename):
+ """Returns True if the given filename matches the test name format.
+
+ @param test_dir the directory to check. Should be absolute or
+ relative to current working directory.
+
+ @param base_filename the base name of the filename to check for a
+ dherence to the python test case filename format.
+
+ @return True if name matches the python test case filename format.
+ """
+ # Not interested in symbolically linked files.
+ if os.path.islink(os.path.join(test_dir, base_filename)):
+ return False
+ # Only interested in test files with the "Test*.py" naming pattern.
+ return (base_filename.startswith("Test") and
+ base_filename.endswith(".py"))
+
+ tests = [
+ (filename, os.path.join(root, filename))
+ for filename in files
+ if is_test_filename(root, filename)]
+ if tests:
+ found_func(root, tests)
+
+
+def initialize_global_vars_common(num_threads, test_work_items):
+ global total_tests, test_counter, test_name_len
+
+ total_tests = sum([len(item[1]) for item in test_work_items])
+ test_counter = multiprocessing.Value('i', 0)
+ test_name_len = multiprocessing.Value('i', 0)
+ if not (RESULTS_FORMATTER and RESULTS_FORMATTER.is_using_terminal()):
+ print("Testing: %d test suites, %d thread%s" % (
+ total_tests, num_threads, (num_threads > 1) * "s"), file=sys.stderr)
+ update_progress()
+
+
+def initialize_global_vars_multiprocessing(num_threads, test_work_items):
+ # Initialize the global state we'll use to communicate with the
+ # rest of the flat module.
+ global output_lock
+ output_lock = multiprocessing.RLock()
+
+ initialize_global_vars_common(num_threads, test_work_items)
+
+
+def initialize_global_vars_threading(num_threads, test_work_items):
+ """Initializes global variables used in threading mode.
+ @param num_threads specifies the number of workers used.
+ @param test_work_items specifies all the work items
+ that will be processed.
+ """
+ # Initialize the global state we'll use to communicate with the
+ # rest of the flat module.
+ global output_lock
+ output_lock = threading.RLock()
+
+ index_lock = threading.RLock()
+ index_map = {}
+
+ def get_worker_index_threading():
+ """Returns a 0-based, thread-unique index for the worker thread."""
+ thread_id = threading.current_thread().ident
+ with index_lock:
+ if thread_id not in index_map:
+ index_map[thread_id] = len(index_map)
+ return index_map[thread_id]
+
+
+ global GET_WORKER_INDEX
+ GET_WORKER_INDEX = get_worker_index_threading
+
+ initialize_global_vars_common(num_threads, test_work_items)
+
+
+def ctrl_c_loop(main_op_func, done_func, ctrl_c_handler):
+ """Provides a main loop that is Ctrl-C protected.
+
+ The main loop calls the main_op_func() repeatedly until done_func()
+ returns true. The ctrl_c_handler() method is called with a single
+ int parameter that contains the number of times the ctrl_c has been
+ hit (starting with 1). The ctrl_c_handler() should mutate whatever
+ it needs to have the done_func() return True as soon as it is desired
+ to exit the loop.
+ """
+ done = False
+ ctrl_c_count = 0
+
+ while not done:
+ try:
+ # See if we're done. Start with done check since it is
+ # the first thing executed after a Ctrl-C handler in the
+ # following loop.
+ done = done_func()
+ if not done:
+ # Run the main op once.
+ main_op_func()
+
+ except KeyboardInterrupt:
+ ctrl_c_count += 1
+ ctrl_c_handler(ctrl_c_count)
+
+
+def pump_workers_and_asyncore_map(workers, asyncore_map):
+ """Prunes out completed workers and maintains the asyncore loop.
+
+ The asyncore loop contains the optional socket listener
+ and handlers. When all workers are complete, this method
+ takes care of stopping the listener. It also runs the
+ asyncore loop for the given async map for 10 iterations.
+
+ @param workers the list of worker Thread/Process instances.
+
+ @param asyncore_map the asyncore threading-aware map that
+ indicates which channels are in use and still alive.
+ """
+
+ # Check on all the workers, removing them from the workers
+ # list as they complete.
+ dead_workers = []
+ for worker in workers:
+ # This non-blocking join call is what allows us
+ # to still receive keyboard interrupts.
+ worker.join(0.01)
+ if not worker.is_alive():
+ dead_workers.append(worker)
+ # Clear out the completed workers
+ for dead_worker in dead_workers:
+ workers.remove(dead_worker)
+
+ # If there are no more workers and there is a listener,
+ # close the listener.
+ global RESULTS_LISTENER_CHANNEL
+ if len(workers) == 0 and RESULTS_LISTENER_CHANNEL is not None:
+ RESULTS_LISTENER_CHANNEL.close()
+ RESULTS_LISTENER_CHANNEL = None
+
+ # Pump the asyncore map if it isn't empty.
+ if len(asyncore_map) > 0:
+ asyncore.loop(0.1, False, asyncore_map, 10)
+
+
+def handle_ctrl_c(ctrl_c_count, job_queue, workers, inferior_pid_events,
+ stop_all_inferiors_func):
+ """Performs the appropriate ctrl-c action for non-pool parallel test runners
+
+ @param ctrl_c_count starting with 1, indicates the number of times ctrl-c
+ has been intercepted. The value is 1 on the first intercept, 2 on the
+ second, etc.
+
+ @param job_queue a Queue object that contains the work still outstanding
+ (i.e. hasn't been assigned to a worker yet).
+
+ @param workers list of Thread or Process workers.
+
+ @param inferior_pid_events specifies a Queue of inferior process
+ construction and destruction events. Used to build the list of inferior
+ processes that should be killed if we get that far.
+
+ @param stop_all_inferiors_func a callable object that takes the
+ workers and inferior_pid_events parameters (in that order) if a hard
+ stop is to be used on the workers.
+ """
+
+ # Print out which Ctrl-C we're handling.
+ key_name = [
+ "first",
+ "second",
+ "third",
+ "many"]
+
+ if ctrl_c_count < len(key_name):
+ name_index = ctrl_c_count - 1
+ else:
+ name_index = len(key_name) - 1
+ message = "\nHandling {} KeyboardInterrupt".format(key_name[name_index])
+ with output_lock:
+ print(message)
+
+ if ctrl_c_count == 1:
+ # Remove all outstanding items from the work queue so we stop
+ # doing any more new work.
+ while not job_queue.empty():
+ try:
+ # Just drain it to stop more work from being started.
+ job_queue.get_nowait()
+ except queue.Empty:
+ pass
+ with output_lock:
+ print("Stopped more work from being started.")
+ elif ctrl_c_count == 2:
+ # Try to stop all inferiors, even the ones currently doing work.
+ stop_all_inferiors_func(workers, inferior_pid_events)
+ else:
+ with output_lock:
+ print("All teardown activities kicked off, should finish soon.")
+
+
+def workers_and_async_done(workers, async_map):
+ """Returns True if the workers list and asyncore channels are all done.
+
+ @param workers list of workers (threads/processes). These must adhere
+ to the threading Thread or multiprocessing.Process interface.
+
+ @param async_map the threading-aware asyncore channel map to check
+ for live channels.
+
+ @return False if the workers list exists and has any entries in it, or
+ if the async_map exists and has any entries left in it; otherwise, True.
+ """
+ if workers is not None and len(workers) > 0:
+ # We're not done if we still have workers left.
+ return False
+ if async_map is not None and len(async_map) > 0:
+ return False
+ # We're done.
+ return True
+
+
+def multiprocessing_test_runner(num_threads, test_work_items):
+ """Provides hand-wrapped pooling test runner adapter with Ctrl-C support.
+
+ This concurrent test runner is based on the multiprocessing
+ library, and rolls its own worker pooling strategy so it
+ can handle Ctrl-C properly.
+
+ This test runner is known to have an issue running on
+ Windows platforms.
+
+ @param num_threads the number of worker processes to use.
+
+ @param test_work_items the iterable of test work item tuples
+ to run.
+ """
+
+ # Initialize our global state.
+ initialize_global_vars_multiprocessing(num_threads, test_work_items)
+
+ # Create jobs.
+ job_queue = multiprocessing.Queue(len(test_work_items))
+ for test_work_item in test_work_items:
+ job_queue.put(test_work_item)
+
+ result_queue = multiprocessing.Queue(len(test_work_items))
+
+ # Create queues for started child pids. Terminating
+ # the multiprocess processes does not terminate the
+ # child processes they spawn. We can remove this tracking
+ # if/when we move to having the multiprocess process directly
+ # perform the test logic. The Queue size needs to be able to
+ # hold 2 * (num inferior dotest.py processes started) entries.
+ inferior_pid_events = multiprocessing.Queue(4096)
+
+ # Worker dictionary allows each worker to figure out its worker index.
+ manager = multiprocessing.Manager()
+ worker_index_map = manager.dict()
+
+ # Create workers. We don't use multiprocessing.Pool due to
+ # challenges with handling ^C keyboard interrupts.
+ workers = []
+ for _ in range(num_threads):
+ worker = multiprocessing.Process(
+ target=process_dir_worker_multiprocessing,
+ args=(output_lock,
+ test_counter,
+ total_tests,
+ test_name_len,
+ dotest_options,
+ job_queue,
+ result_queue,
+ inferior_pid_events,
+ worker_index_map))
+ worker.start()
+ workers.append(worker)
+
+ # Main loop: wait for all workers to finish and wait for
+ # the socket handlers to wrap up.
+ ctrl_c_loop(
+ # Main operation of loop
+ lambda: pump_workers_and_asyncore_map(
+ workers, RUNNER_PROCESS_ASYNC_MAP),
+
+ # Return True when we're done with the main loop.
+ lambda: workers_and_async_done(workers, RUNNER_PROCESS_ASYNC_MAP),
+
+ # Indicate what we do when we receive one or more Ctrl-Cs.
+ lambda ctrl_c_count: handle_ctrl_c(
+ ctrl_c_count, job_queue, workers, inferior_pid_events,
+ kill_all_worker_processes))
+
+ # Reap the test results.
+ test_results = []
+ while not result_queue.empty():
+ test_results.append(result_queue.get(block=False))
+ return test_results
+
+
+def map_async_run_loop(future, channel_map, listener_channel):
+ """Blocks until the Pool.map_async completes and the channel completes.
+
+ @param future an AsyncResult instance from a Pool.map_async() call.
+
+ @param channel_map the asyncore dispatch channel map that should be pumped.
+ Optional: may be None.
+
+ @param listener_channel the channel representing a listener that should be
+ closed once the map_async results are available.
+
+ @return the results from the async_result instance.
+ """
+ map_results = None
+
+ done = False
+ while not done:
+ # Check if we need to reap the map results.
+ if map_results is None:
+ if future.ready():
+ # Get the results.
+ map_results = future.get()
+
+ # Close the runner process listener channel if we have
+ # one: no more connections will be incoming.
+ if listener_channel is not None:
+ listener_channel.close()
+
+ # Pump the asyncore loop if we have a listener socket.
+ if channel_map is not None:
+ asyncore.loop(0.01, False, channel_map, 10)
+
+ # Figure out if we're done running.
+ done = map_results is not None
+ if channel_map is not None:
+ # We have a runner process async map. Check if it
+ # is complete.
+ if len(channel_map) > 0:
+ # We still have an asyncore channel running. Not done yet.
+ done = False
+
+ return map_results
+
+
+def multiprocessing_test_runner_pool(num_threads, test_work_items):
+ # Initialize our global state.
+ initialize_global_vars_multiprocessing(num_threads, test_work_items)
+
+ manager = multiprocessing.Manager()
+ worker_index_map = manager.dict()
+
+ pool = multiprocessing.Pool(
+ num_threads,
+ initializer=setup_global_variables,
+ initargs=(output_lock, test_counter, total_tests, test_name_len,
+ dotest_options, worker_index_map))
+
+ # Start the map operation (async mode).
+ map_future = pool.map_async(
+ process_dir_worker_multiprocessing_pool, test_work_items)
+ return map_async_run_loop(
+ map_future, RUNNER_PROCESS_ASYNC_MAP, RESULTS_LISTENER_CHANNEL)
+
+
+def threading_test_runner(num_threads, test_work_items):
+ """Provides hand-wrapped pooling threading-based test runner adapter
+ with Ctrl-C support.
+
+ This concurrent test runner is based on the threading
+ library, and rolls its own worker pooling strategy so it
+ can handle Ctrl-C properly.
+
+ @param num_threads the number of worker processes to use.
+
+ @param test_work_items the iterable of test work item tuples
+ to run.
+ """
+
+ # Initialize our global state.
+ initialize_global_vars_threading(num_threads, test_work_items)
+
+ # Create jobs.
+ job_queue = queue.Queue()
+ for test_work_item in test_work_items:
+ job_queue.put(test_work_item)
+
+ result_queue = queue.Queue()
+
+ # Create queues for started child pids. Terminating
+ # the threading threads does not terminate the
+ # child processes they spawn.
+ inferior_pid_events = queue.Queue()
+
+ # Create workers. We don't use multiprocessing.pool.ThreadedPool
+ # due to challenges with handling ^C keyboard interrupts.
+ workers = []
+ for _ in range(num_threads):
+ worker = threading.Thread(
+ target=process_dir_worker_threading,
+ args=(job_queue,
+ result_queue,
+ inferior_pid_events))
+ worker.start()
+ workers.append(worker)
+
+ # Main loop: wait for all workers to finish and wait for
+ # the socket handlers to wrap up.
+ ctrl_c_loop(
+ # Main operation of loop
+ lambda: pump_workers_and_asyncore_map(
+ workers, RUNNER_PROCESS_ASYNC_MAP),
+
+ # Return True when we're done with the main loop.
+ lambda: workers_and_async_done(workers, RUNNER_PROCESS_ASYNC_MAP),
+
+ # Indicate what we do when we receive one or more Ctrl-Cs.
+ lambda ctrl_c_count: handle_ctrl_c(
+ ctrl_c_count, job_queue, workers, inferior_pid_events,
+ kill_all_worker_threads))
+
+ # Reap the test results.
+ test_results = []
+ while not result_queue.empty():
+ test_results.append(result_queue.get(block=False))
+ return test_results
+
+
+def threading_test_runner_pool(num_threads, test_work_items):
+ # Initialize our global state.
+ initialize_global_vars_threading(num_threads, test_work_items)
+
+ pool = multiprocessing.pool.ThreadPool(num_threads)
+ map_future = pool.map_async(
+ process_dir_worker_threading_pool, test_work_items)
+
+ return map_async_run_loop(
+ map_future, RUNNER_PROCESS_ASYNC_MAP, RESULTS_LISTENER_CHANNEL)
+
+
+def asyncore_run_loop(channel_map):
+ try:
+ asyncore.loop(None, False, channel_map)
+ except:
+ # Swallow it, we're seeing:
+ # error: (9, 'Bad file descriptor')
+ # when the listener channel is closed. Shouldn't be the case.
+ pass
+
+
+def inprocess_exec_test_runner(test_work_items):
+ # Initialize our global state.
+ initialize_global_vars_multiprocessing(1, test_work_items)
+
+ # We're always worker index 0
+ global GET_WORKER_INDEX
+ GET_WORKER_INDEX = lambda: 0
+
+ # Run the listener and related channel maps in a separate thread.
+ # global RUNNER_PROCESS_ASYNC_MAP
+ global RESULTS_LISTENER_CHANNEL
+ if RESULTS_LISTENER_CHANNEL is not None:
+ socket_thread = threading.Thread(
+ target=lambda: asyncore_run_loop(RUNNER_PROCESS_ASYNC_MAP))
+ socket_thread.start()
+
+ # Do the work.
+ test_results = list(map(process_dir_mapper_inprocess, test_work_items))
+
+ # If we have a listener channel, shut it down here.
+ if RESULTS_LISTENER_CHANNEL is not None:
+ # Close down the channel.
+ RESULTS_LISTENER_CHANNEL.close()
+ RESULTS_LISTENER_CHANNEL = None
+
+ # Wait for the listener and handlers to complete.
+ socket_thread.join()
+
+ return test_results
+
+def walk_and_invoke(test_files, dotest_argv, num_workers, test_runner_func):
+ """Invokes the test runner on each test file specified by test_files.
+
+ @param test_files a list of (test_subdir, list_of_test_files_in_dir)
+ @param num_workers the number of worker queues working on these test files
+ @param test_runner_func the test runner configured to run the tests
+
+ @return a tuple of results from the running of the specified tests,
+ of the form (timed_out, passed, failed, unexpected_successes, pass_count,
+ fail_count)
+ """
+ # The async_map is important to keep all thread-related asyncore
+ # channels distinct when we call asyncore.loop() later on.
+ global RESULTS_LISTENER_CHANNEL, RUNNER_PROCESS_ASYNC_MAP
+ RUNNER_PROCESS_ASYNC_MAP = {}
+
+ # If we're outputting side-channel test results, create the socket
+ # listener channel and tell the inferior to send results to the
+ # port on which we'll be listening.
+ if RESULTS_FORMATTER is not None:
+ forwarding_func = RESULTS_FORMATTER.handle_event
+ RESULTS_LISTENER_CHANNEL = (
+ dotest_channels.UnpicklingForwardingListenerChannel(
+ RUNNER_PROCESS_ASYNC_MAP, "localhost", 0,
+ 2 * num_workers, forwarding_func))
+ # Set the results port command line arg. Might have been
+ # inserted previous, so first try to replace.
+ listener_port = str(RESULTS_LISTENER_CHANNEL.address[1])
+ try:
+ port_value_index = dotest_argv.index("--results-port") + 1
+ dotest_argv[port_value_index] = listener_port
+ except ValueError:
+ # --results-port doesn't exist (yet), add it
+ dotest_argv.append("--results-port")
+ dotest_argv.append(listener_port)
+
+ # Build the test work items out of the (dir, file_list) entries passed in.
+ test_work_items = []
+ for entry in test_files:
+ test_work_items.append((entry[0], entry[1], dotest_argv, None))
+
+ # Convert test work items into test results using whatever
+ # was provided as the test run function.
+ test_results = test_runner_func(test_work_items)
+
+ # Summarize the results and return to caller.
+ timed_out = sum([result[0] for result in test_results], [])
+ passed = sum([result[1] for result in test_results], [])
+ failed = sum([result[2] for result in test_results], [])
+ unexpected_successes = sum([result[3] for result in test_results], [])
+ pass_count = sum([result[4] for result in test_results])
+ fail_count = sum([result[5] for result in test_results])
+
+ return (timed_out, passed, failed, unexpected_successes, pass_count,
+ fail_count)
+
+
+def getExpectedTimeouts(platform_name):
+ # returns a set of test filenames that might timeout
+ # are we running against a remote target?
+ host = sys.platform
+ if platform_name is None:
+ target = sys.platform
+ else:
+ m = re.search(r'remote-(\w+)', platform_name)
+ target = m.group(1)
+
+ expected_timeout = set()
+
+ if target.startswith("android"):
+ expected_timeout |= {
+ "TestExitDuringStep.py",
+ "TestHelloWorld.py",
+ }
+ if host.startswith("win32"):
+ expected_timeout |= {
+ "TestEvents.py",
+ "TestThreadStates.py",
+ }
+ elif target.startswith("freebsd"):
+ expected_timeout |= {
+ "TestBreakpointConditions.py",
+ "TestChangeProcessGroup.py",
+ "TestValueObjectRecursion.py",
+ "TestWatchpointConditionAPI.py",
+ }
+ elif target.startswith("darwin"):
+ expected_timeout |= {
+ # times out on MBP Retina, Mid 2012
+ "TestThreadSpecificBreakpoint.py",
+ "TestExitDuringStep.py",
+ "TestIntegerTypesExpr.py",
+ }
+ return expected_timeout
+
+
+def getDefaultTimeout(platform_name):
+ if os.getenv("LLDB_TEST_TIMEOUT"):
+ return os.getenv("LLDB_TEST_TIMEOUT")
+
+ if platform_name is None:
+ platform_name = sys.platform
+
+ if platform_name.startswith("remote-"):
+ return "10m"
+ elif platform_name == 'darwin':
+ # We are consistently needing more time on a few tests.
+ return "6m"
+ else:
+ return "4m"
+
+
+def touch(fname, times=None):
+ if os.path.exists(fname):
+ os.utime(fname, times)
+
+
+def find(pattern, path):
+ result = []
+ for root, dirs, files in os.walk(path):
+ for name in files:
+ if fnmatch.fnmatch(name, pattern):
+ result.append(os.path.join(root, name))
+ return result
+
+
+def get_test_runner_strategies(num_threads):
+ """Returns the test runner strategies by name in a dictionary.
+
+ @param num_threads specifies the number of threads/processes
+ that will be used for concurrent test runners.
+
+ @return dictionary with key as test runner strategy name and
+ value set to a callable object that takes the test work item
+ and returns a test result tuple.
+ """
+ return {
+ # multiprocessing supports ctrl-c and does not use
+ # multiprocessing.Pool.
+ "multiprocessing":
+ (lambda work_items: multiprocessing_test_runner(
+ num_threads, work_items)),
+
+ # multiprocessing-pool uses multiprocessing.Pool but
+ # does not support Ctrl-C.
+ "multiprocessing-pool":
+ (lambda work_items: multiprocessing_test_runner_pool(
+ num_threads, work_items)),
+
+ # threading uses a hand-rolled worker pool much
+ # like multiprocessing, but instead uses in-process
+ # worker threads. This one supports Ctrl-C.
+ "threading":
+ (lambda work_items: threading_test_runner(num_threads, work_items)),
+
+ # threading-pool uses threading for the workers (in-process)
+ # and uses the multiprocessing.pool thread-enabled pool.
+ # This does not properly support Ctrl-C.
+ "threading-pool":
+ (lambda work_items: threading_test_runner_pool(
+ num_threads, work_items)),
+
+ # serial uses the subprocess-based, single process
+ # test runner. This provides process isolation but
+ # no concurrent test execution.
+ "serial":
+ inprocess_exec_test_runner
+ }
+
+
+def _remove_option(
+ args, long_option_name, short_option_name, takes_arg):
+ """Removes option and related option arguments from args array.
+
+ This method removes all short/long options that match the given
+ arguments.
+
+ @param args the array of command line arguments (in/out)
+
+ @param long_option_name the full command line representation of the
+ long-form option that will be removed (including '--').
+
+ @param short_option_name the short version of the command line option
+ that will be removed (including '-').
+
+ @param takes_arg True if the option takes an argument.
+
+ """
+ if long_option_name is not None:
+ regex_string = "^" + long_option_name + "="
+ long_regex = re.compile(regex_string)
+ if short_option_name is not None:
+ # Short options we only match the -X and assume
+ # any arg is one command line argument jammed together.
+ # i.e. -O--abc=1 is a single argument in the args list.
+ # We don't handle -O --abc=1, as argparse doesn't handle
+ # it, either.
+ regex_string = "^" + short_option_name
+ short_regex = re.compile(regex_string)
+
+ def remove_long_internal():
+ """Removes one matching long option from args.
+ @returns True if one was found and removed; False otherwise.
+ """
+ try:
+ index = args.index(long_option_name)
+ # Handle the exact match case.
+ if takes_arg:
+ removal_count = 2
+ else:
+ removal_count = 1
+ del args[index:index+removal_count]
+ return True
+ except ValueError:
+ # Thanks to argparse not handling options with known arguments
+ # like other options parsing libraries (see
+ # https://bugs.python.org/issue9334), we need to support the
+ # --results-formatter-options={second-level-arguments} (note
+ # the equal sign to fool the first-level arguments parser into
+ # not treating the second-level arguments as first-level
+ # options). We're certainly at risk of getting this wrong
+ # since now we're forced into the business of trying to figure
+ # out what is an argument (although I think this
+ # implementation will suffice).
+ for index in range(len(args)):
+ match = long_regex.search(args[index])
+ if match:
+ del args[index]
+ return True
+ return False
+
+ def remove_short_internal():
+ """Removes one matching short option from args.
+ @returns True if one was found and removed; False otherwise.
+ """
+ for index in range(len(args)):
+ match = short_regex.search(args[index])
+ if match:
+ del args[index]
+ return True
+ return False
+
+ removal_count = 0
+ while long_option_name is not None and remove_long_internal():
+ removal_count += 1
+ while short_option_name is not None and remove_short_internal():
+ removal_count += 1
+ if removal_count == 0:
+ raise Exception(
+ "failed to find at least one of '{}', '{}' in options".format(
+ long_option_name, short_option_name))
+
+
+def adjust_inferior_options(dotest_argv):
+ """Adjusts the commandline args array for inferiors.
+
+ This method adjusts the inferior dotest commandline options based
+ on the parallel test runner's options. Some of the inferior options
+ will need to change to properly handle aggregation functionality.
+ """
+ global dotest_options
+
+ # If we don't have a session directory, create one.
+ if not dotest_options.s:
+ # no session log directory, we need to add this to prevent
+ # every dotest invocation from creating its own directory
+ import datetime
+ # The windows platforms don't like ':' in the pathname.
+ timestamp_started = datetime.datetime.now().strftime("%Y-%m-%d-%H_%M_%S")
+ dotest_argv.append('-s')
+ dotest_argv.append(timestamp_started)
+ dotest_options.s = timestamp_started
+
+ # Adjust inferior results formatter options - if the parallel
+ # test runner is collecting into the user-specified test results,
+ # we'll have inferiors spawn with the --results-port option and
+ # strip the original test runner options.
+ if dotest_options.results_file is not None:
+ _remove_option(dotest_argv, "--results-file", None, True)
+ if dotest_options.results_port is not None:
+ _remove_option(dotest_argv, "--results-port", None, True)
+ if dotest_options.results_formatter is not None:
+ _remove_option(dotest_argv, "--results-formatter", None, True)
+ if dotest_options.results_formatter_options is not None:
+ _remove_option(dotest_argv, "--results-formatter-option", "-O",
+ True)
+
+ # Remove the --curses shortcut if specified.
+ if dotest_options.curses:
+ _remove_option(dotest_argv, "--curses", None, False)
+
+ # Remove test runner name if present.
+ if dotest_options.test_runner_name is not None:
+ _remove_option(dotest_argv, "--test-runner-name", None, True)
+
+
+def is_darwin_version_lower_than(target_version):
+ """Checks that os is Darwin and version is lower than target_version.
+
+ @param target_version the StrictVersion indicating the version
+ we're checking against.
+
+ @return True if the OS is Darwin (OS X) and the version number of
+ the OS is less than target_version; False in all other cases.
+ """
+ if platform.system() != 'Darwin':
+ # Can't be Darwin lower than a certain version.
+ return False
+
+ system_version = distutils.version.StrictVersion(platform.mac_ver()[0])
+ return seven.cmp_(system_version, target_version) < 0
+
+
+def default_test_runner_name(num_threads):
+ """Returns the default test runner name for the configuration.
+
+ @param num_threads the number of threads/workers this test runner is
+ supposed to use.
+
+ @return the test runner name that should be used by default when
+ no test runner was explicitly called out on the command line.
+ """
+ if num_threads == 1:
+ # Use the serial runner.
+ test_runner_name = "serial"
+ elif os.name == "nt":
+ # On Windows, Python uses CRT with a low limit on the number of open
+ # files. If you have a lot of cores, the threading-pool runner will
+ # often fail because it exceeds that limit. It's not clear what the
+ # right balance is, so until we can investigate it more deeply,
+ # just use the one that works
+ test_runner_name = "multiprocessing-pool"
+ elif is_darwin_version_lower_than(
+ distutils.version.StrictVersion("10.10.0")):
+ # OS X versions before 10.10 appear to have an issue using
+ # the threading test runner. Fall back to multiprocessing.
+ # Supports Ctrl-C.
+ test_runner_name = "multiprocessing"
+ else:
+ # For everyone else, use the ctrl-c-enabled threading support.
+ # Should use fewer system resources than the multprocessing
+ # variant.
+ test_runner_name = "threading"
+ return test_runner_name
+
+
+def rerun_tests(test_subdir, tests_for_rerun, dotest_argv):
+ # Build the list of test files to rerun. Some future time we'll
+ # enable re-run by test method so we can constrain the rerun set
+ # to just the method(s) that were in issued within a file.
+
+ # Sort rerun files into subdirectories.
+ print("\nRerunning the following files:")
+ rerun_files_by_subdir = {}
+ for test_filename in tests_for_rerun.keys():
+ # Print the file we'll be rerunning
+ test_relative_path = os.path.relpath(
+ test_filename, lldbsuite.lldb_test_root)
+ print(" {}".format(test_relative_path))
+
+ # Store test filenames by subdir.
+ test_dir = os.path.dirname(test_filename)
+ test_basename = os.path.basename(test_filename)
+ if test_dir in rerun_files_by_subdir:
+ rerun_files_by_subdir[test_dir].append(
+ (test_basename, test_filename))
+ else:
+ rerun_files_by_subdir[test_dir] = [(test_basename, test_filename)]
+
+ # Break rerun work up by subdirectory. We do this since
+ # we have an invariant that states only one test file can
+ # be run at a time in any given subdirectory (related to
+ # rules around built inferior test program lifecycle).
+ rerun_work = []
+ for files_by_subdir in rerun_files_by_subdir.values():
+ rerun_work.append((test_subdir, files_by_subdir))
+
+ # Run the work with the serial runner.
+ # Do not update legacy counts, I am getting rid of
+ # them so no point adding complicated merge logic here.
+ rerun_thread_count = 1
+ # Force the parallel test runner to choose a multi-worker strategy.
+ rerun_runner_name = default_test_runner_name(rerun_thread_count + 1)
+ print("rerun will use the '{}' test runner strategy".format(
+ rerun_runner_name))
+
+ runner_strategies_by_name = get_test_runner_strategies(rerun_thread_count)
+ rerun_runner_func = runner_strategies_by_name[
+ rerun_runner_name]
+ if rerun_runner_func is None:
+ raise Exception(
+ "failed to find rerun test runner "
+ "function named '{}'".format(rerun_runner_name))
+
+ walk_and_invoke(
+ rerun_work,
+ dotest_argv,
+ rerun_thread_count,
+ rerun_runner_func)
+ print("\nTest rerun complete\n")
+
+
+def main(num_threads, test_subdir, test_runner_name, results_formatter):
+ """Run dotest.py in inferior mode in parallel.
+
+ @param num_threads the parsed value of the num-threads command line
+ argument.
+
+ @param test_subdir optionally specifies a subdir to limit testing
+ within. May be None if the entire test tree is to be used. This subdir
+ is assumed to be relative to the lldb/test root of the test hierarchy.
+
+ @param test_runner_name if specified, contains the test runner
+ name which selects the strategy used to run the isolated and
+ optionally concurrent test runner. Specify None to allow the
+ system to choose the most appropriate test runner given desired
+ thread count and OS type.
+
+ @param results_formatter if specified, provides the TestResultsFormatter
+ instance that will format and output test result data from the
+ side-channel test results. When specified, inferior dotest calls
+ will send test results side-channel data over a socket to the parallel
+ test runner, which will forward them on to results_formatter.
+ """
+
+ # Do not shut down on sighup.
+ if hasattr(signal, 'SIGHUP'):
+ signal.signal(signal.SIGHUP, signal.SIG_IGN)
+
+ dotest_argv = sys.argv[1:]
+
+ global RESULTS_FORMATTER
+ RESULTS_FORMATTER = results_formatter
+
+ # We can't use sys.path[0] to determine the script directory
+ # because it doesn't work under a debugger
+ parser = dotest_args.create_parser()
+ global dotest_options
+ dotest_options = dotest_args.parse_args(parser, dotest_argv)
+
+ adjust_inferior_options(dotest_argv)
+
+ session_dir = os.path.join(os.getcwd(), dotest_options.s)
+
+ # The root directory was specified on the command line
+ test_directory = os.path.dirname(os.path.realpath(__file__))
+ if test_subdir and len(test_subdir) > 0:
+ test_subdir = os.path.join(test_directory, test_subdir)
+ else:
+ test_subdir = test_directory
+
+ # clean core files in test tree from previous runs (Linux)
+ cores = find('core.*', test_subdir)
+ for core in cores:
+ os.unlink(core)
+
+ system_info = " ".join(platform.uname())
+
+ # Figure out which test files should be enabled for expected
+ # timeout
+ expected_timeout = getExpectedTimeouts(dotest_options.lldb_platform_name)
+ if results_formatter is not None:
+ results_formatter.set_expected_timeouts_by_basename(expected_timeout)
+
+ # Figure out which testrunner strategy we'll use.
+ runner_strategies_by_name = get_test_runner_strategies(num_threads)
+
+ # If the user didn't specify a test runner strategy, determine
+ # the default now based on number of threads and OS type.
+ if not test_runner_name:
+ test_runner_name = default_test_runner_name(num_threads)
+
+ if test_runner_name not in runner_strategies_by_name:
+ raise Exception(
+ "specified testrunner name '{}' unknown. Valid choices: {}".format(
+ test_runner_name,
+ list(runner_strategies_by_name.keys())))
+ test_runner_func = runner_strategies_by_name[test_runner_name]
+
+ # Collect the files on which we'll run the first test run phase.
+ test_files = []
+ find_test_files_in_dir_tree(
+ test_subdir, lambda tdir, tfiles: test_files.append(
+ (test_subdir, tfiles)))
+
+ # Do the first test run phase.
+ summary_results = walk_and_invoke(
+ test_files,
+ dotest_argv,
+ num_threads,
+ test_runner_func)
+
+ (timed_out, passed, failed, unexpected_successes, pass_count,
+ fail_count) = summary_results
+
+ # Check if we have any tests to rerun as phase 2.
+ if results_formatter is not None:
+ tests_for_rerun = results_formatter.tests_for_rerun
+ results_formatter.tests_for_rerun = {}
+
+ if tests_for_rerun is not None and len(tests_for_rerun) > 0:
+ rerun_file_count = len(tests_for_rerun)
+ print("\n{} test files marked for rerun\n".format(
+ rerun_file_count))
+
+ # Check if the number of files exceeds the max cutoff. If so,
+ # we skip the rerun step.
+ if rerun_file_count > configuration.rerun_max_file_threshold:
+ print("Skipping rerun: max rerun file threshold ({}) "
+ "exceeded".format(
+ configuration.rerun_max_file_threshold))
+ else:
+ rerun_tests(test_subdir, tests_for_rerun, dotest_argv)
+
+ # The results formatter - if present - is done now. Tell it to
+ # terminate.
+ if results_formatter is not None:
+ results_formatter.send_terminate_as_needed()
+
+ timed_out = set(timed_out)
+ num_test_files = len(passed) + len(failed)
+ num_test_cases = pass_count + fail_count
+
+ # move core files into session dir
+ cores = find('core.*', test_subdir)
+ for core in cores:
+ dst = core.replace(test_directory, "")[1:]
+ dst = dst.replace(os.path.sep, "-")
+ os.rename(core, os.path.join(session_dir, dst))
+
+ # remove expected timeouts from failures
+ for xtime in expected_timeout:
+ if xtime in timed_out:
+ timed_out.remove(xtime)
+ failed.remove(xtime)
+ result = "ExpectedTimeout"
+ elif xtime in passed:
+ result = "UnexpectedCompletion"
+ else:
+ result = None # failed
+
+ if result:
+ test_name = os.path.splitext(xtime)[0]
+ touch(os.path.join(session_dir, "{}-{}".format(result, test_name)))
+
+ # Only run the old summary logic if we don't have a results formatter
+ # that already prints the summary.
+ print_legacy_summary = results_formatter is None
+ if not print_legacy_summary:
+ # Print summary results. Summarized results at the end always
+ # get printed to stdout, even if --results-file specifies a different
+ # file for, say, xUnit output.
+ results_formatter.print_results(sys.stdout)
+
+ # Figure out exit code by count of test result types.
+ issue_count = 0
+ for issue_status in EventBuilder.TESTRUN_ERROR_STATUS_VALUES:
+ issue_count += results_formatter.counts_by_test_result_status(
+ issue_status)
+
+ # Return with appropriate result code
+ if issue_count > 0:
+ sys.exit(1)
+ else:
+ sys.exit(0)
+ else:
+ # Print the legacy test results summary.
+ print()
+ sys.stdout.write("Ran %d test suites" % num_test_files)
+ if num_test_files > 0:
+ sys.stdout.write(" (%d failed) (%f%%)" % (
+ len(failed), 100.0 * len(failed) / num_test_files))
+ print()
+ sys.stdout.write("Ran %d test cases" % num_test_cases)
+ if num_test_cases > 0:
+ sys.stdout.write(" (%d failed) (%f%%)" % (
+ fail_count, 100.0 * fail_count / num_test_cases))
+ print()
+ exit_code = 0
+
+ if len(failed) > 0:
+ failed.sort()
+ print("Failing Tests (%d)" % len(failed))
+ for f in failed:
+ print("%s: LLDB (suite) :: %s (%s)" % (
+ "TIMEOUT" if f in timed_out else "FAIL", f, system_info
+ ))
+ exit_code = 1
+
+ if len(unexpected_successes) > 0:
+ unexpected_successes.sort()
+ print("\nUnexpected Successes (%d)" % len(unexpected_successes))
+ for u in unexpected_successes:
+ print("UNEXPECTED SUCCESS: LLDB (suite) :: %s (%s)" % (u, system_info))
+
+ sys.exit(exit_code)
+
+if __name__ == '__main__':
+ sys.stderr.write(
+ "error: dosep.py no longer supports being called directly. "
+ "Please call dotest.py directly. The dosep.py-specific arguments "
+ "have been added under the Parallel processing arguments.\n")
+ sys.exit(128)
diff --git a/packages/Python/lldbsuite/test/dotest.py b/packages/Python/lldbsuite/test/dotest.py
new file mode 100644
index 000000000000..723f26a417e4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/dotest.py
@@ -0,0 +1,1128 @@
+"""
+A simple testing framework for lldb using python's unit testing framework.
+
+Tests for lldb are written as python scripts which take advantage of the script
+bridging provided by LLDB.framework to interact with lldb core.
+
+A specific naming pattern is followed by the .py script to be recognized as
+a module which implements a test scenario, namely, Test*.py.
+
+To specify the directories where "Test*.py" python test scripts are located,
+you need to pass in a list of directory names. By default, the current
+working directory is searched if nothing is specified on the command line.
+
+Type:
+
+./dotest.py -h
+
+for available options.
+"""
+
+from __future__ import absolute_import
+from __future__ import print_function
+
+# System modules
+import atexit
+import importlib
+import os
+import errno
+import platform
+import signal
+import socket
+import subprocess
+import sys
+import inspect
+
+# Third-party modules
+import six
+import unittest2
+
+# LLDB Modules
+import lldbsuite
+from . import configuration
+from . import dotest_args
+from . import lldbtest_config
+from . import test_categories
+from . import result_formatter
+from . import test_result
+from .result_formatter import EventBuilder
+from ..support import seven
+
+def is_exe(fpath):
+ """Returns true if fpath is an executable."""
+ 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 _WritelnDecorator(object):
+ """Used to decorate file-like objects with a handy 'writeln' method"""
+ def __init__(self,stream):
+ self.stream = stream
+
+ def __getattr__(self, attr):
+ if attr in ('stream', '__getstate__'):
+ raise AttributeError(attr)
+ return getattr(self.stream,attr)
+
+ def writeln(self, arg=None):
+ if arg:
+ self.write(arg)
+ self.write('\n') # text-mode streams translate to \r\n if needed
+
+#
+# Global variables:
+#
+def usage(parser):
+ parser.print_help()
+ if configuration.verbose > 0:
+ print("""
+Examples:
+
+This is an example of using the -f option to pinpoint to a specific test class
+and test method to be run:
+
+$ ./dotest.py -f ClassTypesTestCase.test_with_dsym_and_run_command
+----------------------------------------------------------------------
+Collected 1 test
+
+test_with_dsym_and_run_command (TestClassTypes.ClassTypesTestCase)
+Test 'frame variable this' when stopped on a class constructor. ... ok
+
+----------------------------------------------------------------------
+Ran 1 test in 1.396s
+
+OK
+
+And this is an example of using the -p option to run a single file (the filename
+matches the pattern 'ObjC' and it happens to be 'TestObjCMethods.py'):
+
+$ ./dotest.py -v -p ObjC
+----------------------------------------------------------------------
+Collected 4 tests
+
+test_break_with_dsym (TestObjCMethods.FoundationTestCase)
+Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'. ... ok
+test_break_with_dwarf (TestObjCMethods.FoundationTestCase)
+Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'. ... ok
+test_data_type_and_expr_with_dsym (TestObjCMethods.FoundationTestCase)
+Lookup objective-c data types and evaluate expressions. ... ok
+test_data_type_and_expr_with_dwarf (TestObjCMethods.FoundationTestCase)
+Lookup objective-c data types and evaluate expressions. ... ok
+
+----------------------------------------------------------------------
+Ran 4 tests in 16.661s
+
+OK
+
+Running of this script also sets up the LLDB_TEST environment variable so that
+individual test cases can locate their supporting files correctly. The script
+tries to set up Python's search paths for modules by looking at the build tree
+relative to this script. See also the '-i' option in the following example.
+
+Finally, this is an example of using the lldb.py module distributed/installed by
+Xcode4 to run against the tests under the 'forward' directory, and with the '-w'
+option to add some delay between two tests. It uses ARCH=x86_64 to specify that
+as the architecture and CC=clang to specify the compiler used for the test run:
+
+$ PYTHONPATH=/Xcode4/Library/PrivateFrameworks/LLDB.framework/Versions/A/Resources/Python ARCH=x86_64 CC=clang ./dotest.py -v -w -i forward
+
+Session logs for test failures/errors will go into directory '2010-11-11-13_56_16'
+----------------------------------------------------------------------
+Collected 2 tests
+
+test_with_dsym_and_run_command (TestForwardDeclaration.ForwardDeclarationTestCase)
+Display *bar_ptr when stopped on a function with forward declaration of struct bar. ... ok
+test_with_dwarf_and_run_command (TestForwardDeclaration.ForwardDeclarationTestCase)
+Display *bar_ptr when stopped on a function with forward declaration of struct bar. ... ok
+
+----------------------------------------------------------------------
+Ran 2 tests in 5.659s
+
+OK
+
+The 'Session ...' verbiage is recently introduced (see also the '-s' option) to
+notify the directory containing the session logs for test failures or errors.
+In case there is any test failure/error, a similar message is appended at the
+end of the stderr output for your convenience.
+
+ENABLING LOGS FROM TESTS
+
+Option 1:
+
+Writing logs into different files per test case::
+
+This option is particularly useful when multiple dotest instances are created
+by dosep.py
+
+$ ./dotest.py --channel "lldb all"
+
+$ ./dotest.py --channel "lldb all" --channel "gdb-remote packets"
+
+These log files are written to:
+
+<session-dir>/<test-id>-host.log (logs from lldb host process)
+<session-dir>/<test-id>-server.log (logs from debugserver/lldb-server)
+<session-dir>/<test-id>-<test-result>.log (console logs)
+
+By default, logs from successful runs are deleted. Use the --log-success flag
+to create reference logs for debugging.
+
+$ ./dotest.py --log-success
+
+Option 2: (DEPRECATED)
+
+The following options can only enable logs from the host lldb process.
+Only categories from the "lldb" or "gdb-remote" channels can be enabled
+They also do not automatically enable logs in locally running debug servers.
+Also, logs from all test case are written into each log file
+
+o LLDB_LOG: if defined, specifies the log file pathname for the 'lldb' subsystem
+ with a default option of 'event process' if LLDB_LOG_OPTION is not defined.
+
+o GDB_REMOTE_LOG: if defined, specifies the log file pathname for the
+ 'process.gdb-remote' subsystem with a default option of 'packets' if
+ GDB_REMOTE_LOG_OPTION is not defined.
+
+""")
+ sys.exit(0)
+
+def parseOptionsAndInitTestdirs():
+ """Initialize the list of directories containing our unittest scripts.
+
+ '-h/--help as the first option prints out usage info and exit the program.
+ """
+
+ do_help = False
+
+ platform_system = platform.system()
+ platform_machine = platform.machine()
+
+ parser = dotest_args.create_parser()
+ args = dotest_args.parse_args(parser, sys.argv[1:])
+
+ if args.unset_env_varnames:
+ for env_var in args.unset_env_varnames:
+ if env_var in os.environ:
+ # From Python Doc: When unsetenv() is supported, deletion of items in os.environ
+ # is automatically translated into a corresponding call to unsetenv().
+ del os.environ[env_var]
+ #os.unsetenv(env_var)
+
+ if args.set_env_vars:
+ for env_var in args.set_env_vars:
+ parts = env_var.split('=', 1)
+ if len(parts) == 1:
+ os.environ[parts[0]] = ""
+ else:
+ os.environ[parts[0]] = parts[1]
+
+ # only print the args if being verbose (and parsable is off)
+ if args.v and not args.q:
+ print(sys.argv)
+
+ if args.h:
+ do_help = True
+
+ if args.compilers:
+ configuration.compilers = args.compilers
+ else:
+ # Use a compiler appropriate appropriate for the Apple SDK if one was specified
+ if platform_system == 'Darwin' and args.apple_sdk:
+ configuration.compilers = [seven.get_command_output('xcrun -sdk "%s" -find clang 2> /dev/null' % (args.apple_sdk))]
+ else:
+ # 'clang' on ubuntu 14.04 is 3.4 so we try clang-3.5 first
+ candidateCompilers = ['clang-3.5', 'clang', 'gcc']
+ for candidate in candidateCompilers:
+ if which(candidate):
+ configuration.compilers = [candidate]
+ break
+
+ if args.channels:
+ lldbtest_config.channels = args.channels
+
+ if args.log_success:
+ lldbtest_config.log_success = args.log_success
+
+ # Set SDKROOT if we are using an Apple SDK
+ if platform_system == 'Darwin' and args.apple_sdk:
+ os.environ['SDKROOT'] = seven.get_command_output('xcrun --sdk "%s" --show-sdk-path 2> /dev/null' % (args.apple_sdk))
+
+ if args.archs:
+ configuration.archs = args.archs
+ for arch in configuration.archs:
+ if arch.startswith('arm') and platform_system == 'Darwin' and not args.apple_sdk:
+ os.environ['SDKROOT'] = seven.get_command_output('xcrun --sdk iphoneos.internal --show-sdk-path 2> /dev/null')
+ if not os.path.exists(os.environ['SDKROOT']):
+ os.environ['SDKROOT'] = seven.get_command_output('xcrun --sdk iphoneos --show-sdk-path 2> /dev/null')
+ else:
+ configuration.archs = [platform_machine]
+
+ if args.categoriesList:
+ configuration.categoriesList = set(test_categories.validate(args.categoriesList, False))
+ configuration.useCategories = True
+ else:
+ configuration.categoriesList = []
+
+ if args.skipCategories:
+ configuration.skipCategories = test_categories.validate(args.skipCategories, False)
+
+ if args.E:
+ cflags_extras = args.E
+ os.environ['CFLAGS_EXTRAS'] = cflags_extras
+
+ if args.d:
+ sys.stdout.write("Suspending the process %d to wait for debugger to attach...\n" % os.getpid())
+ sys.stdout.flush()
+ os.kill(os.getpid(), signal.SIGSTOP)
+
+ if args.f:
+ if any([x.startswith('-') for x in args.f]):
+ usage(parser)
+ configuration.filters.extend(args.f)
+ # Shut off multiprocessing mode when additional filters are specified.
+ # The rational is that the user is probably going after a very specific
+ # test and doesn't need a bunch of parallel test runners all looking for
+ # it in a frenzy. Also, '-v' now spits out all test run output even
+ # on success, so the standard recipe for redoing a failing test (with -v
+ # and a -f to filter to the specific test) now causes all test scanning
+ # (in parallel) to print results for do-nothing runs in a very distracting
+ # manner. If we really need filtered parallel runs in the future, consider
+ # adding a --no-output-on-success that prevents -v from setting
+ # output-on-success.
+ configuration.no_multiprocess_test_runner = True
+
+ if args.l:
+ configuration.skip_long_running_test = False
+
+ if args.framework:
+ configuration.lldbFrameworkPath = args.framework
+
+ if args.executable:
+ lldbtest_config.lldbExec = args.executable
+
+ if args.p:
+ if args.p.startswith('-'):
+ usage(parser)
+ configuration.regexp = args.p
+
+ if args.q:
+ configuration.parsable = True
+
+ if args.s:
+ if args.s.startswith('-'):
+ usage(parser)
+ configuration.sdir_name = args.s
+
+ if args.t:
+ os.environ['LLDB_COMMAND_TRACE'] = 'YES'
+
+ if args.v:
+ configuration.verbose = 2
+
+ # argparse makes sure we have a number
+ if args.sharp:
+ configuration.count = args.sharp
+
+ if sys.platform.startswith('win32'):
+ os.environ['LLDB_DISABLE_CRASH_DIALOG'] = str(args.disable_crash_dialog)
+ os.environ['LLDB_LAUNCH_INFERIORS_WITHOUT_CONSOLE'] = str(True)
+
+ if do_help == True:
+ usage(parser)
+
+ if args.no_multiprocess:
+ configuration.no_multiprocess_test_runner = True
+
+ if args.inferior:
+ configuration.is_inferior_test_runner = True
+
+ if args.num_threads:
+ configuration.num_threads = args.num_threads
+
+ if args.test_subdir:
+ configuration.multiprocess_test_subdir = args.test_subdir
+
+ if args.test_runner_name:
+ configuration.test_runner_name = args.test_runner_name
+
+ # Capture test results-related args.
+ if args.curses and not args.inferior:
+ # Act as if the following args were set.
+ args.results_formatter = "lldbsuite.test.curses_results.Curses"
+ args.results_file = "stdout"
+
+ if args.results_file:
+ configuration.results_filename = args.results_file
+
+ if args.results_port:
+ configuration.results_port = args.results_port
+
+ if args.results_file and args.results_port:
+ sys.stderr.write(
+ "only one of --results-file and --results-port should "
+ "be specified\n")
+ usage(args)
+
+ if args.results_formatter:
+ configuration.results_formatter_name = args.results_formatter
+ if args.results_formatter_options:
+ configuration.results_formatter_options = args.results_formatter_options
+
+ # Default to using the BasicResultsFormatter if no formatter is specified
+ # and we're not a test inferior.
+ if not args.inferior and configuration.results_formatter_name is None:
+ configuration.results_formatter_name = (
+ "lldbsuite.test.result_formatter.ResultsFormatter")
+
+ # rerun-related arguments
+ configuration.rerun_all_issues = args.rerun_all_issues
+ configuration.rerun_max_file_threshold = args.rerun_max_file_threshold
+
+ if args.lldb_platform_name:
+ configuration.lldb_platform_name = args.lldb_platform_name
+ if args.lldb_platform_url:
+ configuration.lldb_platform_url = args.lldb_platform_url
+ if args.lldb_platform_working_dir:
+ configuration.lldb_platform_working_dir = args.lldb_platform_working_dir
+
+ if args.event_add_entries and len(args.event_add_entries) > 0:
+ entries = {}
+ # Parse out key=val pairs, separated by comma
+ for keyval in args.event_add_entries.split(","):
+ key_val_entry = keyval.split("=")
+ if len(key_val_entry) == 2:
+ (key, val) = key_val_entry
+ val_parts = val.split(':')
+ if len(val_parts) > 1:
+ (val, val_type) = val_parts
+ if val_type == 'int':
+ val = int(val)
+ entries[key] = val
+ # Tell the event builder to create all events with these
+ # key/val pairs in them.
+ if len(entries) > 0:
+ result_formatter.EventBuilder.add_entries_to_all_events(entries)
+
+ # Gather all the dirs passed on the command line.
+ if len(args.args) > 0:
+ configuration.testdirs = list(map(lambda x: os.path.realpath(os.path.abspath(x)), args.args))
+ # Shut off multiprocessing mode when test directories are specified.
+ configuration.no_multiprocess_test_runner = True
+
+ #print("testdirs:", testdirs)
+
+def getXcodeOutputPaths(lldbRootDirectory):
+ result = []
+
+ # These are for xcode build directories.
+ xcode3_build_dir = ['build']
+ xcode4_build_dir = ['build', 'lldb', 'Build', 'Products']
+
+ configurations = [['Debug'], ['DebugClang'], ['Release'], ['BuildAndIntegration']]
+ xcode_build_dirs = [xcode3_build_dir, xcode4_build_dir]
+ for configuration in configurations:
+ for xcode_build_dir in xcode_build_dirs:
+ outputPath = os.path.join(lldbRootDirectory, *(xcode_build_dir+configuration) )
+ result.append(outputPath)
+
+ return result
+
+
+def createSocketToLocalPort(port):
+ def socket_closer(s):
+ """Close down an opened socket properly."""
+ s.shutdown(socket.SHUT_RDWR)
+ s.close()
+
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ sock.connect(("localhost", port))
+ return (sock, lambda: socket_closer(sock))
+
+
+def setupTestResults():
+ """Sets up test results-related objects based on arg settings."""
+ # Setup the results formatter configuration.
+ formatter_config = result_formatter.FormatterConfig()
+ formatter_config.filename = configuration.results_filename
+ formatter_config.formatter_name = configuration.results_formatter_name
+ formatter_config.formatter_options = (
+ configuration.results_formatter_options)
+ formatter_config.port = configuration.results_port
+
+ # Create the results formatter.
+ formatter_spec = result_formatter.create_results_formatter(
+ formatter_config)
+ if formatter_spec is not None and formatter_spec.formatter is not None:
+ configuration.results_formatter_object = formatter_spec.formatter
+
+ # Send an intialize message to the formatter.
+ initialize_event = EventBuilder.bare_event("initialize")
+ if isMultiprocessTestRunner():
+ if (configuration.test_runner_name is not None and
+ configuration.test_runner_name == "serial"):
+ # Only one worker queue here.
+ worker_count = 1
+ else:
+ # Workers will be the number of threads specified.
+ worker_count = configuration.num_threads
+ else:
+ worker_count = 1
+ initialize_event["worker_count"] = worker_count
+
+ formatter_spec.formatter.handle_event(initialize_event)
+
+ # Make sure we clean up the formatter on shutdown.
+ if formatter_spec.cleanup_func is not None:
+ atexit.register(formatter_spec.cleanup_func)
+
+
+def getOutputPaths(lldbRootDirectory):
+ """
+ Returns typical build output paths for the lldb executable
+
+ lldbDirectory - path to the root of the lldb svn/git repo
+ """
+ result = []
+
+ if sys.platform == 'darwin':
+ result.extend(getXcodeOutputPaths(lldbRootDirectory))
+
+ # cmake builds? look for build or build/host folder next to llvm directory
+ # lldb is located in llvm/tools/lldb so we need to go up three levels
+ llvmParentDir = os.path.abspath(os.path.join(lldbRootDirectory, os.pardir, os.pardir, os.pardir))
+ result.append(os.path.join(llvmParentDir, 'build', 'bin'))
+ result.append(os.path.join(llvmParentDir, 'build', 'host', 'bin'))
+
+ # some cmake developers keep their build directory beside their lldb directory
+ lldbParentDir = os.path.abspath(os.path.join(lldbRootDirectory, os.pardir))
+ result.append(os.path.join(lldbParentDir, 'build', 'bin'))
+ result.append(os.path.join(lldbParentDir, 'build', 'host', 'bin'))
+
+ return result
+
+def setupSysPath():
+ """
+ Add LLDB.framework/Resources/Python to the search paths for modules.
+ As a side effect, we also discover the 'lldb' executable and export it here.
+ """
+
+ # Get the directory containing the current script.
+ if "DOTEST_PROFILE" in os.environ and "DOTEST_SCRIPT_DIR" in os.environ:
+ scriptPath = os.environ["DOTEST_SCRIPT_DIR"]
+ else:
+ scriptPath = os.path.dirname(os.path.realpath(__file__))
+ if not scriptPath.endswith('test'):
+ print("This script expects to reside in lldb's test directory.")
+ sys.exit(-1)
+
+ os.environ["LLDB_TEST"] = scriptPath
+
+ # Set up the LLDB_SRC environment variable, so that the tests can locate
+ # the LLDB source code.
+ os.environ["LLDB_SRC"] = lldbsuite.lldb_root
+
+ pluginPath = os.path.join(scriptPath, 'plugins')
+ toolsLLDBMIPath = os.path.join(scriptPath, 'tools', 'lldb-mi')
+ toolsLLDBServerPath = os.path.join(scriptPath, 'tools', 'lldb-server')
+
+ # Insert script dir, plugin dir, lldb-mi dir and lldb-server dir to the sys.path.
+ sys.path.insert(0, pluginPath)
+ sys.path.insert(0, toolsLLDBMIPath) # Adding test/tools/lldb-mi to the path makes it easy
+ # to "import lldbmi_testcase" from the MI tests
+ sys.path.insert(0, toolsLLDBServerPath) # Adding test/tools/lldb-server to the path makes it easy
+ # to "import lldbgdbserverutils" from the lldb-server tests
+
+ # This is the root of the lldb git/svn checkout
+ # When this changes over to a package instead of a standalone script, this
+ # will be `lldbsuite.lldb_root`
+ lldbRootDirectory = lldbsuite.lldb_root
+
+ # Some of the tests can invoke the 'lldb' command directly.
+ # We'll try to locate the appropriate executable right here.
+
+ # The lldb executable can be set from the command line
+ # if it's not set, we try to find it now
+ # first, we try the environment
+ if not lldbtest_config.lldbExec:
+ # First, you can define an environment variable LLDB_EXEC specifying the
+ # full pathname of the lldb executable.
+ if "LLDB_EXEC" in os.environ:
+ lldbtest_config.lldbExec = os.environ["LLDB_EXEC"]
+
+ if not lldbtest_config.lldbExec:
+ outputPaths = getOutputPaths(lldbRootDirectory)
+ for outputPath in outputPaths:
+ candidatePath = os.path.join(outputPath, 'lldb')
+ if is_exe(candidatePath):
+ lldbtest_config.lldbExec = candidatePath
+ break
+
+ if not lldbtest_config.lldbExec:
+ # Last, check the path
+ lldbtest_config.lldbExec = which('lldb')
+
+ if lldbtest_config.lldbExec and not is_exe(lldbtest_config.lldbExec):
+ print("'{}' is not a path to a valid executable".format(lldbtest_config.lldbExec))
+ lldbtest_config.lldbExec = None
+
+ if not lldbtest_config.lldbExec:
+ print("The 'lldb' executable cannot be located. Some of the tests may not be run as a result.")
+ sys.exit(-1)
+
+ lldbLibDir = os.path.dirname(lldbtest_config.lldbExec) # confusingly, this is the "bin" directory
+ os.environ["LLDB_LIB_DIR"] = lldbLibDir
+ lldbImpLibDir = os.path.join(lldbLibDir, '..', 'lib') if sys.platform.startswith('win32') else lldbLibDir
+ os.environ["LLDB_IMPLIB_DIR"] = lldbImpLibDir
+ print("LLDB library dir:", os.environ["LLDB_LIB_DIR"])
+ print("LLDB import library dir:", os.environ["LLDB_IMPLIB_DIR"])
+ os.system('%s -v' % lldbtest_config.lldbExec)
+
+ # Assume lldb-mi is in same place as lldb
+ # If not found, disable the lldb-mi tests
+ lldbMiExec = None
+ if lldbtest_config.lldbExec and is_exe(lldbtest_config.lldbExec + "-mi"):
+ lldbMiExec = lldbtest_config.lldbExec + "-mi"
+ if not lldbMiExec:
+ if not configuration.shouldSkipBecauseOfCategories(["lldb-mi"]):
+ print("The 'lldb-mi' executable cannot be located. The lldb-mi tests can not be run as a result.")
+ configuration.skipCategories.append("lldb-mi")
+ else:
+ os.environ["LLDBMI_EXEC"] = lldbMiExec
+
+ lldbPythonDir = None # The directory that contains 'lldb/__init__.py'
+ if configuration.lldbFrameworkPath:
+ candidatePath = os.path.join(configuration.lldbFrameworkPath, 'Resources', 'Python')
+ if os.path.isfile(os.path.join(candidatePath, 'lldb/__init__.py')):
+ lldbPythonDir = candidatePath
+ if not lldbPythonDir:
+ print('Resources/Python/lldb/__init__.py was not found in ' + configuration.lldbFrameworkPath)
+ sys.exit(-1)
+ else:
+ # If our lldb supports the -P option, use it to find the python path:
+ init_in_python_dir = os.path.join('lldb', '__init__.py')
+
+ lldb_dash_p_result = subprocess.check_output([lldbtest_config.lldbExec, "-P"], stderr=subprocess.STDOUT, universal_newlines=True)
+
+ if lldb_dash_p_result and not lldb_dash_p_result.startswith(("<", "lldb: invalid option:")) \
+ and not lldb_dash_p_result.startswith("Traceback"):
+ lines = lldb_dash_p_result.splitlines()
+
+ # Workaround for readline vs libedit issue on FreeBSD. If stdout
+ # is not a terminal Python executes
+ # rl_variable_bind ("enable-meta-key", "off");
+ # This produces a warning with FreeBSD's libedit because the
+ # enable-meta-key variable is unknown. Not an issue on Apple
+ # because cpython commit f0ab6f9f0603 added a #ifndef __APPLE__
+ # around the call. See http://bugs.python.org/issue19884 for more
+ # information. For now we just discard the warning output.
+ if len(lines) >= 1 and lines[0].startswith("bind: Invalid command"):
+ lines.pop(0)
+
+ # Taking the last line because lldb outputs
+ # 'Cannot read termcap database;\nusing dumb terminal settings.\n'
+ # before the path
+ if len(lines) >= 1 and os.path.isfile(os.path.join(lines[-1], init_in_python_dir)):
+ lldbPythonDir = lines[-1]
+ if "freebsd" in sys.platform or "linux" in sys.platform:
+ os.environ['LLDB_LIB_DIR'] = os.path.join(lldbPythonDir, '..', '..')
+
+ if not lldbPythonDir:
+ if platform.system() == "Darwin":
+ python_resource_dir = ['LLDB.framework', 'Resources', 'Python']
+ outputPaths = getXcodeOutputPaths()
+ for outputPath in outputPaths:
+ candidatePath = os.path.join(outputPath, python_resource_dir)
+ if os.path.isfile(os.path.join(candidatePath, init_in_python_dir)):
+ lldbPythonDir = candidatePath
+ break
+
+ if not lldbPythonDir:
+ print('This script requires lldb.py to be in either ' + dbgPath + ',', end=' ')
+ print(relPath + ', or ' + baiPath + '. Some tests might fail.')
+ else:
+ print("Unable to load lldb extension module. Possible reasons for this include:")
+ print(" 1) LLDB was built with LLDB_DISABLE_PYTHON=1")
+ print(" 2) PYTHONPATH and PYTHONHOME are not set correctly. PYTHONHOME should refer to")
+ print(" the version of Python that LLDB built and linked against, and PYTHONPATH")
+ print(" should contain the Lib directory for the same python distro, as well as the")
+ print(" location of LLDB\'s site-packages folder.")
+ print(" 3) A different version of Python than that which was built against is exported in")
+ print(" the system\'s PATH environment variable, causing conflicts.")
+ print(" 4) The executable '%s' could not be found. Please check " % lldbExecutable)
+ print(" that it exists and is executable.")
+
+ if lldbPythonDir:
+ lldbPythonDir = os.path.normpath(lldbPythonDir)
+ # Some of the code that uses this path assumes it hasn't resolved the Versions... link.
+ # If the path we've constructed looks like that, then we'll strip out the Versions/A part.
+ (before, frameWithVersion, after) = lldbPythonDir.rpartition("LLDB.framework/Versions/A")
+ if frameWithVersion != "" :
+ lldbPythonDir = before + "LLDB.framework" + after
+
+ lldbPythonDir = os.path.abspath(lldbPythonDir)
+
+ # If tests need to find LLDB_FRAMEWORK, now they can do it
+ os.environ["LLDB_FRAMEWORK"] = os.path.dirname(os.path.dirname(lldbPythonDir))
+
+ # This is to locate the lldb.py module. Insert it right after sys.path[0].
+ sys.path[1:1] = [lldbPythonDir]
+
+def visit(prefix, dir, names):
+ """Visitor function for os.path.walk(path, visit, arg)."""
+
+ dir_components = set(dir.split(os.sep))
+ excluded_components = set(['.svn', '.git'])
+ if dir_components.intersection(excluded_components):
+ #print("Detected an excluded dir component: %s" % dir)
+ return
+
+ for name in names:
+ if '.py' == os.path.splitext(name)[1] and name.startswith(prefix):
+
+ if name in configuration.all_tests:
+ raise Exception("Found multiple tests with the name %s" % name)
+ configuration.all_tests.add(name)
+
+ # Try to match the regexp pattern, if specified.
+ if configuration.regexp:
+ import re
+ if re.search(configuration.regexp, name):
+ #print("Filename: '%s' matches pattern: '%s'" % (name, regexp))
+ pass
+ else:
+ #print("Filename: '%s' does not match pattern: '%s'" % (name, regexp))
+ continue
+
+ # We found a match for our test. Add it to the suite.
+
+ # Update the sys.path first.
+ if not sys.path.count(dir):
+ sys.path.insert(0, dir)
+ base = os.path.splitext(name)[0]
+
+ # Thoroughly check the filterspec against the base module and admit
+ # the (base, filterspec) combination only when it makes sense.
+ filterspec = None
+ for filterspec in configuration.filters:
+ # Optimistically set the flag to True.
+ filtered = True
+ module = __import__(base)
+ parts = filterspec.split('.')
+ obj = module
+ for part in parts:
+ try:
+ parent, obj = obj, getattr(obj, part)
+ except AttributeError:
+ # The filterspec has failed.
+ filtered = False
+ break
+
+ # If filtered, we have a good filterspec. Add it.
+ if filtered:
+ #print("adding filter spec %s to module %s" % (filterspec, module))
+ configuration.suite.addTests(
+ unittest2.defaultTestLoader.loadTestsFromName(filterspec, module))
+ continue
+
+ # Forgo this module if the (base, filterspec) combo is invalid
+ if configuration.filters and not filtered:
+ continue
+
+ # Add either the filtered test case(s) (which is done before) or the entire test class.
+ if not filterspec or not filtered:
+ # A simple case of just the module name. Also the failover case
+ # from the filterspec branch when the (base, filterspec) combo
+ # doesn't make sense.
+ configuration.suite.addTests(unittest2.defaultTestLoader.loadTestsFromName(base))
+
+
+def disabledynamics():
+ import lldb
+ ci = lldb.DBG.GetCommandInterpreter()
+ res = lldb.SBCommandReturnObject()
+ ci.HandleCommand("setting set target.prefer-dynamic-value no-dynamic-values", res, False)
+ if not res.Succeeded():
+ raise Exception('disabling dynamic type support failed')
+
+def lldbLoggings():
+ import lldb
+ """Check and do lldb loggings if necessary."""
+
+ # Turn on logging for debugging purposes if ${LLDB_LOG} environment variable is
+ # defined. Use ${LLDB_LOG} to specify the log file.
+ ci = lldb.DBG.GetCommandInterpreter()
+ res = lldb.SBCommandReturnObject()
+ if ("LLDB_LOG" in os.environ):
+ open(os.environ["LLDB_LOG"], 'w').close()
+ if ("LLDB_LOG_OPTION" in os.environ):
+ lldb_log_option = os.environ["LLDB_LOG_OPTION"]
+ else:
+ lldb_log_option = "event process expr state api"
+ ci.HandleCommand(
+ "log enable -n -f " + os.environ["LLDB_LOG"] + " lldb " + lldb_log_option,
+ res)
+ if not res.Succeeded():
+ raise Exception('log enable failed (check LLDB_LOG env variable)')
+
+ if ("LLDB_LINUX_LOG" in os.environ):
+ open(os.environ["LLDB_LINUX_LOG"], 'w').close()
+ if ("LLDB_LINUX_LOG_OPTION" in os.environ):
+ lldb_log_option = os.environ["LLDB_LINUX_LOG_OPTION"]
+ else:
+ lldb_log_option = "event process expr state api"
+ ci.HandleCommand(
+ "log enable -n -f " + os.environ["LLDB_LINUX_LOG"] + " linux " + lldb_log_option,
+ res)
+ if not res.Succeeded():
+ raise Exception('log enable failed (check LLDB_LINUX_LOG env variable)')
+
+ # Ditto for gdb-remote logging if ${GDB_REMOTE_LOG} environment variable is defined.
+ # Use ${GDB_REMOTE_LOG} to specify the log file.
+ if ("GDB_REMOTE_LOG" in os.environ):
+ if ("GDB_REMOTE_LOG_OPTION" in os.environ):
+ gdb_remote_log_option = os.environ["GDB_REMOTE_LOG_OPTION"]
+ else:
+ gdb_remote_log_option = "packets process"
+ ci.HandleCommand(
+ "log enable -n -f " + os.environ["GDB_REMOTE_LOG"] + " gdb-remote "
+ + gdb_remote_log_option,
+ res)
+ if not res.Succeeded():
+ raise Exception('log enable failed (check GDB_REMOTE_LOG env variable)')
+
+def getMyCommandLine():
+ return ' '.join(sys.argv)
+
+# ======================================== #
+# #
+# Execution of the test driver starts here #
+# #
+# ======================================== #
+
+def checkDsymForUUIDIsNotOn():
+ cmd = ["defaults", "read", "com.apple.DebugSymbols"]
+ pipe = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
+ cmd_output = pipe.stdout.read()
+ if cmd_output and "DBGFileMappedPaths = " in cmd_output:
+ print("%s =>" % ' '.join(cmd))
+ print(cmd_output)
+ print("Disable automatic lookup and caching of dSYMs before running the test suite!")
+ print("Exiting...")
+ sys.exit(0)
+
+def exitTestSuite(exitCode = None):
+ import lldb
+ lldb.SBDebugger.Terminate()
+ if exitCode:
+ sys.exit(exitCode)
+
+
+def isMultiprocessTestRunner():
+ # We're not multiprocess when we're either explicitly
+ # the inferior (as specified by the multiprocess test
+ # runner) OR we've been told to skip using the multiprocess
+ # test runner
+ return not (configuration.is_inferior_test_runner or configuration.no_multiprocess_test_runner)
+
+def getVersionForSDK(sdk):
+ sdk = str.lower(sdk)
+ full_path = seven.get_command_output('xcrun -sdk %s --show-sdk-path' % sdk)
+ basename = os.path.basename(full_path)
+ basename = os.path.splitext(basename)[0]
+ basename = str.lower(basename)
+ ver = basename.replace(sdk, '')
+ return ver
+
+def getPathForSDK(sdk):
+ sdk = str.lower(sdk)
+ full_path = seven.get_command_output('xcrun -sdk %s --show-sdk-path' % sdk)
+ if os.path.exists(full_path): return full_path
+ return None
+
+def setDefaultTripleForPlatform():
+ if configuration.lldb_platform_name == 'ios-simulator':
+ triple_str = 'x86_64-apple-ios%s' % (getVersionForSDK('iphonesimulator'))
+ os.environ['TRIPLE'] = triple_str
+ return {'TRIPLE':triple_str}
+ return {}
+
+def run_suite():
+ # On MacOS X, check to make sure that domain for com.apple.DebugSymbols defaults
+ # does not exist before proceeding to running the test suite.
+ if sys.platform.startswith("darwin"):
+ checkDsymForUUIDIsNotOn()
+
+ #
+ # Start the actions by first parsing the options while setting up the test
+ # directories, followed by setting up the search paths for lldb utilities;
+ # then, we walk the directory trees and collect the tests into our test suite.
+ #
+ parseOptionsAndInitTestdirs()
+
+ # Setup test results (test results formatter and output handling).
+ setupTestResults()
+
+ # If we are running as the multiprocess test runner, kick off the
+ # multiprocess test runner here.
+ if isMultiprocessTestRunner():
+ from . import dosep
+ dosep.main(configuration.num_threads, configuration.multiprocess_test_subdir,
+ configuration.test_runner_name, configuration.results_formatter_object)
+ raise Exception("should never get here")
+ elif configuration.is_inferior_test_runner:
+ # Shut off Ctrl-C processing in inferiors. The parallel
+ # test runner handles this more holistically.
+ signal.signal(signal.SIGINT, signal.SIG_IGN)
+
+ setupSysPath()
+ configuration.setupCrashInfoHook()
+
+ #
+ # If '-l' is specified, do not skip the long running tests.
+ if not configuration.skip_long_running_test:
+ os.environ["LLDB_SKIP_LONG_RUNNING_TEST"] = "NO"
+
+ # For the time being, let's bracket the test runner within the
+ # lldb.SBDebugger.Initialize()/Terminate() pair.
+ import lldb
+
+ # Create a singleton SBDebugger in the lldb namespace.
+ lldb.DBG = lldb.SBDebugger.Create()
+
+ if configuration.lldb_platform_name:
+ print("Setting up remote platform '%s'" % (configuration.lldb_platform_name))
+ lldb.remote_platform = lldb.SBPlatform(configuration.lldb_platform_name)
+ if not lldb.remote_platform.IsValid():
+ print("error: unable to create the LLDB platform named '%s'." % (configuration.lldb_platform_name))
+ exitTestSuite(1)
+ if configuration.lldb_platform_url:
+ # We must connect to a remote platform if a LLDB platform URL was specified
+ print("Connecting to remote platform '%s' at '%s'..." % (configuration.lldb_platform_name, configuration.lldb_platform_url))
+ platform_connect_options = lldb.SBPlatformConnectOptions(configuration.lldb_platform_url)
+ err = lldb.remote_platform.ConnectRemote(platform_connect_options)
+ if err.Success():
+ print("Connected.")
+ else:
+ print("error: failed to connect to remote platform using URL '%s': %s" % (configuration.lldb_platform_url, err))
+ exitTestSuite(1)
+ else:
+ configuration.lldb_platform_url = None
+
+ platform_changes = setDefaultTripleForPlatform()
+ first = True
+ for key in platform_changes:
+ if first:
+ print("Environment variables setup for platform support:")
+ first = False
+ print("%s = %s" % (key,platform_changes[key]))
+
+ if configuration.lldb_platform_working_dir:
+ print("Setting remote platform working directory to '%s'..." % (configuration.lldb_platform_working_dir))
+ lldb.remote_platform.SetWorkingDirectory(configuration.lldb_platform_working_dir)
+ lldb.DBG.SetSelectedPlatform(lldb.remote_platform)
+ else:
+ lldb.remote_platform = None
+ configuration.lldb_platform_working_dir = None
+ configuration.lldb_platform_url = None
+
+ target_platform = lldb.DBG.GetSelectedPlatform().GetTriple().split('-')[2]
+
+ # Don't do debugserver tests on everything except OS X.
+ configuration.dont_do_debugserver_test = "linux" in target_platform or "freebsd" in target_platform or "windows" in target_platform
+
+ # Don't do lldb-server (llgs) tests on anything except Linux.
+ configuration.dont_do_llgs_test = not ("linux" in target_platform)
+
+ #
+ # Walk through the testdirs while collecting tests.
+ #
+ for testdir in configuration.testdirs:
+ for (dirpath, dirnames, filenames) in os.walk(testdir):
+ visit('Test', dirpath, filenames)
+
+ #
+ # Now that we have loaded all the test cases, run the whole test suite.
+ #
+
+ # Turn on lldb loggings if necessary.
+ lldbLoggings()
+
+ # Disable default dynamic types for testing purposes
+ disabledynamics()
+
+ # Install the control-c handler.
+ unittest2.signals.installHandler()
+
+ # If sdir_name is not specified through the '-s sdir_name' option, get a
+ # timestamp string and export it as LLDB_SESSION_DIR environment var. This will
+ # be used when/if we want to dump the session info of individual test cases
+ # later on.
+ #
+ # See also TestBase.dumpSessionInfo() in lldbtest.py.
+ import datetime
+ # The windows platforms don't like ':' in the pathname.
+ timestamp_started = datetime.datetime.now().strftime("%Y-%m-%d-%H_%M_%S")
+ if not configuration.sdir_name:
+ configuration.sdir_name = timestamp_started
+ os.environ["LLDB_SESSION_DIRNAME"] = os.path.join(os.getcwd(), configuration.sdir_name)
+
+ sys.stderr.write("\nSession logs for test failures/errors/unexpected successes"
+ " will go into directory '%s'\n" % configuration.sdir_name)
+ sys.stderr.write("Command invoked: %s\n" % getMyCommandLine())
+
+ if not os.path.isdir(configuration.sdir_name):
+ try:
+ os.mkdir(configuration.sdir_name)
+ except OSError as exception:
+ if exception.errno != errno.EEXIST:
+ raise
+ where_to_save_session = os.getcwd()
+ fname = os.path.join(configuration.sdir_name, "TestStarted-%d" % os.getpid())
+ with open(fname, "w") as f:
+ print("Test started at: %s\n" % timestamp_started, file=f)
+ print(configuration.svn_info, file=f)
+ print("Command invoked: %s\n" % getMyCommandLine(), file=f)
+
+ #
+ # Invoke the default TextTestRunner to run the test suite, possibly iterating
+ # over different configurations.
+ #
+
+ iterArchs = False
+ iterCompilers = False
+
+ if isinstance(configuration.archs, list) and len(configuration.archs) >= 1:
+ iterArchs = True
+
+ #
+ # Add some intervention here to sanity check that the compilers requested are sane.
+ # If found not to be an executable program, the invalid one is dropped from the list.
+ for i in range(len(configuration.compilers)):
+ c = configuration.compilers[i]
+ if which(c):
+ continue
+ else:
+ if sys.platform.startswith("darwin"):
+ pipe = subprocess.Popen(['xcrun', '-find', c], stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
+ cmd_output = pipe.stdout.read()
+ if cmd_output:
+ if "not found" in cmd_output:
+ print("dropping %s from the compilers used" % c)
+ configuration.compilers.remove(i)
+ else:
+ configuration.compilers[i] = cmd_output.split('\n')[0]
+ print("'xcrun -find %s' returning %s" % (c, configuration.compilers[i]))
+
+ if not configuration.parsable:
+ print("compilers=%s" % str(configuration.compilers))
+
+ if not configuration.compilers or len(configuration.compilers) == 0:
+ print("No eligible compiler found, exiting.")
+ exitTestSuite(1)
+
+ if isinstance(configuration.compilers, list) and len(configuration.compilers) >= 1:
+ iterCompilers = True
+
+ # If we iterate on archs or compilers, there is a chance we want to split stderr/stdout.
+ if iterArchs or iterCompilers:
+ old_stderr = sys.stderr
+ old_stdout = sys.stdout
+ new_stderr = None
+ new_stdout = None
+
+ # Iterating over all possible architecture and compiler combinations.
+ for ia in range(len(configuration.archs) if iterArchs else 1):
+ archConfig = ""
+ if iterArchs:
+ os.environ["ARCH"] = configuration.archs[ia]
+ archConfig = "arch=%s" % configuration.archs[ia]
+ for ic in range(len(configuration.compilers) if iterCompilers else 1):
+ if iterCompilers:
+ os.environ["CC"] = configuration.compilers[ic]
+ configString = "%s compiler=%s" % (archConfig, configuration.compilers[ic])
+ else:
+ configString = archConfig
+
+ if iterArchs or iterCompilers:
+ # Translate ' ' to '-' for pathname component.
+ if six.PY2:
+ import string
+ tbl = string.maketrans(' ', '-')
+ else:
+ tbl = str.maketrans(' ', '-')
+ configPostfix = configString.translate(tbl)
+
+ # Output the configuration.
+ if not configuration.parsable:
+ sys.stderr.write("\nConfiguration: " + configString + "\n")
+
+ #print("sys.stderr name is", sys.stderr.name)
+ #print("sys.stdout name is", sys.stdout.name)
+
+ # First, write out the number of collected test cases.
+ if not configuration.parsable:
+ sys.stderr.write(configuration.separator + "\n")
+ sys.stderr.write("Collected %d test%s\n\n"
+ % (configuration.suite.countTestCases(),
+ configuration.suite.countTestCases() != 1 and "s" or ""))
+
+ if configuration.parsable:
+ v = 0
+ else:
+ v = configuration.verbose
+
+ # Invoke the test runner.
+ if configuration.count == 1:
+ result = unittest2.TextTestRunner(stream=sys.stderr,
+ verbosity=v,
+ resultclass=test_result.LLDBTestResult).run(configuration.suite)
+ else:
+ # We are invoking the same test suite more than once. In this case,
+ # mark __ignore_singleton__ flag as True so the signleton pattern is
+ # not enforced.
+ test_result.LLDBTestResult.__ignore_singleton__ = True
+ for i in range(count):
+
+ result = unittest2.TextTestRunner(stream=sys.stderr,
+ verbosity=v,
+ resultclass=test_result.LLDBTestResult).run(configuration.suite)
+
+ configuration.failed = configuration.failed or not result.wasSuccessful()
+
+ if configuration.sdir_has_content and not configuration.parsable:
+ sys.stderr.write("Session logs for test failures/errors/unexpected successes"
+ " can be found in directory '%s'\n" % configuration.sdir_name)
+
+ if configuration.useCategories and len(configuration.failuresPerCategory) > 0:
+ sys.stderr.write("Failures per category:\n")
+ for category in configuration.failuresPerCategory:
+ sys.stderr.write("%s - %d\n" % (category, configuration.failuresPerCategory[category]))
+
+ os.chdir(where_to_save_session)
+ fname = os.path.join(configuration.sdir_name, "TestFinished-%d" % os.getpid())
+ with open(fname, "w") as f:
+ print("Test finished at: %s\n" % datetime.datetime.now().strftime("%Y-%m-%d-%H_%M_%S"), file=f)
+
+ # Terminate the test suite if ${LLDB_TESTSUITE_FORCE_FINISH} is defined.
+ # This should not be necessary now.
+ if ("LLDB_TESTSUITE_FORCE_FINISH" in os.environ):
+ print("Terminating Test suite...")
+ subprocess.Popen(["/bin/sh", "-c", "kill %s; exit 0" % (os.getpid())])
+
+ # Exiting.
+ exitTestSuite(configuration.failed)
+
+if __name__ == "__main__":
+ print(__file__ + " is for use as a module only. It should not be run as a standalone script.")
+ sys.exit(-1)
diff --git a/packages/Python/lldbsuite/test/dotest_args.py b/packages/Python/lldbsuite/test/dotest_args.py
new file mode 100644
index 000000000000..105156df7e84
--- /dev/null
+++ b/packages/Python/lldbsuite/test/dotest_args.py
@@ -0,0 +1,188 @@
+from __future__ import print_function
+from __future__ import absolute_import
+
+# System modules
+import argparse
+import sys
+import multiprocessing
+import os
+import textwrap
+
+# Third-party modules
+
+# LLDB modules
+
+class ArgParseNamespace(object):
+ pass
+
+def parse_args(parser, argv):
+ """ Returns an argument object. LLDB_TEST_ARGUMENTS environment variable can
+ be used to pass additional arguments.
+ """
+ args = ArgParseNamespace()
+
+ if ('LLDB_TEST_ARGUMENTS' in os.environ):
+ print("Arguments passed through environment: '%s'" % os.environ['LLDB_TEST_ARGUMENTS'])
+ args = parser.parse_args([sys.argv[0]].__add__(os.environ['LLDB_TEST_ARGUMENTS'].split()),namespace=args)
+
+ return parser.parse_args(args=argv, namespace=args)
+
+
+def default_thread_count():
+ # Check if specified in the environment
+ num_threads_str = os.environ.get("LLDB_TEST_THREADS")
+ if num_threads_str:
+ return int(num_threads_str)
+ else:
+ return multiprocessing.cpu_count()
+
+
+def create_parser():
+ parser = argparse.ArgumentParser(description='description', prefix_chars='+-', add_help=False)
+ group = None
+
+ # Helper function for boolean options (group will point to the current group when executing X)
+ X = lambda optstr, helpstr, **kwargs: group.add_argument(optstr, help=helpstr, action='store_true', **kwargs)
+
+ group = parser.add_argument_group('Help')
+ group.add_argument('-h', '--help', dest='h', action='store_true', help="Print this help message and exit. Add '-v' for more detailed help.")
+
+ # C and Python toolchain options
+ group = parser.add_argument_group('Toolchain options')
+ group.add_argument('-A', '--arch', metavar='arch', action='append', dest='archs', help=textwrap.dedent('''Specify the architecture(s) to test. This option can be specified more than once'''))
+ group.add_argument('-C', '--compiler', metavar='compiler', dest='compilers', action='append', help=textwrap.dedent('''Specify the compiler(s) used to build the inferior executables. The compiler path can be an executable basename or a full path to a compiler executable. This option can be specified multiple times.'''))
+ if sys.platform == 'darwin':
+ group.add_argument('--apple-sdk', metavar='apple_sdk', dest='apple_sdk', help=textwrap.dedent('''Specify the name of the Apple SDK (macosx, macosx.internal, iphoneos, iphoneos.internal, or path to SDK) and use the appropriate tools from that SDK's toolchain.'''))
+ # FIXME? This won't work for different extra flags according to each arch.
+ group.add_argument('-E', metavar='extra-flags', help=textwrap.dedent('''Specify the extra flags to be passed to the toolchain when building the inferior programs to be debugged
+ suggestions: do not lump the "-A arch1 -A arch2" together such that the -E option applies to only one of the architectures'''))
+
+ # Test filtering options
+ group = parser.add_argument_group('Test filtering options')
+ group.add_argument('-f', metavar='filterspec', action='append', help='Specify a filter, which consists of the test class name, a dot, followed by the test method, to only admit such test into the test suite') # FIXME: Example?
+ X('-l', "Don't skip long running tests")
+ group.add_argument('-p', metavar='pattern', help='Specify a regexp filename pattern for inclusion in the test suite')
+ group.add_argument('-G', '--category', metavar='category', action='append', dest='categoriesList', help=textwrap.dedent('''Specify categories of test cases of interest. Can be specified more than once.'''))
+ group.add_argument('--skip-category', metavar='category', action='append', dest='skipCategories', help=textwrap.dedent('''Specify categories of test cases to skip. Takes precedence over -G. Can be specified more than once.'''))
+
+ # Configuration options
+ group = parser.add_argument_group('Configuration options')
+ group.add_argument('--framework', metavar='framework-path', help='The path to LLDB.framework')
+ group.add_argument('--executable', metavar='executable-path', help='The path to the lldb executable')
+ group.add_argument('-s', metavar='name', help='Specify the name of the dir created to store the session files of tests with errored or failed status. If not specified, the test driver uses the timestamp as the session dir name')
+ group.add_argument('-y', type=int, metavar='count', help="Specify the iteration count used to collect our benchmarks. An example is the number of times to do 'thread step-over' to measure stepping speed.")
+ group.add_argument('-#', type=int, metavar='sharp', dest='sharp', help='Repeat the test suite for a specified number of times')
+ group.add_argument('--channel', metavar='channel', dest='channels', action='append', help=textwrap.dedent("Specify the log channels (and optional categories) e.g. 'lldb all' or 'gdb-remote packets' if no categories are specified, 'default' is used"))
+ group.add_argument('--log-success', dest='log_success', action='store_true', help="Leave logs/traces even for successful test runs (useful for creating reference log files during debugging.)")
+
+ # Configuration options
+ group = parser.add_argument_group('Remote platform options')
+ group.add_argument('--platform-name', dest='lldb_platform_name', metavar='platform-name', help='The name of a remote platform to use')
+ group.add_argument('--platform-url', dest='lldb_platform_url', metavar='platform-url', help='A LLDB platform URL to use when connecting to a remote platform to run the test suite')
+ group.add_argument('--platform-working-dir', dest='lldb_platform_working_dir', metavar='platform-working-dir', help='The directory to use on the remote platform.')
+
+ # Test-suite behaviour
+ group = parser.add_argument_group('Runtime behaviour options')
+ X('-d', 'Suspend the process after launch to wait indefinitely for a debugger to attach')
+ X('-q', "Don't print extra output from this script.")
+ X('-t', 'Turn on tracing of lldb command and other detailed test executions')
+ group.add_argument('-u', dest='unset_env_varnames', metavar='variable', action='append', help='Specify an environment variable to unset before running the test cases. e.g., -u DYLD_INSERT_LIBRARIES -u MallocScribble')
+ group.add_argument('--env', dest='set_env_vars', metavar='variable', action='append', help='Specify an environment variable to set to the given value before running the test cases e.g.: --env CXXFLAGS=-O3 --env DYLD_INSERT_LIBRARIES')
+ X('-v', 'Do verbose mode of unittest framework (print out each test case invocation)')
+ group.add_argument('--enable-crash-dialog', dest='disable_crash_dialog', action='store_false', help='(Windows only) When LLDB crashes, display the Windows crash dialog.')
+ group.set_defaults(disable_crash_dialog=True)
+
+ group = parser.add_argument_group('Parallel execution options')
+ group.add_argument(
+ '--inferior',
+ action='store_true',
+ help=('specify this invocation is a multiprocess inferior, '
+ 'used internally'))
+ group.add_argument(
+ '--no-multiprocess',
+ action='store_true',
+ help='skip running the multiprocess test runner')
+ group.add_argument(
+ '--threads',
+ type=int,
+ dest='num_threads',
+ default=default_thread_count(),
+ help=('The number of threads/processes to use when running tests '
+ 'separately, defaults to the number of CPU cores available'))
+ group.add_argument(
+ '--test-subdir',
+ action='store',
+ help='Specify a test subdirectory to use relative to the test root dir'
+ )
+ group.add_argument(
+ '--test-runner-name',
+ action='store',
+ help=('Specify a test runner strategy. Valid values: multiprocessing,'
+ ' multiprocessing-pool, serial, threading, threading-pool')
+ )
+
+ # Test results support.
+ group = parser.add_argument_group('Test results options')
+ group.add_argument(
+ '--curses',
+ action='store_true',
+ help='Shortcut for specifying test results using the curses formatter')
+ group.add_argument(
+ '--results-file',
+ action='store',
+ help=('Specifies the file where test results will be written '
+ 'according to the results-formatter class used'))
+ group.add_argument(
+ '--results-port',
+ action='store',
+ type=int,
+ help=('Specifies the localhost port to which the results '
+ 'formatted output should be sent'))
+ group.add_argument(
+ '--results-formatter',
+ action='store',
+ help=('Specifies the full package/module/class name used to translate '
+ 'test events into some kind of meaningful report, written to '
+ 'the designated output results file-like object'))
+ group.add_argument(
+ '--results-formatter-option',
+ '-O',
+ action='append',
+ dest='results_formatter_options',
+ help=('Specify an option to pass to the formatter. '
+ 'Use --results-formatter-option="--option1=val1" '
+ 'syntax. Note the "=" is critical, don\'t include whitespace.'))
+ group.add_argument(
+ '--event-add-entries',
+ action='store',
+ help=('Specify comma-separated KEY=VAL entries to add key and value '
+ 'pairs to all test events generated by this test run. VAL may '
+ 'be specified as VAL:TYPE, where TYPE may be int to convert '
+ 'the value to an int'))
+
+ # Re-run related arguments
+ group = parser.add_argument_group('Test Re-run Options')
+ group.add_argument(
+ '--rerun-all-issues',
+ action='store_true',
+ help=('Re-run all issues that occurred during the test run '
+ 'irrespective of the test method\'s marking as flakey. '
+ 'Default behavior is to apply re-runs only to flakey '
+ 'tests that generate issues.'))
+ group.add_argument(
+ '--rerun-max-file-threshold',
+ action='store',
+ type=int,
+ default=50,
+ help=('Maximum number of files requiring a rerun beyond '
+ 'which the rerun will not occur. This is meant to '
+ 'stop a catastrophically failing test suite from forcing '
+ 'all tests to be rerun in the single-worker phase.'))
+
+ # Remove the reference to our helper function
+ del X
+
+ group = parser.add_argument_group('Test directories')
+ group.add_argument('args', metavar='test-dir', nargs='*', help='Specify a list of directory names to search for test modules named after Test*.py (test discovery). If empty, search from the current working directory instead.')
+
+ return parser
diff --git a/packages/Python/lldbsuite/test/dotest_channels.py b/packages/Python/lldbsuite/test/dotest_channels.py
new file mode 100644
index 000000000000..d2faf10c8929
--- /dev/null
+++ b/packages/Python/lldbsuite/test/dotest_channels.py
@@ -0,0 +1,200 @@
+"""
+ The LLVM Compiler Infrastructure
+
+This file is distributed under the University of Illinois Open Source
+License. See LICENSE.TXT for details.
+
+Sync lldb and related source from a local machine to a remote machine.
+
+This facilitates working on the lldb sourcecode on multiple machines
+and multiple OS types, verifying changes across all.
+
+
+This module provides asyncore channels used within the LLDB test
+framework.
+"""
+
+from __future__ import print_function
+from __future__ import absolute_import
+
+
+# System modules
+import asyncore
+import socket
+
+# Third-party modules
+from six.moves import cPickle
+
+# LLDB modules
+
+
+class UnpicklingForwardingReaderChannel(asyncore.dispatcher):
+ """Provides an unpickling, forwarding asyncore dispatch channel reader.
+
+ Inferior dotest.py processes with side-channel-based test results will
+ send test result event data in a pickled format, one event at a time.
+ This class supports reconstructing the pickled data and forwarding it
+ on to its final destination.
+
+ The channel data is written in the form:
+ {num_payload_bytes}#{payload_bytes}
+
+ The bulk of this class is devoted to reading and parsing out
+ the payload bytes.
+ """
+ def __init__(self, file_object, async_map, forwarding_func):
+ asyncore.dispatcher.__init__(self, sock=file_object, map=async_map)
+
+ self.header_contents = b""
+ self.packet_bytes_remaining = 0
+ self.reading_header = True
+ self.ibuffer = b''
+ self.forwarding_func = forwarding_func
+ if forwarding_func is None:
+ # This whole class is useless if we do nothing with the
+ # unpickled results.
+ raise Exception("forwarding function must be set")
+
+ def deserialize_payload(self):
+ """Unpickles the collected input buffer bytes and forwards."""
+ if len(self.ibuffer) > 0:
+ self.forwarding_func(cPickle.loads(self.ibuffer))
+ self.ibuffer = b''
+
+ def consume_header_bytes(self, data):
+ """Consumes header bytes from the front of data.
+ @param data the incoming data stream bytes
+ @return any data leftover after consuming header bytes.
+ """
+ # We're done if there is no content.
+ if not data or (len(data) == 0):
+ return None
+
+ full_header_len = 4
+
+ assert len(self.header_contents) < full_header_len
+
+ bytes_avail = len(data)
+ bytes_needed = full_header_len - len(self.header_contents)
+ header_bytes_avail = min(bytes_needed, bytes_avail)
+ self.header_contents += data[:header_bytes_avail]
+ if len(self.header_contents) == full_header_len:
+ import struct
+ # End of header.
+ self.packet_bytes_remaining = struct.unpack(
+ "!I", self.header_contents)[0]
+ self.header_contents = b""
+ self.reading_header = False
+ return data[header_bytes_avail:]
+
+ # If we made it here, we've exhausted the data and
+ # we're still parsing header content.
+ return None
+
+ def consume_payload_bytes(self, data):
+ """Consumes payload bytes from the front of data.
+ @param data the incoming data stream bytes
+ @return any data leftover after consuming remaining payload bytes.
+ """
+ if not data or (len(data) == 0):
+ # We're done and there's nothing to do.
+ return None
+
+ data_len = len(data)
+ if data_len <= self.packet_bytes_remaining:
+ # We're consuming all the data provided.
+ self.ibuffer += data
+ self.packet_bytes_remaining -= data_len
+
+ # If we're no longer waiting for payload bytes,
+ # we flip back to parsing header bytes and we
+ # unpickle the payload contents.
+ if self.packet_bytes_remaining < 1:
+ self.reading_header = True
+ self.deserialize_payload()
+
+ # We're done, no more data left.
+ return None
+ else:
+ # We're only consuming a portion of the data since
+ # the data contains more than the payload amount.
+ self.ibuffer += data[:self.packet_bytes_remaining]
+ data = data[self.packet_bytes_remaining:]
+
+ # We now move on to reading the header.
+ self.reading_header = True
+ self.packet_bytes_remaining = 0
+
+ # And we can deserialize the payload.
+ self.deserialize_payload()
+
+ # Return the remaining data.
+ return data
+
+ def handle_read(self):
+ # Read some data from the socket.
+ try:
+ data = self.recv(8192)
+ # print('driver socket READ: %d bytes' % len(data))
+ except socket.error as socket_error:
+ print(
+ "\nINFO: received socket error when reading data "
+ "from test inferior:\n{}".format(socket_error))
+ raise
+ except Exception as general_exception:
+ print(
+ "\nERROR: received non-socket error when reading data "
+ "from the test inferior:\n{}".format(general_exception))
+ raise
+
+ # Consume the message content.
+ while data and (len(data) > 0):
+ # If we're reading the header, gather header bytes.
+ if self.reading_header:
+ data = self.consume_header_bytes(data)
+ else:
+ data = self.consume_payload_bytes(data)
+
+ def handle_close(self):
+ # print("socket reader: closing port")
+ self.close()
+
+
+class UnpicklingForwardingListenerChannel(asyncore.dispatcher):
+ """Provides a socket listener asyncore channel for unpickling/forwarding.
+
+ This channel will listen on a socket port (use 0 for host-selected). Any
+ client that connects will have an UnpicklingForwardingReaderChannel handle
+ communication over the connection.
+
+ The dotest parallel test runners, when collecting test results, open the
+ test results side channel over a socket. This channel handles connections
+ from inferiors back to the test runner. Each worker fires up a listener
+ for each inferior invocation. This simplifies the asyncore.loop() usage,
+ one of the reasons for implementing with asyncore. This listener shuts
+ down once a single connection is made to it.
+ """
+ def __init__(self, async_map, host, port, backlog_count, forwarding_func):
+ asyncore.dispatcher.__init__(self, map=async_map)
+ self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+ self.set_reuse_addr()
+ self.bind((host, port))
+ self.address = self.socket.getsockname()
+ self.listen(backlog_count)
+ self.handler = None
+ self.async_map = async_map
+ self.forwarding_func = forwarding_func
+ if forwarding_func is None:
+ # This whole class is useless if we do nothing with the
+ # unpickled results.
+ raise Exception("forwarding function must be set")
+
+ def handle_accept(self):
+ (sock, addr) = self.socket.accept()
+ if sock and addr:
+ # print('Incoming connection from %s' % repr(addr))
+ self.handler = UnpicklingForwardingReaderChannel(
+ sock, self.async_map, self.forwarding_func)
+
+ def handle_close(self):
+ self.close()
diff --git a/packages/Python/lldbsuite/test/driver/batch_mode/Makefile b/packages/Python/lldbsuite/test/driver/batch_mode/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/driver/batch_mode/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/driver/batch_mode/TestBatchMode.py b/packages/Python/lldbsuite/test/driver/batch_mode/TestBatchMode.py
new file mode 100644
index 000000000000..b5ff88c3bba1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/driver/batch_mode/TestBatchMode.py
@@ -0,0 +1,89 @@
+"""
+Test that the lldb driver's batch mode works correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class DriverBatchModeTest (TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfRemote # test not remote-ready llvm.org/pr24813
+ @expectedFlakeyFreeBSD("llvm.org/pr25172 fails rarely on the buildbot")
+ @expectedFlakeyLinux("llvm.org/pr25172")
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ def test_driver_batch_mode(self):
+ """Test that the lldb driver's batch mode works correctly."""
+ self.build()
+ self.setTearDownCleanup()
+ self.batch_mode()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Our simple source filename.
+ self.source = 'main.c'
+
+ def expect_string (self, string):
+ import pexpect
+ """This expects for "string", with timeout & EOF being test fails."""
+ try:
+ self.child.expect_exact(string)
+ except pexpect.EOF:
+ self.fail ("Got EOF waiting for '%s'"%(string))
+ except pexpect.TIMEOUT:
+ self.fail ("Timed out waiting for '%s'"%(string))
+
+ def batch_mode (self):
+ import pexpect
+ exe = os.path.join(os.getcwd(), "a.out")
+ prompt = "(lldb) "
+
+ # First time through, pass CRASH so the process will crash and stop in batch mode.
+ run_commands = ' -b -o "break set -n main" -o "run" -o "continue" -k "frame var touch_me_not"'
+ self.child = pexpect.spawn('%s %s %s %s -- CRASH' % (lldbtest_config.lldbExec, self.lldbOption, run_commands, exe))
+ child = self.child
+ # Turn on logging for what the child sends back.
+ if self.TraceOn():
+ child.logfile_read = sys.stdout
+
+ # We should see the "run":
+ self.expect_string ("run")
+ # We should have hit the breakpoint & continued:
+ self.expect_string ("continue")
+ # The App should have crashed:
+ self.expect_string("About to crash")
+ # The -k option should have printed the frame variable once:
+ self.expect_string ('(char *) touch_me_not')
+ # Then we should have a live prompt:
+ self.expect_string (prompt)
+ self.child.sendline("frame variable touch_me_not")
+ self.expect_string ('(char *) touch_me_not')
+
+ self.deletePexpectChild()
+
+ # Now do it again, and see make sure if we don't crash, we quit:
+ run_commands = ' -b -o "break set -n main" -o "run" -o "continue" '
+ self.child = pexpect.spawn('%s %s %s %s -- NOCRASH' % (lldbtest_config.lldbExec, self.lldbOption, run_commands, exe))
+ child = self.child
+ # Turn on logging for what the child sends back.
+ if self.TraceOn():
+ child.logfile_read = sys.stdout
+
+ # We should see the "run":
+ self.expect_string ("run")
+ # We should have hit the breakpoint & continued:
+ self.expect_string ("continue")
+ # The App should have not have crashed:
+ self.expect_string("Got there on time and it did not crash.")
+ # Then we should have a live prompt:
+ self.expect_string ("exited")
+ index = self.child.expect([pexpect.EOF, pexpect.TIMEOUT])
+ self.assertTrue(index == 0, "lldb didn't close on successful batch completion.")
+
diff --git a/packages/Python/lldbsuite/test/driver/batch_mode/main.c b/packages/Python/lldbsuite/test/driver/batch_mode/main.c
new file mode 100644
index 000000000000..418160eaa36d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/driver/batch_mode/main.c
@@ -0,0 +1,15 @@
+#include <stdio.h>
+#include <string.h>
+
+int
+main (int argc, char **argv)
+{
+ if (argc >= 2 && strcmp (argv[1], "CRASH") == 0)
+ {
+ char *touch_me_not = (char *) 0;
+ printf ("About to crash.\n");
+ touch_me_not[0] = 'a';
+ }
+ printf ("Got there on time and it did not crash.\n");
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/example/TestSequenceFunctions.py b/packages/Python/lldbsuite/test/example/TestSequenceFunctions.py
new file mode 100644
index 000000000000..a08529300646
--- /dev/null
+++ b/packages/Python/lldbsuite/test/example/TestSequenceFunctions.py
@@ -0,0 +1,36 @@
+"""An example unittest copied from python tutorial."""
+
+import random
+import unittest
+import traceback
+
+class SequenceFunctionsTestCase(unittest.TestCase):
+
+ def setUp(self):
+ #traceback.print_stack()
+ self.seq = list(range(10))
+
+ def tearDown(self):
+ #traceback.print_stack()
+ pass
+
+ def test_shuffle(self):
+ # make sure the shuffled sequence does not lose any elements
+ random.shuffle(self.seq)
+ self.seq.sort()
+ self.assertEqual(self.seq, list(range(10)))
+
+ def test_choice(self):
+ element = random.choice(self.seq)
+ self.assertTrue(element in self.seq)
+
+ def test_sample(self):
+ self.assertRaises(ValueError, random.sample, self.seq, 20)
+ for element in random.sample(self.seq, 5):
+ self.assertTrue(element in self.seq)
+
+ def getCategories(self):
+ return []
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/packages/Python/lldbsuite/test/expression_command/.categories b/packages/Python/lldbsuite/test/expression_command/.categories
new file mode 100644
index 000000000000..897e40a99dda
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/.categories
@@ -0,0 +1 @@
+expression
diff --git a/packages/Python/lldbsuite/test/expression_command/call-function/Makefile b/packages/Python/lldbsuite/test/expression_command/call-function/Makefile
new file mode 100644
index 000000000000..d4b82b3db276
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/call-function/Makefile
@@ -0,0 +1,15 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+# clang-3.5+ outputs FullDebugInfo by default for Darwin/FreeBSD
+# targets. Other targets do not, which causes this test to fail.
+# This flag enables FullDebugInfo for all targets.
+ifneq (,$(findstring clang,$(CC)))
+ CFLAGS_EXTRAS += -fno-limit-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
+
+clean::
+ rm -rf $(wildcard *.o *.d *.dSYM)
diff --git a/packages/Python/lldbsuite/test/expression_command/call-function/TestCallStdStringFunction.py b/packages/Python/lldbsuite/test/expression_command/call-function/TestCallStdStringFunction.py
new file mode 100644
index 000000000000..3756b4a8cea4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/call-function/TestCallStdStringFunction.py
@@ -0,0 +1,43 @@
+"""
+Test calling std::String member functions.
+"""
+
+from __future__ import print_function
+
+
+
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ExprCommandCallFunctionTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break for main.c.
+ self.line = line_number('main.cpp',
+ '// Please test these expressions while stopped at this line:')
+
+ @expectedFailureIcc # llvm.org/pr14437, fails with ICC 13.1
+ @expectedFailureFreeBSD('llvm.org/pr17807') # Fails on FreeBSD buildbot
+ @expectedFailureWindows("llvm.org/pr21765")
+ def test_with(self):
+ """Test calling std::String member function."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ # Some versions of GCC encode two locations for the 'return' statement in main.cpp
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.expect("print str",
+ substrs = ['Hello world'])
+
+ # Calling this function now succeeds, but we follow the typedef return type through to
+ # const char *, and thus don't invoke the Summary formatter.
+ self.expect("print str.c_str()",
+ substrs = ['Hello world'])
diff --git a/packages/Python/lldbsuite/test/expression_command/call-function/TestCallStopAndContinue.py b/packages/Python/lldbsuite/test/expression_command/call-function/TestCallStopAndContinue.py
new file mode 100644
index 000000000000..f6d63885248a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/call-function/TestCallStopAndContinue.py
@@ -0,0 +1,46 @@
+"""
+Test calling a function, stopping in the call, continue and gather the result on stop.
+"""
+
+from __future__ import print_function
+
+
+
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ExprCommandCallStopContinueTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break for main.c.
+ self.line = line_number('main.cpp',
+ '// Please test these expressions while stopped at this line:')
+ self.func_line = line_number ('main.cpp',
+ '{ 5, "five" }')
+
+ @expectedFlakeyDarwin("llvm.org/pr20274")
+ @expectedFailureWindows("llvm.org/pr24489: Name lookup not working correctly on Windows")
+ def test(self):
+ """Test gathering result from interrupted function call."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ # Some versions of GCC encode two locations for the 'return' statement in main.cpp
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.func_line, num_expected_locations=-1, loc_exact=True)
+
+ self.expect("expr -i false -- returnsFive()", error=True,
+ substrs = ['Execution was interrupted, reason: breakpoint'])
+
+ self.runCmd("continue", "Continue completed")
+ self.expect ("thread list",
+ substrs = ['stop reason = User Expression thread plan',
+ r'Completed expression: (Five) $0 = (number = 5, name = "five")'])
diff --git a/packages/Python/lldbsuite/test/expression_command/call-function/TestCallUserDefinedFunction.py b/packages/Python/lldbsuite/test/expression_command/call-function/TestCallUserDefinedFunction.py
new file mode 100644
index 000000000000..9138af0b0b47
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/call-function/TestCallUserDefinedFunction.py
@@ -0,0 +1,52 @@
+"""
+Test calling user defined functions using expression evaluation.
+
+Note:
+ LLDBs current first choice of evaluating functions is using the IR interpreter,
+ which is only supported on Hexagon. Otherwise JIT is used for the evaluation.
+
+"""
+
+from __future__ import print_function
+
+
+
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ExprCommandCallUserDefinedFunction(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break for main.c.
+ self.line = line_number('main.cpp',
+ '// Please test these expressions while stopped at this line:')
+ @expectedFlakeyDsym("llvm.org/pr20274")
+ @expectedFailureWindows("llvm.org/pr24489: Name lookup not working correctly on Windows")
+ def test(self):
+ """Test return values of user defined function calls."""
+ self.build()
+
+ # Set breakpoint in main and run exe
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Test recursive function call.
+ self.expect("expr fib(5)", substrs = ['$0 = 5'])
+
+ # Test function with more than one paramter
+ self.expect("expr add(4,8)", substrs = ['$1 = 12'])
+
+ # Test nesting function calls in function paramters
+ self.expect("expr add(add(5,2),add(3,4))", substrs = ['$2 = 14'])
+ self.expect("expr add(add(5,2),fib(5))", substrs = ['$3 = 12'])
+
+ # Test function with pointer paramter
+ self.expect("exp stringCompare((const char*) \"Hello world\")", substrs = ['$4 = true'])
+ self.expect("exp stringCompare((const char*) \"Hellworld\")", substrs = ['$5 = false'])
diff --git a/packages/Python/lldbsuite/test/expression_command/call-function/main.cpp b/packages/Python/lldbsuite/test/expression_command/call-function/main.cpp
new file mode 100644
index 000000000000..9b494c712bcc
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/call-function/main.cpp
@@ -0,0 +1,53 @@
+#include <iostream>
+#include <string>
+#include <cstring>
+
+struct Five
+{
+ int number;
+ const char *name;
+};
+
+Five
+returnsFive()
+{
+ Five my_five = { 5, "five" };
+ return my_five;
+}
+
+unsigned int
+fib(unsigned int n)
+{
+ if (n < 2)
+ return n;
+ else
+ return fib(n - 1) + fib(n - 2);
+}
+
+int
+add(int a, int b)
+{
+ return a + b;
+}
+
+bool
+stringCompare(const char *str)
+{
+ if (strcmp( str, "Hello world" ) == 0)
+ return true;
+ else
+ return false;
+}
+
+int main (int argc, char const *argv[])
+{
+ std::string str = "Hello world";
+ std::cout << str << std::endl;
+ std::cout << str.c_str() << std::endl;
+ Five main_five = returnsFive();
+#if 0
+ print str
+ print str.c_str()
+#endif
+ return 0; // Please test these expressions while stopped at this line:
+}
diff --git a/packages/Python/lldbsuite/test/expression_command/call-restarts/Makefile b/packages/Python/lldbsuite/test/expression_command/call-restarts/Makefile
new file mode 100644
index 000000000000..1c93ae1de439
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/call-restarts/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := lotta-signals.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/expression_command/call-restarts/TestCallThatRestarts.py b/packages/Python/lldbsuite/test/expression_command/call-restarts/TestCallThatRestarts.py
new file mode 100644
index 000000000000..abf48742567d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/call-restarts/TestCallThatRestarts.py
@@ -0,0 +1,139 @@
+"""
+Test calling a function that hits a signal set to auto-restart, make sure the call completes.
+"""
+
+from __future__ import print_function
+
+
+
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ExprCommandThatRestartsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+
+ self.main_source = "lotta-signals.c"
+ self.main_source_spec = lldb.SBFileSpec (self.main_source)
+
+ @skipIfFreeBSD # llvm.org/pr19246: intermittent failure
+ @skipIfDarwin # llvm.org/pr19246: intermittent failure
+ @skipIfWindows # Test relies on signals, unsupported on Windows
+ def test(self):
+ """Test calling function that hits a signal and restarts."""
+ self.build()
+ self.call_function()
+
+ def check_after_call (self, num_sigchld):
+ after_call = self.sigchld_no.GetValueAsSigned(-1)
+ self.assertTrue (after_call - self.start_sigchld_no == num_sigchld, "Really got %d SIGCHLD signals through the call."%(num_sigchld))
+ self.start_sigchld_no = after_call
+
+ # Check that we are back where we were before:
+ frame = self.thread.GetFrameAtIndex(0)
+ self.assertTrue (self.orig_frame_pc == frame.GetPC(), "Restored the zeroth frame correctly")
+
+ def call_function(self):
+ exe_name = "a.out"
+ exe = os.path.join(os.getcwd(), exe_name)
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+ empty = lldb.SBFileSpec()
+ breakpoint = target.BreakpointCreateBySourceRegex('Stop here in main.',self.main_source_spec)
+ self.assertTrue(breakpoint.GetNumLocations() > 0, VALID_BREAKPOINT)
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Frame #0 should be at our breakpoint.
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint)
+
+ self.assertTrue(len(threads) == 1)
+ self.thread = threads[0]
+
+ # Make sure the SIGCHLD behavior is pass/no-stop/no-notify:
+ return_obj = lldb.SBCommandReturnObject()
+ self.dbg.GetCommandInterpreter().HandleCommand("process handle SIGCHLD -s 0 -p 1 -n 0", return_obj)
+ self.assertTrue (return_obj.Succeeded() == True, "Set SIGCHLD to pass, no-stop")
+
+ # The sigchld_no variable should be 0 at this point.
+ self.sigchld_no = target.FindFirstGlobalVariable("sigchld_no")
+ self.assertTrue (self.sigchld_no.IsValid(), "Got a value for sigchld_no")
+
+ self.start_sigchld_no = self.sigchld_no.GetValueAsSigned (-1)
+ self.assertTrue (self.start_sigchld_no != -1, "Got an actual value for sigchld_no")
+
+ options = lldb.SBExpressionOptions()
+ # processing 30 signals takes a while, increase the expression timeout a bit
+ options.SetTimeoutInMicroSeconds(3000000) # 3s
+ options.SetUnwindOnError(True)
+
+ frame = self.thread.GetFrameAtIndex(0)
+ # Store away the PC to check that the functions unwind to the right place after calls
+ self.orig_frame_pc = frame.GetPC()
+
+ num_sigchld = 30
+ value = frame.EvaluateExpression ("call_me (%d)"%(num_sigchld), options)
+ self.assertTrue (value.IsValid())
+ self.assertTrue (value.GetError().Success() == True)
+ self.assertTrue (value.GetValueAsSigned(-1) == num_sigchld)
+
+ self.check_after_call(num_sigchld)
+
+ # Okay, now try with a breakpoint in the called code in the case where
+ # we are ignoring breakpoint hits.
+ handler_bkpt = target.BreakpointCreateBySourceRegex("Got sigchld %d.", self.main_source_spec)
+ self.assertTrue (handler_bkpt.GetNumLocations() > 0)
+ options.SetIgnoreBreakpoints(True)
+ options.SetUnwindOnError(True)
+
+ value = frame.EvaluateExpression("call_me (%d)"%(num_sigchld), options)
+
+ self.assertTrue (value.IsValid() and value.GetError().Success() == True)
+ self.assertTrue (value.GetValueAsSigned(-1) == num_sigchld)
+ self.check_after_call(num_sigchld)
+
+ # Now set the signal to print but not stop and make sure that calling still works:
+ self.dbg.GetCommandInterpreter().HandleCommand("process handle SIGCHLD -s 0 -p 1 -n 1", return_obj)
+ self.assertTrue (return_obj.Succeeded() == True, "Set SIGCHLD to pass, no-stop, notify")
+
+ value = frame.EvaluateExpression("call_me (%d)"%(num_sigchld), options)
+
+ self.assertTrue (value.IsValid() and value.GetError().Success() == True)
+ self.assertTrue (value.GetValueAsSigned(-1) == num_sigchld)
+ self.check_after_call(num_sigchld)
+
+ # Now set this unwind on error to false, and make sure that we still complete the call:
+ options.SetUnwindOnError(False)
+ value = frame.EvaluateExpression("call_me (%d)"%(num_sigchld), options)
+
+ self.assertTrue (value.IsValid() and value.GetError().Success() == True)
+ self.assertTrue (value.GetValueAsSigned(-1) == num_sigchld)
+ self.check_after_call(num_sigchld)
+
+ # Okay, now set UnwindOnError to true, and then make the signal behavior to stop
+ # and see that now we do stop at the signal point:
+
+ self.dbg.GetCommandInterpreter().HandleCommand("process handle SIGCHLD -s 1 -p 1 -n 1", return_obj)
+ self.assertTrue (return_obj.Succeeded() == True, "Set SIGCHLD to pass, stop, notify")
+
+ value = frame.EvaluateExpression("call_me (%d)"%(num_sigchld), options)
+ self.assertTrue (value.IsValid() and value.GetError().Success() == False)
+
+ # Set signal handling back to no-stop, and continue and we should end up back in out starting frame:
+ self.dbg.GetCommandInterpreter().HandleCommand("process handle SIGCHLD -s 0 -p 1 -n 1", return_obj)
+ self.assertTrue (return_obj.Succeeded() == True, "Set SIGCHLD to pass, no-stop, notify")
+
+ error = process.Continue()
+ self.assertTrue (error.Success(), "Continuing after stopping for signal succeeds.")
+
+ frame = self.thread.GetFrameAtIndex(0)
+ self.assertTrue (frame.GetPC() == self.orig_frame_pc, "Continuing returned to the place we started.")
diff --git a/packages/Python/lldbsuite/test/expression_command/call-restarts/lotta-signals.c b/packages/Python/lldbsuite/test/expression_command/call-restarts/lotta-signals.c
new file mode 100644
index 000000000000..f5c15b41e2de
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/call-restarts/lotta-signals.c
@@ -0,0 +1,61 @@
+#include <unistd.h>
+#include <stdio.h>
+#include <signal.h>
+
+static int sigchld_no;
+static int nosig_no;
+static int weird_value;
+
+void
+sigchld_handler (int signo)
+{
+ sigchld_no++;
+ printf ("Got sigchld %d.\n", sigchld_no);
+}
+
+int
+call_me (int some_value)
+{
+ int ret_val = 0;
+ int i;
+ for (i = 0; i < some_value; i++)
+ {
+ int result = 0;
+ if (i%2 == 0)
+ result = kill (getpid(), SIGCHLD);
+ else
+ sigchld_no++;
+
+ usleep(1000);
+ if (result == 0)
+ ret_val++;
+ }
+ usleep (10000);
+ return ret_val;
+}
+
+int
+call_me_nosig (int some_value)
+{
+ int ret_val = 0;
+ int i;
+ for (i = 0; i < some_value; i++)
+ weird_value += i % 4;
+
+ nosig_no += some_value;
+ return some_value;
+}
+
+int
+main ()
+{
+ int ret_val;
+ signal (SIGCHLD, sigchld_handler);
+
+ ret_val = call_me (2); // Stop here in main.
+
+ ret_val = call_me_nosig (10);
+
+ return 0;
+
+}
diff --git a/packages/Python/lldbsuite/test/expression_command/call-throws/Makefile b/packages/Python/lldbsuite/test/expression_command/call-throws/Makefile
new file mode 100644
index 000000000000..ac07b31c48cc
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/call-throws/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../make
+
+OBJC_SOURCES := call-throws.m
+
+include $(LEVEL)/Makefile.rules
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/expression_command/call-throws/TestCallThatThrows.py b/packages/Python/lldbsuite/test/expression_command/call-throws/TestCallThatThrows.py
new file mode 100644
index 000000000000..0e766ac2953a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/call-throws/TestCallThatThrows.py
@@ -0,0 +1,112 @@
+"""
+Test calling a function that throws an ObjC exception, make sure that it doesn't propagate the exception.
+"""
+
+from __future__ import print_function
+
+
+
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ExprCommandWithThrowTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+
+ self.main_source = "call-throws.m"
+ self.main_source_spec = lldb.SBFileSpec (self.main_source)
+
+ @skipUnlessDarwin
+ def test(self):
+ """Test calling a function that throws and ObjC exception."""
+ self.build()
+ self.call_function()
+
+ def check_after_call (self):
+ # Check that we are back where we were before:
+ frame = self.thread.GetFrameAtIndex(0)
+ self.assertTrue (self.orig_frame_pc == frame.GetPC(), "Restored the zeroth frame correctly")
+
+
+ def call_function(self):
+ """Test calling function that throws."""
+ exe_name = "a.out"
+ exe = os.path.join(os.getcwd(), exe_name)
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateBySourceRegex('I am about to throw.',self.main_source_spec)
+ self.assertTrue(breakpoint.GetNumLocations() > 0, VALID_BREAKPOINT)
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Frame #0 should be at our breakpoint.
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint)
+
+ self.assertTrue(len(threads) == 1)
+ self.thread = threads[0]
+
+ options = lldb.SBExpressionOptions()
+ options.SetUnwindOnError(True)
+
+ frame = self.thread.GetFrameAtIndex(0)
+ # Store away the PC to check that the functions unwind to the right place after calls
+ self.orig_frame_pc = frame.GetPC()
+
+ value = frame.EvaluateExpression ("[my_class callMeIThrow]", options)
+ self.assertTrue (value.IsValid())
+ self.assertTrue (value.GetError().Success() == False)
+
+ self.check_after_call()
+
+ # Okay, now try with a breakpoint in the called code in the case where
+ # we are ignoring breakpoint hits.
+ handler_bkpt = target.BreakpointCreateBySourceRegex("I felt like it", self.main_source_spec)
+ self.assertTrue (handler_bkpt.GetNumLocations() > 0)
+ options.SetIgnoreBreakpoints(True)
+ options.SetUnwindOnError(True)
+
+ value = frame.EvaluateExpression ("[my_class callMeIThrow]", options)
+
+ self.assertTrue (value.IsValid() and value.GetError().Success() == False)
+ self.check_after_call()
+
+ # Now set the ObjC language breakpoint and make sure that doesn't interfere with the call:
+ exception_bkpt = target.BreakpointCreateForException (lldb.eLanguageTypeObjC, False, True)
+ self.assertTrue(exception_bkpt.GetNumLocations() > 0)
+
+ options.SetIgnoreBreakpoints(True)
+ options.SetUnwindOnError(True)
+
+ value = frame.EvaluateExpression ("[my_class callMeIThrow]", options)
+
+ self.assertTrue (value.IsValid() and value.GetError().Success() == False)
+ self.check_after_call()
+
+
+ # Now turn off exception trapping, and call a function that catches the exceptions,
+ # and make sure the function actually completes, and we get the right value:
+ options.SetTrapExceptions(False)
+ value = frame.EvaluateExpression ("[my_class iCatchMyself]", options)
+ self.assertTrue (value.IsValid())
+ self.assertTrue (value.GetError().Success() == True)
+ self.assertTrue (value.GetValueAsUnsigned() == 57)
+ self.check_after_call()
+ options.SetTrapExceptions(True)
+
+ # Now set this unwind on error to false, and make sure that we stop where the exception was thrown
+ options.SetUnwindOnError(False)
+ value = frame.EvaluateExpression ("[my_class callMeIThrow]", options)
+
+
+ self.assertTrue (value.IsValid() and value.GetError().Success() == False)
+ self.check_after_call()
diff --git a/packages/Python/lldbsuite/test/expression_command/call-throws/call-throws.m b/packages/Python/lldbsuite/test/expression_command/call-throws/call-throws.m
new file mode 100644
index 000000000000..a184718be7dd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/call-throws/call-throws.m
@@ -0,0 +1,47 @@
+#import <Foundation/Foundation.h>
+
+@interface MyClass : NSObject
+{
+}
+- (int) callMeIThrow;
+- (int) iCatchMyself;
+@end
+
+@implementation MyClass
+- (int) callMeIThrow
+{
+ NSException *e = [NSException
+ exceptionWithName:@"JustForTheHeckOfItException"
+ reason:@"I felt like it"
+ userInfo:nil];
+ @throw e;
+ return 56;
+}
+
+- (int) iCatchMyself
+{
+ int return_value = 55;
+ @try
+ {
+ return_value = [self callMeIThrow];
+ }
+ @catch (NSException *e)
+ {
+ return_value = 57;
+ }
+ return return_value;
+}
+@end
+
+int
+main ()
+{
+ int return_value;
+ MyClass *my_class = [[MyClass alloc] init];
+
+ NSLog (@"I am about to throw.");
+
+ return_value = [my_class iCatchMyself];
+
+ return return_value;
+}
diff --git a/packages/Python/lldbsuite/test/expression_command/char/Makefile b/packages/Python/lldbsuite/test/expression_command/char/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/char/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/expression_command/char/TestExprsChar.py b/packages/Python/lldbsuite/test/expression_command/char/TestExprsChar.py
new file mode 100644
index 000000000000..90e847fd5fa2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/char/TestExprsChar.py
@@ -0,0 +1,69 @@
+from __future__ import print_function
+
+
+
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ExprCharTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+
+ self.main_source = "main.cpp"
+ self.main_source_spec = lldb.SBFileSpec (self.main_source)
+ self.exe = os.path.join(os.getcwd(), "a.out")
+
+ def do_test(self, dictionary=None):
+ """These basic expression commands should work as expected."""
+ self.build(dictionary = dictionary)
+
+ target = self.dbg.CreateTarget(self.exe)
+ self.assertTrue(target)
+
+ breakpoint = target.BreakpointCreateBySourceRegex('// Break here', self.main_source_spec)
+ self.assertTrue(breakpoint)
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple(None, None, self.get_process_working_directory())
+ self.assertTrue(process)
+
+ threads = lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint)
+ self.assertEqual(len(threads), 1)
+
+ frame = threads[0].GetFrameAtIndex(0)
+
+ value = frame.EvaluateExpression("foo(c)")
+ self.assertTrue(value.IsValid())
+ self.assertTrue(value.GetError().Success())
+ self.assertEqual(value.GetValueAsSigned(0), 1)
+
+ value = frame.EvaluateExpression("foo(sc)")
+ self.assertTrue(value.IsValid())
+ self.assertTrue(value.GetError().Success())
+ self.assertEqual(value.GetValueAsSigned(0), 2)
+
+ value = frame.EvaluateExpression("foo(uc)")
+ self.assertTrue(value.IsValid())
+ self.assertTrue(value.GetError().Success())
+ self.assertEqual(value.GetValueAsSigned(0), 3)
+
+ @expectedFailureWindows("llvm.org/pr21765")
+ def test_default_char(self):
+ self.do_test()
+
+ @expectedFailureArch("arm", "llvm.org/pr23069")
+ @expectedFailureArch("aarch64", "llvm.org/pr23069")
+ @expectedFailureWindows("llvm.org/pr21765")
+ def test_signed_char(self):
+ self.do_test(dictionary={'CFLAGS_EXTRAS': '-fsigned-char'})
+
+ @expectedFailurei386("llvm.org/pr23069")
+ @expectedFailurex86_64("llvm.org/pr23069")
+ @expectedFailureWindows("llvm.org/pr21765")
+ def test_unsigned_char(self):
+ self.do_test(dictionary={'CFLAGS_EXTRAS': '-funsigned-char'})
diff --git a/packages/Python/lldbsuite/test/expression_command/char/main.cpp b/packages/Python/lldbsuite/test/expression_command/char/main.cpp
new file mode 100644
index 000000000000..c8b0beb1b355
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/char/main.cpp
@@ -0,0 +1,10 @@
+int foo(char c) { return 1; }
+int foo(signed char c) { return 2; }
+int foo(unsigned char c) { return 3; }
+
+int main() {
+ char c = 0;
+ signed char sc = 0;
+ unsigned char uc = 0;
+ return 0; // Break here
+}
diff --git a/packages/Python/lldbsuite/test/expression_command/expr-in-syscall/Makefile b/packages/Python/lldbsuite/test/expression_command/expr-in-syscall/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/expr-in-syscall/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/expression_command/expr-in-syscall/TestExpressionInSyscall.py b/packages/Python/lldbsuite/test/expression_command/expr-in-syscall/TestExpressionInSyscall.py
new file mode 100644
index 000000000000..0430fa55f995
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/expr-in-syscall/TestExpressionInSyscall.py
@@ -0,0 +1,82 @@
+"""Test that we are able to evaluate expressions when the inferior is blocked in a syscall"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+
+class ExprSyscallTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureWindows("llvm.org/pr21765") # Also getpid() is not a function on Windows anyway
+ def test_setpgid(self):
+ self.build()
+ self.expr_syscall()
+
+ def expr_syscall(self):
+ exe = os.path.join(os.getcwd(), 'a.out')
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ listener = lldb.SBListener("my listener")
+
+ # launch the inferior and don't wait for it to stop
+ self.dbg.SetAsync(True)
+ error = lldb.SBError()
+ process = target.Launch (listener,
+ None, # argv
+ None, # envp
+ None, # stdin_path
+ None, # stdout_path
+ None, # stderr_path
+ None, # working directory
+ 0, # launch flags
+ False, # Stop at entry
+ error) # error
+
+ self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID)
+
+ event = lldb.SBEvent()
+
+ # Give the child enough time to reach the syscall,
+ # while clearing out all the pending events.
+ # The last WaitForEvent call will time out after 2 seconds.
+ while listener.WaitForEvent(2, event):
+ pass
+
+ # now the process should be running (blocked in the syscall)
+ self.assertEqual(process.GetState(), lldb.eStateRunning, "Process is running")
+
+ # send the process a signal
+ process.SendAsyncInterrupt()
+ while listener.WaitForEvent(2, event):
+ pass
+
+ # as a result the process should stop
+ # in all likelihood we have stopped in the middle of the sleep() syscall
+ self.assertEqual(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED)
+ thread = process.GetSelectedThread()
+
+ # try evaluating a couple of expressions in this state
+ self.expect("expr release_flag = 1", substrs = [" = 1"])
+ self.expect("print (int)getpid()", substrs = [str(process.GetProcessID())])
+
+ # and run the process to completion
+ process.Continue()
+
+ # process all events
+ while listener.WaitForEvent(10, event):
+ new_state = lldb.SBProcess.GetStateFromEvent(event)
+ if new_state == lldb.eStateExited:
+ break
+
+ self.assertEqual(process.GetState(), lldb.eStateExited)
+ self.assertEqual(process.GetExitStatus(), 0)
diff --git a/packages/Python/lldbsuite/test/expression_command/expr-in-syscall/main.cpp b/packages/Python/lldbsuite/test/expression_command/expr-in-syscall/main.cpp
new file mode 100644
index 000000000000..743b69434d5f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/expr-in-syscall/main.cpp
@@ -0,0 +1,12 @@
+#include <chrono>
+#include <thread>
+
+volatile int release_flag = 0;
+
+int main(int argc, char const *argv[])
+{
+ while (! release_flag) // Wait for debugger to attach
+ std::this_thread::sleep_for(std::chrono::seconds(3));
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/expression_command/formatters/Makefile b/packages/Python/lldbsuite/test/expression_command/formatters/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/formatters/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/expression_command/formatters/TestFormatters.py b/packages/Python/lldbsuite/test/expression_command/formatters/TestFormatters.py
new file mode 100644
index 000000000000..3f47206480c3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/formatters/TestFormatters.py
@@ -0,0 +1,167 @@
+"""
+Test using LLDB data formatters with frozen objects coming from the expression parser.
+"""
+
+from __future__ import print_function
+
+
+
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ExprFormattersTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break for main.cpp.
+ self.line = line_number('main.cpp',
+ '// Stop here')
+
+ @skipIfFreeBSD # llvm.org/pr24691 skipping to avoid crashing the test runner
+ @expectedFailureFreeBSD('llvm.org/pr19011') # Newer Clang omits C1 complete object constructor
+ @expectedFailureFreeBSD('llvm.org/pr24691') # we hit an assertion in clang
+ @expectedFailureWindows("llvm.org/pr21765")
+ @skipIfTargetAndroid() # skipping to avoid crashing the test runner
+ @expectedFailureAndroid('llvm.org/pr24691') # we hit an assertion in clang
+ def test(self):
+ """Test expr + formatters for good interoperability."""
+ self.build()
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type synthetic clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ """Test expr + formatters for good interoperability."""
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+ self.runCmd("command script import formatters.py")
+ self.runCmd("command script import foosynth.py")
+
+ if self.TraceOn():
+ self.runCmd("frame variable foo1 --show-types")
+ self.runCmd("frame variable foo1.b --show-types")
+ self.runCmd("frame variable foo1.b.b_ref --show-types")
+
+ self.expect("expression --show-types -- *(new foo(47))",
+ substrs = ['(int) a = 47', '(bar) b = {', '(int) i = 94', '(baz) b = {', '(int) k = 99'])
+
+ self.runCmd("type summary add -F formatters.foo_SummaryProvider foo")
+
+ self.expect("expression new int(12)",
+ substrs = ['(int *) $', ' = 0x'])
+
+ self.runCmd("type summary add -s \"${var%pointer} -> ${*var%decimal}\" \"int *\"")
+
+ self.expect("expression new int(12)",
+ substrs = ['(int *) $', '= 0x', ' -> 12'])
+
+ self.expect("expression foo1.a_ptr",
+ substrs = ['(int *) $', '= 0x', ' -> 13'])
+
+ self.expect("expression foo1",
+ substrs = ['(foo) $', ' a = 12', 'a_ptr = ', ' -> 13','i = 24','i_ptr = ', ' -> 25'])
+
+ self.expect("expression --ptr-depth=1 -- new foo(47)",
+ substrs = ['(foo *) $', 'a = 47','a_ptr = ', ' -> 48','i = 94','i_ptr = ', ' -> 95'])
+
+ self.expect("expression foo2",
+ substrs = ['(foo) $', 'a = 121','a_ptr = ', ' -> 122','i = 242','i_ptr = ', ' -> 243'])
+
+ object_name = self.res.GetOutput()
+ object_name = object_name[7:]
+ object_name = object_name[0:object_name.find(' =')]
+
+ self.expect("frame variable foo2",
+ substrs = ['(foo)', 'foo2', 'a = 121','a_ptr = ', ' -> 122','i = 242','i_ptr = ', ' -> 243'])
+
+ self.expect("expression $" + object_name,
+ substrs = ['(foo) $', 'a = 121','a_ptr = ', ' -> 122','i = 242','i_ptr = ', ' -> 243', 'h = 245','k = 247'])
+
+ self.runCmd("type summary delete foo")
+ self.runCmd("type synthetic add --python-class foosynth.FooSyntheticProvider foo")
+
+ self.expect("expression --show-types -- $" + object_name,
+ substrs = ['(foo) $', ' = {', '(int) *i_ptr = 243'])
+
+ self.runCmd("n")
+ self.runCmd("n")
+
+ self.runCmd("type synthetic delete foo")
+ self.runCmd("type summary add -F formatters.foo_SummaryProvider foo")
+
+ self.expect("expression foo2",
+ substrs = ['(foo) $', 'a = 7777','a_ptr = ', ' -> 122','i = 242','i_ptr = ', ' -> 8888'])
+
+ self.expect("expression $" + object_name + '.a',
+ substrs = ['7777'])
+
+ self.expect("expression *$" + object_name + '.b.i_ptr',
+ substrs = ['8888'])
+
+ self.expect("expression $" + object_name,
+ substrs = ['(foo) $', 'a = 121', 'a_ptr = ', ' -> 122', 'i = 242', 'i_ptr = ', ' -> 8888', 'h = 245','k = 247'])
+
+ self.runCmd("type summary delete foo")
+ self.runCmd("type synthetic add --python-class foosynth.FooSyntheticProvider foo")
+
+ self.expect("expression --show-types -- $" + object_name,
+ substrs = ['(foo) $', ' = {', '(int) *i_ptr = 8888'])
+
+ self.runCmd("n")
+
+ self.runCmd("type synthetic delete foo")
+ self.runCmd("type summary add -F formatters.foo_SummaryProvider foo")
+
+ self.expect("expression $" + object_name,
+ substrs = ['(foo) $', 'a = 121','a_ptr = ', ' -> 122','i = 242', 'i_ptr = ', ' -> 8888','k = 247'])
+
+ process = self.dbg.GetSelectedTarget().GetProcess()
+ thread = process.GetThreadAtIndex(0)
+ frame = thread.GetSelectedFrame()
+
+ frozen = frame.EvaluateExpression("$" + object_name + ".a_ptr")
+
+ a_data = frozen.GetPointeeData()
+
+ error = lldb.SBError()
+ self.assertTrue(a_data.GetUnsignedInt32(error, 0) == 122, '*a_ptr = 122')
+
+ self.runCmd("n");self.runCmd("n");self.runCmd("n");
+
+ self.expect("frame variable numbers",
+ substrs = ['1','2','3','4','5'])
+
+ self.expect("expression numbers",
+ substrs = ['1','2','3','4','5'])
+
+ frozen = frame.EvaluateExpression("&numbers")
+
+ a_data = frozen.GetPointeeData(0, 1)
+
+ self.assertTrue(a_data.GetUnsignedInt32(error, 0) == 1, 'numbers[0] == 1')
+ self.assertTrue(a_data.GetUnsignedInt32(error, 4) == 2, 'numbers[1] == 2')
+ self.assertTrue(a_data.GetUnsignedInt32(error, 8) == 3, 'numbers[2] == 3')
+ self.assertTrue(a_data.GetUnsignedInt32(error, 12) == 4, 'numbers[3] == 4')
+ self.assertTrue(a_data.GetUnsignedInt32(error, 16) == 5, 'numbers[4] == 5')
+
+ frozen = frame.EvaluateExpression("numbers")
+
+ a_data = frozen.GetData()
+
+ self.assertTrue(a_data.GetUnsignedInt32(error, 0) == 1, 'numbers[0] == 1')
+ self.assertTrue(a_data.GetUnsignedInt32(error, 4) == 2, 'numbers[1] == 2')
+ self.assertTrue(a_data.GetUnsignedInt32(error, 8) == 3, 'numbers[2] == 3')
+ self.assertTrue(a_data.GetUnsignedInt32(error, 12) == 4, 'numbers[3] == 4')
+ self.assertTrue(a_data.GetUnsignedInt32(error, 16) == 5, 'numbers[4] == 5')
diff --git a/packages/Python/lldbsuite/test/expression_command/formatters/foosynth.py b/packages/Python/lldbsuite/test/expression_command/formatters/foosynth.py
new file mode 100644
index 000000000000..91c4d4a84c62
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/formatters/foosynth.py
@@ -0,0 +1,29 @@
+import lldb
+
+class FooSyntheticProvider:
+ def __init__(self,valobj,dict):
+ self.valobj = valobj;
+ self.update();
+
+ def update(self):
+ self.adjust_for_architecture()
+
+ def num_children(self):
+ return 1;
+
+ def get_child_at_index(self,index):
+ if index != 0:
+ return None;
+ return self.i_ptr.Dereference();
+
+ def get_child_index(self,name):
+ if name == "*i_ptr":
+ return 0;
+ return None;
+
+ def adjust_for_architecture(self):
+ self.lp64 = (self.valobj.GetTarget().GetProcess().GetAddressByteSize() == 8)
+ self.is_little = (self.valobj.GetTarget().GetProcess().GetByteOrder() == lldb.eByteOrderLittle)
+ self.pointer_size = self.valobj.GetTarget().GetProcess().GetAddressByteSize()
+ self.bar = self.valobj.GetChildMemberWithName('b');
+ self.i_ptr = self.bar.GetChildMemberWithName('i_ptr'); \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/expression_command/formatters/formatters.py b/packages/Python/lldbsuite/test/expression_command/formatters/formatters.py
new file mode 100644
index 000000000000..ce922a8f911d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/formatters/formatters.py
@@ -0,0 +1,17 @@
+def foo_SummaryProvider (valobj,dict):
+ a = valobj.GetChildMemberWithName('a');
+ a_ptr = valobj.GetChildMemberWithName('a_ptr');
+ bar = valobj.GetChildMemberWithName('b');
+ i = bar.GetChildMemberWithName('i');
+ i_ptr = bar.GetChildMemberWithName('i_ptr');
+ b_ref = bar.GetChildMemberWithName('b_ref');
+ b_ref_ptr = b_ref.AddressOf()
+ b_ref = b_ref_ptr.Dereference()
+ h = b_ref.GetChildMemberWithName('h');
+ k = b_ref.GetChildMemberWithName('k');
+ return 'a = ' + str(a.GetValueAsUnsigned(0)) + ', a_ptr = ' + \
+ str(a_ptr.GetValueAsUnsigned(0)) + ' -> ' + str(a_ptr.Dereference().GetValueAsUnsigned(0)) + \
+ ', i = ' + str(i.GetValueAsUnsigned(0)) + \
+ ', i_ptr = ' + str(i_ptr.GetValueAsUnsigned(0)) + ' -> ' + str(i_ptr.Dereference().GetValueAsUnsigned(0)) + \
+ ', b_ref = ' + str(b_ref.GetValueAsUnsigned(0)) + \
+ ', h = ' + str(h.GetValueAsUnsigned(0)) + ' , k = ' + str(k.GetValueAsUnsigned(0)) \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/expression_command/formatters/main.cpp b/packages/Python/lldbsuite/test/expression_command/formatters/main.cpp
new file mode 100644
index 000000000000..4c3b180f3709
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/formatters/main.cpp
@@ -0,0 +1,48 @@
+#include <iostream>
+#include <string>
+
+struct baz
+ {
+ int h;
+ int k;
+ baz(int a, int b) : h(a), k(b) {}
+ };
+
+struct bar
+ {
+ int i;
+ int* i_ptr;
+ baz b;
+ baz& b_ref;
+ bar(int x) : i(x),i_ptr(new int(x+1)),b(i+3,i+5),b_ref(b) {}
+ };
+
+struct foo
+ {
+ int a;
+ int* a_ptr;
+ bar b;
+
+ foo(int x) : a(x),
+ a_ptr(new int(x+1)),
+ b(2*x) {}
+
+ };
+
+int main(int argc, char** argv)
+{
+ foo foo1(12);
+ foo foo2(121);
+
+ foo2.a = 7777; // Stop here
+ *(foo2.b.i_ptr) = 8888;
+ foo2.b.b.h = 9999;
+
+ *(foo1.a_ptr) = 9999;
+ foo1.b.i = 9999;
+
+ int numbers[5] = {1,2,3,4,5};
+
+ return 0;
+
+} \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/expression_command/issue_11588/Makefile b/packages/Python/lldbsuite/test/expression_command/issue_11588/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/issue_11588/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/expression_command/issue_11588/Test11588.py b/packages/Python/lldbsuite/test/expression_command/issue_11588/Test11588.py
new file mode 100644
index 000000000000..fdc981ea178d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/issue_11588/Test11588.py
@@ -0,0 +1,77 @@
+"""
+Test the solution to issue 11581.
+valobj.AddressOf() returns None when an address is
+expected in a SyntheticChildrenProvider
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class Issue11581TestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test_11581_commands(self):
+ # This is the function to remove the custom commands in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type synthetic clear', check=False)
+
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ """valobj.AddressOf() should return correct values."""
+ self.build()
+
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateBySourceRegex('Set breakpoint here.',lldb.SBFileSpec ("main.cpp", False))
+
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue (process, "Created a process.")
+ self.assertTrue (process.GetState() == lldb.eStateStopped, "Stopped it too.")
+
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint)
+ self.assertTrue (len(thread_list) == 1)
+ thread = thread_list[0]
+
+ self.runCmd("command script import --allow-reload s11588.py")
+ self.runCmd("type synthetic add --python-class s11588.Issue11581SyntheticProvider StgClosure")
+
+ self.expect("expr --show-types -- *((StgClosure*)(r14-1))",
+ substrs = ["(StgClosure) $",
+ "(StgClosure *) &$","0x",
+ "addr = ",
+ "load_address = "])
+
+ # register r14 is an x86_64 extension let's skip this part of the test
+ # if we are on a different architecture
+ if self.getArchitecture() == 'x86_64':
+ target = lldb.debugger.GetSelectedTarget()
+ process = target.GetProcess()
+ frame = process.GetSelectedThread().GetSelectedFrame()
+ pointer = frame.FindVariable("r14")
+ addr = pointer.GetValueAsUnsigned(0)
+ self.assertTrue(addr != 0, "could not read pointer to StgClosure")
+ addr = addr - 1
+ self.runCmd("register write r14 %d" % addr)
+ self.expect("register read r14",
+ substrs = ["0x",hex(addr)[2:].rstrip("L")]) # Remove trailing 'L' if it exists
+ self.expect("expr --show-types -- *(StgClosure*)$r14",
+ substrs = ["(StgClosure) $",
+ "(StgClosure *) &$","0x",
+ "addr = ",
+ "load_address = ",
+ hex(addr)[2:].rstrip("L"),
+ str(addr)])
diff --git a/packages/Python/lldbsuite/test/expression_command/issue_11588/main.cpp b/packages/Python/lldbsuite/test/expression_command/issue_11588/main.cpp
new file mode 100644
index 000000000000..4f9ea3abf181
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/issue_11588/main.cpp
@@ -0,0 +1,54 @@
+//
+// 11588.cpp
+//
+
+#include <iostream>
+
+class StgInfoTable {};
+
+class StgHeader
+{
+private:
+ StgInfoTable* info;
+public:
+ StgHeader()
+ {
+ info = new StgInfoTable();
+ }
+ ~StgHeader()
+ {
+ delete info;
+ }
+};
+
+class StgClosure
+{
+private:
+ StgHeader header;
+ StgClosure* payload[1];
+public:
+ StgClosure(bool make_payload = true)
+ {
+ if (make_payload)
+ payload[0] = new StgClosure(false);
+ else
+ payload[0] = NULL;
+ }
+ ~StgClosure()
+ {
+ if (payload[0])
+ delete payload[0];
+ }
+};
+
+typedef unsigned long long int ptr_type;
+
+int main()
+{
+ StgClosure* r14_ = new StgClosure();
+ r14_ = (StgClosure*)(((ptr_type)r14_ | 0x01)); // set the LSB to 1 for tagging
+ ptr_type r14 = (ptr_type)r14_;
+ int x = 0;
+ x = 3;
+ return (x-1); // Set breakpoint here.
+}
diff --git a/packages/Python/lldbsuite/test/expression_command/issue_11588/s11588.py b/packages/Python/lldbsuite/test/expression_command/issue_11588/s11588.py
new file mode 100644
index 000000000000..01bb09a1b0d6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/issue_11588/s11588.py
@@ -0,0 +1,26 @@
+class Issue11581SyntheticProvider(object):
+ def __init__(self, valobj, dict):
+ self.valobj = valobj
+ self.addrOf = valobj.AddressOf()
+ self.addr = valobj.GetAddress()
+ self.load_address = valobj.GetLoadAddress()
+
+ def num_children(self):
+ return 3;
+
+ def get_child_at_index(self, index):
+ if index == 0:
+ return self.addrOf
+ if index == 1:
+ return self.valobj.CreateValueFromExpression("addr", str(self.addr))
+ if index == 2:
+ return self.valobj.CreateValueFromExpression("load_address", str(self.load_address))
+
+ def get_child_index(self, name):
+ if name == "addrOf":
+ return 0
+ if name == "addr":
+ return 1
+ if name == "load_address":
+ return 2
+
diff --git a/packages/Python/lldbsuite/test/expression_command/macros/Makefile b/packages/Python/lldbsuite/test/expression_command/macros/Makefile
new file mode 100644
index 000000000000..1ecd744be14b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/macros/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+DEBUG_INFO_FLAG = -g3
+
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/expression_command/macros/TestMacros.py b/packages/Python/lldbsuite/test/expression_command/macros/TestMacros.py
new file mode 100644
index 000000000000..c3d6306c5a63
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/macros/TestMacros.py
@@ -0,0 +1,106 @@
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TestMacros(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureClang("clang does not emit .debug_macro[.dwo] sections.")
+ @expectedFailureDwo("GCC produces multiple .debug_macro.dwo sections and the spec is unclear as to what it means")
+ @expectedFailureAll(hostoslist=["windows"], compiler="gcc", triple='.*-android')
+ def test_expr_with_macros(self):
+ self.build()
+
+ # Get main source file
+ src_file = "main.cpp"
+ hdr_file = "macro1.h"
+ src_file_spec = lldb.SBFileSpec(src_file)
+ self.assertTrue(src_file_spec.IsValid(), "Main source file")
+
+ # Get the path of the executable
+ cwd = os.getcwd()
+ exe_file = "a.out"
+ exe_path = os.path.join(cwd, exe_file)
+
+ # Load the executable
+ target = self.dbg.CreateTarget(exe_path)
+ self.assertTrue(target.IsValid(), VALID_TARGET)
+
+ # Set breakpoints
+ bp1 = target.BreakpointCreateBySourceRegex("Break here", src_file_spec)
+ self.assertTrue(bp1.IsValid() and bp1.GetNumLocations() >= 1, VALID_BREAKPOINT)
+
+ # Launch the process
+ process = target.LaunchSimple(None, None, self.get_process_working_directory())
+ self.assertTrue(process.IsValid(), PROCESS_IS_VALID)
+
+ # Get the thread of the process
+ self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+
+ # Get frame for current thread
+ frame = thread.GetSelectedFrame()
+
+ result = frame.EvaluateExpression("MACRO_1")
+ self.assertTrue(result.IsValid() and result.GetValue() == "100", "MACRO_1 = 100")
+
+ result = frame.EvaluateExpression("MACRO_2")
+ self.assertTrue(result.IsValid() and result.GetValue() == "200", "MACRO_2 = 200")
+
+ result = frame.EvaluateExpression("ONE")
+ self.assertTrue(result.IsValid() and result.GetValue() == "1", "ONE = 1")
+
+ result = frame.EvaluateExpression("TWO")
+ self.assertTrue(result.IsValid() and result.GetValue() == "2", "TWO = 2")
+
+ result = frame.EvaluateExpression("THREE")
+ self.assertTrue(result.IsValid() and result.GetValue() == "3", "THREE = 3")
+
+ result = frame.EvaluateExpression("FOUR")
+ self.assertTrue(result.IsValid() and result.GetValue() == "4", "FOUR = 4")
+
+ result = frame.EvaluateExpression("HUNDRED")
+ self.assertTrue(result.IsValid() and result.GetValue() == "100", "HUNDRED = 100")
+
+ result = frame.EvaluateExpression("THOUSAND")
+ self.assertTrue(result.IsValid() and result.GetValue() == "1000", "THOUSAND = 1000")
+
+ result = frame.EvaluateExpression("MILLION")
+ self.assertTrue(result.IsValid() and result.GetValue() == "1000000", "MILLION = 1000000")
+
+ result = frame.EvaluateExpression("MAX(ONE, TWO)")
+ self.assertTrue(result.IsValid() and result.GetValue() == "2", "MAX(ONE, TWO) = 2")
+
+ result = frame.EvaluateExpression("MAX(THREE, TWO)")
+ self.assertTrue(result.IsValid() and result.GetValue() == "3", "MAX(THREE, TWO) = 3")
+
+ # Get the thread of the process
+ thread.StepOver()
+
+ # Get frame for current thread
+ frame = thread.GetSelectedFrame()
+
+ result = frame.EvaluateExpression("MACRO_2")
+ self.assertTrue(result.GetError().Fail(), "Printing MACRO_2 fails in the mail file")
+
+ result = frame.EvaluateExpression("FOUR")
+ self.assertTrue(result.GetError().Fail(), "Printing FOUR fails in the main file")
+
+ thread.StepInto()
+
+ # Get frame for current thread
+ frame = thread.GetSelectedFrame()
+
+ result = frame.EvaluateExpression("ONE")
+ self.assertTrue(result.IsValid() and result.GetValue() == "1", "ONE = 1")
+
+ result = frame.EvaluateExpression("MAX(ONE, TWO)")
+ self.assertTrue(result.IsValid() and result.GetValue() == "2", "MAX(ONE, TWO) = 2")
+
+ # This time, MACRO_1 and MACRO_2 are not visible.
+ result = frame.EvaluateExpression("MACRO_1")
+ self.assertTrue(result.GetError().Fail(), "Printing MACRO_1 fails in the header file")
+
+ result = frame.EvaluateExpression("MACRO_2")
+ self.assertTrue(result.GetError().Fail(), "Printing MACRO_2 fails in the header file")
diff --git a/packages/Python/lldbsuite/test/expression_command/macros/macro1.h b/packages/Python/lldbsuite/test/expression_command/macros/macro1.h
new file mode 100644
index 000000000000..e026bc018ace
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/macros/macro1.h
@@ -0,0 +1,17 @@
+
+#include "macro2.h"
+
+#define ONE 1
+#define TWO 2
+#define THREE 3
+#define FOUR 4
+
+class Simple
+{
+public:
+ int
+ Method()
+ {
+ return ONE + TWO;
+ };
+};
diff --git a/packages/Python/lldbsuite/test/expression_command/macros/macro2.h b/packages/Python/lldbsuite/test/expression_command/macros/macro2.h
new file mode 100644
index 000000000000..cec6efbba990
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/macros/macro2.h
@@ -0,0 +1,8 @@
+#define HUNDRED 100
+#define THOUSAND 1000
+#define MILLION 1000000
+
+#define MAX(a, b)\
+((a) > (b) ?\
+ (a):\
+ (b))
diff --git a/packages/Python/lldbsuite/test/expression_command/macros/main.cpp b/packages/Python/lldbsuite/test/expression_command/macros/main.cpp
new file mode 100644
index 000000000000..f2c2c101fa15
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/macros/main.cpp
@@ -0,0 +1,15 @@
+#include "macro1.h"
+
+#define MACRO_1 100
+#define MACRO_2 200
+
+int
+main ()
+{
+ int a = ONE + TWO; // Break here
+
+ #undef MACRO_2
+ #undef FOUR
+
+ return Simple().Method();
+}
diff --git a/packages/Python/lldbsuite/test/expression_command/options/Makefile b/packages/Python/lldbsuite/test/expression_command/options/Makefile
new file mode 100644
index 000000000000..81ae6f6f16ec
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/options/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp foo.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/expression_command/options/TestExprOptions.py b/packages/Python/lldbsuite/test/expression_command/options/TestExprOptions.py
new file mode 100644
index 000000000000..00c34820eef3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/options/TestExprOptions.py
@@ -0,0 +1,76 @@
+"""
+Test expression command options.
+
+Test cases:
+
+o test_expr_options:
+ Test expression command options.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ExprOptionsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+
+ self.main_source = "main.cpp"
+ self.main_source_spec = lldb.SBFileSpec (self.main_source)
+ self.line = line_number('main.cpp', '// breakpoint_in_main')
+ self.exe = os.path.join(os.getcwd(), "a.out")
+
+ def test_expr_options(self):
+ """These expression command options should work as expected."""
+ self.build()
+
+ # Set debugger into synchronous mode
+ self.dbg.SetAsync(False)
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(self.exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Set breakpoints inside main.
+ breakpoint = target.BreakpointCreateBySourceRegex('// breakpoint_in_main', self.main_source_spec)
+ self.assertTrue(breakpoint)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple(None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ threads = lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint)
+ self.assertEqual(len(threads), 1)
+
+ frame = threads[0].GetFrameAtIndex(0)
+ options = lldb.SBExpressionOptions()
+
+ # test --language on C++ expression using the SB API's
+
+ # Make sure we can evaluate a C++11 expression.
+ val = frame.EvaluateExpression('foo != nullptr')
+ self.assertTrue(val.IsValid())
+ self.assertTrue(val.GetError().Success())
+ self.DebugSBValue(val)
+
+ # Make sure it still works if language is set to C++11:
+ options.SetLanguage(lldb.eLanguageTypeC_plus_plus_11)
+ val = frame.EvaluateExpression('foo != nullptr', options)
+ self.assertTrue(val.IsValid())
+ self.assertTrue(val.GetError().Success())
+ self.DebugSBValue(val)
+
+ # Make sure it fails if language is set to C:
+ options.SetLanguage(lldb.eLanguageTypeC)
+ val = frame.EvaluateExpression('foo != nullptr', options)
+ self.assertTrue(val.IsValid())
+ self.assertFalse(val.GetError().Success())
diff --git a/packages/Python/lldbsuite/test/expression_command/options/foo.cpp b/packages/Python/lldbsuite/test/expression_command/options/foo.cpp
new file mode 100644
index 000000000000..8a5a6a2b5416
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/options/foo.cpp
@@ -0,0 +1,11 @@
+namespace ns {
+ int func(void)
+ {
+ return 0;
+ }
+}
+
+extern "C" int foo(void)
+{
+ return ns::func();
+}
diff --git a/packages/Python/lldbsuite/test/expression_command/options/main.cpp b/packages/Python/lldbsuite/test/expression_command/options/main.cpp
new file mode 100644
index 000000000000..ecd9a90f6626
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/options/main.cpp
@@ -0,0 +1,15 @@
+extern "C" int foo(void);
+static int static_value = 0;
+
+int
+bar()
+{
+ static_value++;
+ return static_value;
+}
+
+int main (int argc, char const *argv[])
+{
+ bar(); // breakpoint_in_main
+ return foo();
+}
diff --git a/packages/Python/lldbsuite/test/expression_command/persist_objc_pointeetype/Makefile b/packages/Python/lldbsuite/test/expression_command/persist_objc_pointeetype/Makefile
new file mode 100644
index 000000000000..8066198300fb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/persist_objc_pointeetype/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../make
+
+OBJC_SOURCES := main.m
+
+include $(LEVEL)/Makefile.rules
+LDFLAGS += -framework Foundation -framework CloudKit
+
diff --git a/packages/Python/lldbsuite/test/expression_command/persist_objc_pointeetype/TestPersistObjCPointeeType.py b/packages/Python/lldbsuite/test/expression_command/persist_objc_pointeetype/TestPersistObjCPointeeType.py
new file mode 100644
index 000000000000..7b0707cdf22c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/persist_objc_pointeetype/TestPersistObjCPointeeType.py
@@ -0,0 +1,50 @@
+"""
+Test that we can p *objcObject
+"""
+
+from __future__ import print_function
+
+
+
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class PersistObjCPointeeType(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break for main.cpp.
+ self.line = line_number('main.m','// break here')
+
+ @skipUnlessDarwin
+ @expectedFailureAll(
+ bugnumber='http://llvm.org/pr23504',
+ oslist=['macosx'], compiler='clang', compiler_version=['<', '7.0.0'])
+ def test_with(self):
+ """Test that we can p *objcObject"""
+ self.build()
+
+ def cleanup():
+ pass
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.expect("p *self", substrs=['_sc_name = nil',
+ '_sc_name2 = nil',
+ '_sc_name3 = nil',
+ '_sc_name4 = nil',
+ '_sc_name5 = nil',
+ '_sc_name6 = nil',
+ '_sc_name7 = nil',
+ '_sc_name8 = nil'])
diff --git a/packages/Python/lldbsuite/test/expression_command/persist_objc_pointeetype/main.m b/packages/Python/lldbsuite/test/expression_command/persist_objc_pointeetype/main.m
new file mode 100644
index 000000000000..a2b6b703d6c8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/persist_objc_pointeetype/main.m
@@ -0,0 +1,80 @@
+/*
+clang -g ExtendSuperclass.m -o ExtendSuperclass -framework Foundation -framework ProtectedCloudStorage -F/System/Library/PrivateFrameworks/ -framework CloudKit && ./ExtendSuperclass
+*/
+#include <assert.h>
+#import <Foundation/Foundation.h>
+#import <CloudKit/CloudKit.h>
+
+#define SuperClass CKDatabase
+
+@interface SubClass : SuperClass
+@end
+
+// class extension
+@interface SuperClass ()
+@property (nonatomic, strong) NSString *_sc_name;
+@property (nonatomic, strong) NSString *_sc_name2;
+@property (nonatomic, strong) NSString *_sc_name3;
+@property (nonatomic, strong) NSString *_sc_name4;
+@property (nonatomic, strong) NSString *_sc_name5;
+@property (nonatomic, strong) NSString *_sc_name6;
+@property (nonatomic, strong) NSString *_sc_name7;
+@property (nonatomic, strong) NSString *_sc_name8;
+@end
+
+@implementation SuperClass (MySuperClass)
+- (id)initThatDoesNotAssert
+{
+ return [super init];
+}
+@end
+
+@implementation SubClass
+- (id)initThatDoesNotAssert
+{
+ assert(_sc_name == nil);
+ assert(_sc_name2 == nil);
+ assert(_sc_name3 == nil);
+ assert(_sc_name4 == nil);
+ assert(_sc_name5 == nil);
+ assert(_sc_name6 == nil);
+ assert(_sc_name7 == nil);
+ assert(_sc_name8 == nil); // break here
+
+ if ((self = [super _initWithContainer:(CKContainer*)@"foo" scope:0xff])) {
+ assert(_sc_name == nil);
+ assert(_sc_name2 == nil);
+ assert(_sc_name3 == nil);
+ assert(_sc_name4 == nil);
+ assert(_sc_name5 == nil);
+ assert(_sc_name6 == nil);
+ assert(_sc_name7 == nil);
+ assert(_sc_name8 == nil);
+
+ _sc_name = @"empty";
+ }
+ return self;
+}
+@synthesize _sc_name;
+@synthesize _sc_name2;
+@synthesize _sc_name3;
+@synthesize _sc_name4;
+@synthesize _sc_name5;
+@synthesize _sc_name6;
+@synthesize _sc_name7;
+@synthesize _sc_name8;
+- (void)foo:(NSString*)bar { self._sc_name = bar; }
+- (NSString*)description { return [NSString stringWithFormat:@"%p: %@", self, self._sc_name]; }
+@end
+
+int main()
+{
+ SubClass *sc = [[SubClass alloc] initThatDoesNotAssert];
+ NSLog(@"%@", sc);
+ [sc foo:@"bar"];
+ NSLog(@"%@", sc);
+ sc._sc_name = @"bar2";
+ NSLog(@"%@", sc);
+ NSLog(@"%@", sc._sc_name);
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/expression_command/persistent_ptr_update/Makefile b/packages/Python/lldbsuite/test/expression_command/persistent_ptr_update/Makefile
new file mode 100644
index 000000000000..db5f575866d9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/persistent_ptr_update/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
+
+
diff --git a/packages/Python/lldbsuite/test/expression_command/persistent_ptr_update/TestPersistentPtrUpdate.py b/packages/Python/lldbsuite/test/expression_command/persistent_ptr_update/TestPersistentPtrUpdate.py
new file mode 100644
index 000000000000..9d7359fb2d45
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/persistent_ptr_update/TestPersistentPtrUpdate.py
@@ -0,0 +1,41 @@
+"""
+Test that we can have persistent pointer variables
+"""
+
+from __future__ import print_function
+
+
+
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class PersistentPtrUpdateTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+
+ def test(self):
+ """Test that we can have persistent pointer variables"""
+ self.build()
+
+ def cleanup():
+ pass
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ self.runCmd('break set -p here')
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.runCmd("expr void* $foo = 0")
+
+ self.runCmd("continue")
+
+ self.expect("expr $foo", substrs=['$foo','0x0'])
diff --git a/packages/Python/lldbsuite/test/expression_command/persistent_ptr_update/main.c b/packages/Python/lldbsuite/test/expression_command/persistent_ptr_update/main.c
new file mode 100644
index 000000000000..73346969eccc
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/persistent_ptr_update/main.c
@@ -0,0 +1,11 @@
+void* foo(void *p)
+{
+ return p; // break here
+}
+
+int main() {
+ while (1) {
+ foo(0);
+ }
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/expression_command/persistent_types/Makefile b/packages/Python/lldbsuite/test/expression_command/persistent_types/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/persistent_types/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/expression_command/persistent_types/TestNestedPersistentTypes.py b/packages/Python/lldbsuite/test/expression_command/persistent_types/TestNestedPersistentTypes.py
new file mode 100644
index 000000000000..3ea5b7040655
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/persistent_types/TestNestedPersistentTypes.py
@@ -0,0 +1,41 @@
+"""
+Test that nested persistent types work.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class NestedPersistentTypesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureWindows("llvm.org/pr21765")
+ def test_persistent_types(self):
+ """Test that nested persistent types work."""
+ self.build()
+
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ self.runCmd("breakpoint set --name main")
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.runCmd("expression struct $foo { int a; int b; };")
+
+ self.runCmd("expression struct $bar { struct $foo start; struct $foo end; };")
+
+ self.runCmd("expression struct $bar $my_bar = {{ 2, 3 }, { 4, 5 }};")
+
+ self.expect("expression $my_bar",
+ substrs = ['a = 2', 'b = 3', 'a = 4', 'b = 5'])
+
+ self.expect("expression $my_bar.start.b",
+ substrs = ['(int)', '3'])
+
+ self.expect("expression $my_bar.end.b",
+ substrs = ['(int)', '5'])
diff --git a/packages/Python/lldbsuite/test/expression_command/persistent_types/TestPersistentTypes.py b/packages/Python/lldbsuite/test/expression_command/persistent_types/TestPersistentTypes.py
new file mode 100644
index 000000000000..47c6675511fd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/persistent_types/TestPersistentTypes.py
@@ -0,0 +1,57 @@
+"""
+Test that lldb persistent types works correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class PersistenttypesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureWindows("llvm.org/pr21765")
+ def test_persistent_types(self):
+ """Test that lldb persistent types works correctly."""
+ self.build()
+
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ self.runCmd("breakpoint set --name main")
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.runCmd("expression struct $foo { int a; int b; };")
+
+ self.expect("expression struct $foo $my_foo; $my_foo.a = 2; $my_foo.b = 3;",
+ startstr = "(int) $0 = 3")
+
+ self.expect("expression $my_foo",
+ substrs = ['a = 2', 'b = 3'])
+
+ self.runCmd("expression typedef int $bar")
+
+ self.expect("expression $bar i = 5; i",
+ startstr = "($bar) $1 = 5")
+
+ self.runCmd("expression struct $foobar { char a; char b; char c; char d; };")
+ self.runCmd("next")
+
+ self.expect("memory read foo -t $foobar",
+ substrs = ['($foobar) 0x', ' = ', "a = 'H'","b = 'e'","c = 'l'","d = 'l'"]) # persistent types are OK to use for memory read
+
+ self.expect("memory read foo -t foobar",
+ substrs = ['($foobar) 0x', ' = ', "a = 'H'","b = 'e'","c = 'l'","d = 'l'"],matching=False,error=True) # the type name is $foobar, make sure we settle for nothing less
+
+ self.expect("expression struct { int a; int b; } x = { 2, 3 }; x",
+ substrs = ['a = 2', 'b = 3'])
+
+ self.expect("expression struct { int x; int y; int z; } object; object.y = 1; object.z = 3; object.x = 2; object",
+ substrs = ['x = 2', 'y = 1', 'z = 3'])
+
+ self.expect("expression struct A { int x; int y; }; struct { struct A a; int z; } object; object.a.y = 1; object.z = 3; object.a.x = 2; object",
+ substrs = ['x = 2', 'y = 1', 'z = 3'])
diff --git a/packages/Python/lldbsuite/test/expression_command/persistent_types/main.c b/packages/Python/lldbsuite/test/expression_command/persistent_types/main.c
new file mode 100644
index 000000000000..9e26e619bfdb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/persistent_types/main.c
@@ -0,0 +1,14 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+int main (int argc, char const *argv[])
+{
+ const char* foo = "Hello world";
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/expression_command/persistent_variables/Makefile b/packages/Python/lldbsuite/test/expression_command/persistent_variables/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/persistent_variables/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/expression_command/persistent_variables/TestPersistentVariables.py b/packages/Python/lldbsuite/test/expression_command/persistent_variables/TestPersistentVariables.py
new file mode 100644
index 000000000000..e148fcd89599
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/persistent_variables/TestPersistentVariables.py
@@ -0,0 +1,54 @@
+"""
+Test that lldb persistent variables works correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class PersistentVariablesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test_persistent_variables(self):
+ """Test that lldb persistent variables works correctly."""
+ self.build()
+
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ self.runCmd("breakpoint set --source-pattern-regexp break")
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.runCmd("expression int $i = i")
+
+ self.expect("expression $i == i",
+ startstr = "(bool) $0 = true")
+
+ self.expect("expression $i + 1",
+ startstr = "(int) $1 = 6")
+
+ self.expect("expression $i + 3",
+ startstr = "(int) $2 = 8")
+
+ self.expect("expression $2 + $1",
+ startstr = "(int) $3 = 14")
+
+ self.expect("expression $3",
+ startstr = "(int) $3 = 14")
+
+ self.expect("expression $2",
+ startstr = "(int) $2 = 8")
+
+ self.expect("expression (int)-2",
+ startstr = "(int) $4 = -2")
+
+ self.expect("expression $4 > (int)31",
+ startstr = "(bool) $5 = false")
+
+ self.expect("expression (long)$4",
+ startstr = "(long) $6 = -2")
diff --git a/packages/Python/lldbsuite/test/expression_command/persistent_variables/main.c b/packages/Python/lldbsuite/test/expression_command/persistent_variables/main.c
new file mode 100644
index 000000000000..fd41471df8ed
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/persistent_variables/main.c
@@ -0,0 +1,14 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+int main (int argc, char const *argv[])
+{
+ int i = 5;
+ return 0; // Set breakpoint here
+}
diff --git a/packages/Python/lldbsuite/test/expression_command/po_verbosity/Makefile b/packages/Python/lldbsuite/test/expression_command/po_verbosity/Makefile
new file mode 100644
index 000000000000..4464e2ee9f5c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/po_verbosity/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../make
+
+OBJC_SOURCES := main.m
+
+include $(LEVEL)/Makefile.rules
+LDFLAGS += -framework Cocoa
diff --git a/packages/Python/lldbsuite/test/expression_command/po_verbosity/TestPoVerbosity.py b/packages/Python/lldbsuite/test/expression_command/po_verbosity/TestPoVerbosity.py
new file mode 100644
index 000000000000..e415b92a43a6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/po_verbosity/TestPoVerbosity.py
@@ -0,0 +1,61 @@
+"""
+Test that the po command acts correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class PoVerbosityTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break for main.cpp.
+ self.line = line_number('main.m',
+ '// Stop here')
+
+ @skipUnlessDarwin
+ def test(self):
+ """Test that the po command acts correctly."""
+ self.build()
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type synthetic clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ """Test expr + formatters for good interoperability."""
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.expect("expr -O -v -- foo",
+ substrs = ['(id) $',' = 0x', '1 = 2','2 = 3;'])
+ self.expect("expr -O -vfull -- foo",
+ substrs = ['(id) $',' = 0x', '1 = 2','2 = 3;'])
+ self.expect("expr -O -- foo",matching=False,
+ substrs = ['(id) $'])
+
+ self.expect("expr -O -- 22",matching=False,
+ substrs = ['(int) $'])
+ self.expect("expr -O -- 22",
+ substrs = ['22'])
+
+ self.expect("expr -O -vfull -- 22",
+ substrs = ['(int) $', ' = 22'])
+
+ self.expect("expr -O -v -- 22",
+ substrs = ['(int) $', ' = 22'])
diff --git a/packages/Python/lldbsuite/test/expression_command/po_verbosity/main.m b/packages/Python/lldbsuite/test/expression_command/po_verbosity/main.m
new file mode 100644
index 000000000000..3dbb024b2809
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/po_verbosity/main.m
@@ -0,0 +1,9 @@
+#import <Cocoa/Cocoa.h>
+
+int main()
+{
+ [NSString initialize];
+ id foo = @{@1 : @2, @2 : @3};
+ int x = 34;
+ return 0; // Stop here
+}
diff --git a/packages/Python/lldbsuite/test/expression_command/radar_8638051/Makefile b/packages/Python/lldbsuite/test/expression_command/radar_8638051/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/radar_8638051/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/expression_command/radar_8638051/Test8638051.py b/packages/Python/lldbsuite/test/expression_command/radar_8638051/Test8638051.py
new file mode 100644
index 000000000000..302b14b7360e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/radar_8638051/Test8638051.py
@@ -0,0 +1,39 @@
+"""
+Test the robustness of lldb expression parser.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class Radar8638051TestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test_expr_commands(self):
+ """The following expression commands should not crash."""
+ self.build()
+
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ self.runCmd("breakpoint set -n c")
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.expect("expression val",
+ startstr = "(int) $0 = 1")
+ # (int) $0 = 1
+
+ self.expect("expression *(&val)",
+ startstr = "(int) $1 = 1")
+ # (int) $1 = 1
+
+ # rdar://problem/8638051
+ # lldb expression command: Could this crash be avoided
+ self.expect("expression &val",
+ startstr = "(int *) $2 = ")
+ # (int *) $2 = 0x....
diff --git a/packages/Python/lldbsuite/test/expression_command/radar_8638051/main.c b/packages/Python/lldbsuite/test/expression_command/radar_8638051/main.c
new file mode 100644
index 000000000000..1329fd69a2e1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/radar_8638051/main.c
@@ -0,0 +1,54 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+// This simple program is to demonstrate the capability of the lldb command
+// "breakpoint command add" to add a set of commands to a breakpoint to be
+// executed when the breakpoint is hit.
+//
+// In particular, we want to break within c(), but only if the immediate caller
+// is a().
+
+int a(int);
+int b(int);
+int c(int);
+
+int a(int val)
+{
+ if (val <= 1)
+ return b(val);
+ else if (val >= 3)
+ return c(val); // Find the line number where c's parent frame is a here.
+
+ return val;
+}
+
+int b(int val)
+{
+ return c(val);
+}
+
+int c(int val)
+{
+ return val + 3;
+}
+
+int main (int argc, char const *argv[])
+{
+ int A1 = a(1); // a(1) -> b(1) -> c(1)
+ printf("a(1) returns %d\n", A1);
+
+ int B2 = b(2); // b(2) -> c(2)
+ printf("b(2) returns %d\n", B2);
+
+ int A3 = a(3); // a(3) -> c(3)
+ printf("a(3) returns %d\n", A3);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/expression_command/radar_9531204/Makefile b/packages/Python/lldbsuite/test/expression_command/radar_9531204/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/radar_9531204/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/expression_command/radar_9531204/TestPrintfAfterUp.py b/packages/Python/lldbsuite/test/expression_command/radar_9531204/TestPrintfAfterUp.py
new file mode 100644
index 000000000000..fb16d2a93326
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/radar_9531204/TestPrintfAfterUp.py
@@ -0,0 +1,42 @@
+"""
+The evaluating printf(...) after break stop and then up a stack frame.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class Radar9531204TestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ # rdar://problem/9531204
+ @expectedFailureWindows("llvm.org/pr21765")
+ def test_expr_commands(self):
+ """The evaluating printf(...) after break stop and then up a stack frame."""
+ self.build()
+
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_symbol (self, 'foo', sym_exact=True, num_expected_locations=1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.runCmd("frame variable")
+
+ # This works fine.
+ self.runCmd('expression (int)printf("value is: %d.\\n", value);')
+
+ # rdar://problem/9531204
+ # "Error dematerializing struct" error when evaluating expressions "up" on the stack
+ self.runCmd('up') # frame select -r 1
+
+ self.runCmd("frame variable")
+
+ # This does not currently.
+ self.runCmd('expression (int)printf("argc is: %d.\\n", argc)')
diff --git a/packages/Python/lldbsuite/test/expression_command/radar_9531204/main.c b/packages/Python/lldbsuite/test/expression_command/radar_9531204/main.c
new file mode 100644
index 000000000000..2bf05f2b3065
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/radar_9531204/main.c
@@ -0,0 +1,25 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+// breakpoint set -n foo
+//
+//
+int foo (int value)
+{
+ printf ("I got the value: %d.\n", value);
+ return 0;
+}
+
+int main (int argc, char **argv)
+{
+ foo (argc);
+ printf ("Hello there: %d.\n", argc);
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/expression_command/radar_9673664/Makefile b/packages/Python/lldbsuite/test/expression_command/radar_9673664/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/radar_9673664/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/expression_command/radar_9673664/TestExprHelpExamples.py b/packages/Python/lldbsuite/test/expression_command/radar_9673664/TestExprHelpExamples.py
new file mode 100644
index 000000000000..ce3e51d05149
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/radar_9673664/TestExprHelpExamples.py
@@ -0,0 +1,41 @@
+"""
+Test example snippets from the lldb 'help expression' output.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class Radar9673644TestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.main_source = "main.c"
+ self.line = line_number(self.main_source, '// Set breakpoint here.')
+
+ @expectedFailureWindows("llvm.org/pr21765")
+ def test_expr_commands(self):
+ """The following expression commands should just work."""
+ self.build()
+
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, self.main_source, self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # rdar://problem/9673664 lldb expression evaluation problem
+
+ self.expect('expr char c[] = "foo"; c[0]',
+ substrs = ["'f'"])
+ # runCmd: expr char c[] = "foo"; c[0]
+ # output: (char) $0 = 'f'
diff --git a/packages/Python/lldbsuite/test/expression_command/radar_9673664/main.c b/packages/Python/lldbsuite/test/expression_command/radar_9673664/main.c
new file mode 100644
index 000000000000..934abdfaef3e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/radar_9673664/main.c
@@ -0,0 +1,16 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+int main (int argc, char const *argv[])
+{
+ printf("Hello, world.\n"); // Set breakpoint here.
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/expression_command/test/Makefile b/packages/Python/lldbsuite/test/expression_command/test/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/test/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/expression_command/test/TestExprs.py b/packages/Python/lldbsuite/test/expression_command/test/TestExprs.py
new file mode 100644
index 000000000000..ec3e7f93af26
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/test/TestExprs.py
@@ -0,0 +1,248 @@
+"""
+Test many basic expression commands and SBFrame.EvaluateExpression() API.
+
+Test cases:
+
+o test_many_expr_commands:
+ Test many basic expression commands.
+o test_evaluate_expression_python:
+ Use Python APIs (SBFrame.EvaluateExpression()) to evaluate expressions.
+o test_expr_commands_can_handle_quotes:
+ Throw some expression commands with quotes at lldb.
+"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class BasicExprCommandsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break for main.c.
+ self.line = line_number('main.cpp',
+ '// Please test many expressions while stopped at this line:')
+
+ # Disable confirmation prompt to avoid infinite wait
+ self.runCmd("settings set auto-confirm true")
+ self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm"))
+
+
+ def build_and_run(self):
+ """These basic expression commands should work as expected."""
+ self.build()
+
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=False)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ @unittest2.expectedFailure("llvm.org/pr17135 <rdar://problem/14874559> APFloat::toString does not identify the correct (i.e. least) precision.")
+ def test_floating_point_expr_commands(self):
+ self.build_and_run()
+
+ self.expect("expression 2.234f",
+ patterns = ["\(float\) \$.* = 2\.234"])
+ # (float) $2 = 2.234
+
+ @expectedFailureWindows("llvm.org/pr21765")
+ def test_many_expr_commands(self):
+ self.build_and_run()
+
+ self.expect("expression 2",
+ patterns = ["\(int\) \$.* = 2"])
+ # (int) $0 = 1
+
+ self.expect("expression 2ull",
+ patterns = ["\(unsigned long long\) \$.* = 2"])
+ # (unsigned long long) $1 = 2
+
+ self.expect("expression 0.5f",
+ patterns = ["\(float\) \$.* = 0\.5"])
+ # (float) $2 = 0.5
+
+ self.expect("expression 2.234",
+ patterns = ["\(double\) \$.* = 2\.234"])
+ # (double) $3 = 2.234
+
+ self.expect("expression 2+3",
+ patterns = ["\(int\) \$.* = 5"])
+ # (int) $4 = 5
+
+ self.expect("expression argc",
+ patterns = ["\(int\) \$.* = 1"])
+ # (int) $5 = 1
+
+ self.expect("expression argc + 22",
+ patterns = ["\(int\) \$.* = 23"])
+ # (int) $6 = 23
+
+ self.expect("expression argv",
+ patterns = ["\(const char \*\*\) \$.* = 0x"])
+ # (const char *) $7 = ...
+
+ self.expect("expression argv[0]",
+ substrs = ["(const char *)",
+ "a.out"])
+ # (const char *) $8 = 0x... "/Volumes/data/lldb/svn/trunk/test/expression_command/test/a.out"
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureWindows # Test crashes
+ def test_evaluate_expression_python(self):
+ """Test SBFrame.EvaluateExpression() API for evaluating an expression."""
+ self.build()
+
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Create the breakpoint.
+ filespec = lldb.SBFileSpec("main.cpp", False)
+ breakpoint = target.BreakpointCreateByLocation(filespec, self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Verify the breakpoint just created.
+ self.expect(str(breakpoint), BREAKPOINT_CREATED, exe=False,
+ substrs = ['main.cpp',
+ str(self.line)])
+
+ # Launch the process, and do not stop at the entry point.
+ # Pass 'X Y Z' as the args, which makes argc == 4.
+ process = target.LaunchSimple (['X', 'Y', 'Z'], None, self.get_process_working_directory())
+
+ if not process:
+ self.fail("SBTarget.LaunchProcess() failed")
+
+ if process.GetState() != lldb.eStateStopped:
+ self.fail("Process should be in the 'stopped' state, "
+ "instead the actual state is: '%s'" %
+ lldbutil.state_type_to_str(process.GetState()))
+
+ # The stop reason of the thread should be breakpoint.
+ thread = process.GetThreadAtIndex(0)
+ if thread.GetStopReason() != lldb.eStopReasonBreakpoint:
+ from lldbsuite.test.lldbutil import stop_reason_to_str
+ self.fail(STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS %
+ stop_reason_to_str(thread.GetStopReason()))
+
+ # The filename of frame #0 should be 'main.cpp' and function is main.
+ self.expect(lldbutil.get_filenames(thread)[0],
+ "Break correctly at main.cpp", exe=False,
+ startstr = "main.cpp")
+ self.expect(lldbutil.get_function_names(thread)[0],
+ "Break correctly at main()", exe=False,
+ startstr = "main")
+
+ # We should be stopped on the breakpoint with a hit count of 1.
+ self.assertTrue(breakpoint.GetHitCount() == 1, BREAKPOINT_HIT_ONCE)
+
+ #
+ # Use Python API to evaluate expressions while stopped in a stack frame.
+ #
+ frame = thread.GetFrameAtIndex(0)
+
+ val = frame.EvaluateExpression("2.234")
+ self.expect(val.GetValue(), "2.345 evaluated correctly", exe=False,
+ startstr = "2.234")
+ self.expect(val.GetTypeName(), "2.345 evaluated correctly", exe=False,
+ startstr = "double")
+ self.DebugSBValue(val)
+
+ val = frame.EvaluateExpression("argc")
+ self.expect(val.GetValue(), "Argc evaluated correctly", exe=False,
+ startstr = "4")
+ self.DebugSBValue(val)
+
+ val = frame.EvaluateExpression("*argv[1]")
+ self.expect(val.GetValue(), "Argv[1] evaluated correctly", exe=False,
+ startstr = "'X'")
+ self.DebugSBValue(val)
+
+ val = frame.EvaluateExpression("*argv[2]")
+ self.expect(val.GetValue(), "Argv[2] evaluated correctly", exe=False,
+ startstr = "'Y'")
+ self.DebugSBValue(val)
+
+ val = frame.EvaluateExpression("*argv[3]")
+ self.expect(val.GetValue(), "Argv[3] evaluated correctly", exe=False,
+ startstr = "'Z'")
+ self.DebugSBValue(val)
+
+ callee_break = target.BreakpointCreateByName ("a_function_to_call", None)
+ self.assertTrue(callee_break.GetNumLocations() > 0)
+
+ # Make sure ignoring breakpoints works from the command line:
+ self.expect("expression -i true -- a_function_to_call()",
+ substrs = ['(int) $', ' 1'])
+ self.assertTrue (callee_break.GetHitCount() == 1)
+
+ # Now try ignoring breakpoints using the SB API's:
+ options = lldb.SBExpressionOptions()
+ options.SetIgnoreBreakpoints(True)
+ value = frame.EvaluateExpression('a_function_to_call()', options)
+ self.assertTrue (value.IsValid())
+ self.assertTrue (value.GetValueAsSigned(0) == 2)
+ self.assertTrue (callee_break.GetHitCount() == 2)
+
+ # rdar://problem/8686536
+ # CommandInterpreter::HandleCommand is stripping \'s from input for WantsRawCommand commands
+ @expectedFailureWindows("llvm.org/pr21765")
+ def test_expr_commands_can_handle_quotes(self):
+ """Throw some expression commands with quotes at lldb."""
+ self.build()
+
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line(self, "main.cpp", self.line, num_expected_locations=1,loc_exact=False)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # runCmd: expression 'a'
+ # output: (char) $0 = 'a'
+ self.expect("expression 'a'",
+ substrs = ['(char) $',
+ "'a'"])
+
+ # runCmd: expression (int) printf ("\n\n\tHello there!\n")
+ # output: (int) $1 = 16
+ self.expect(r'''expression (int) printf ("\n\n\tHello there!\n")''',
+ substrs = ['(int) $',
+ '16'])
+
+ # runCmd: expression (int) printf("\t\x68\n")
+ # output: (int) $2 = 3
+ self.expect(r'''expression (int) printf("\t\x68\n")''',
+ substrs = ['(int) $',
+ '3'])
+
+ # runCmd: expression (int) printf("\"\n")
+ # output: (int) $3 = 2
+ self.expect(r'''expression (int) printf("\"\n")''',
+ substrs = ['(int) $',
+ '2'])
+
+ # runCmd: expression (int) printf("'\n")
+ # output: (int) $4 = 2
+ self.expect(r'''expression (int) printf("'\n")''',
+ substrs = ['(int) $',
+ '2'])
+
+ # runCmd: command alias print_hi expression (int) printf ("\n\tHi!\n")
+ # output:
+ self.runCmd(r'''command alias print_hi expression (int) printf ("\n\tHi!\n")''')
+ # This fails currently.
+ self.expect('print_hi',
+ substrs = ['(int) $',
+ '6'])
diff --git a/packages/Python/lldbsuite/test/expression_command/test/TestExprs2.py b/packages/Python/lldbsuite/test/expression_command/test/TestExprs2.py
new file mode 100644
index 000000000000..578a037e9f0f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/test/TestExprs2.py
@@ -0,0 +1,60 @@
+"""
+Test some more expression commands.
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ExprCommands2TestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break for main.c.
+ self.line = line_number('main.cpp',
+ '// Please test many expressions while stopped at this line:')
+
+ @expectedFailureWindows("llvm.org/pr24489: Name lookup not working correctly on Windows")
+ def test_more_expr_commands(self):
+ """Test some more expression commands."""
+ self.build()
+
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line(self, "main.cpp", self.line, num_expected_locations=1,loc_exact=False)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Does static casting work?
+ self.expect("expression (int*)argv",
+ startstr = "(int *) $0 = 0x")
+ # (int *) $0 = 0x00007fff5fbff258
+
+ # Do anonymous symbols work?
+ self.expect("expression ((char**)environ)[0]",
+ startstr = "(char *) $1 = 0x")
+ # (char *) $1 = 0x00007fff5fbff298 "Apple_PubSub_Socket_Render=/tmp/launch-7AEsUD/Render"
+
+ # Do return values containing the contents of expression locals work?
+ self.expect("expression int i = 5; i",
+ startstr = "(int) $2 = 5")
+ # (int) $2 = 5
+ self.expect("expression $2 + 1",
+ startstr = "(int) $3 = 6")
+ # (int) $3 = 6
+
+ # Do return values containing the results of static expressions work?
+ self.expect("expression 20 + 3",
+ startstr = "(int) $4 = 23")
+ # (int) $4 = 5
+ self.expect("expression $4 + 1",
+ startstr = "(int) $5 = 24")
+ # (int) $5 = 6
diff --git a/packages/Python/lldbsuite/test/expression_command/test/main.cpp b/packages/Python/lldbsuite/test/expression_command/test/main.cpp
new file mode 100644
index 000000000000..22208a87cb44
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/test/main.cpp
@@ -0,0 +1,44 @@
+#include <stdio.h>
+
+static int static_value = 0;
+
+int
+a_function_to_call()
+{
+ static_value++;
+ return static_value;
+}
+
+int main (int argc, char const *argv[])
+{
+ printf ("Hello world!\n");
+ puts ("hello");
+ // Please test many expressions while stopped at this line:
+#if 0
+ expression 'a' // make sure character constant makes it down (this is broken: <rdar://problem/8686536>)
+ expression 2 // Test int
+ expression 2ull // Test unsigned long long
+ expression 2.234f // Test float constants
+ expression 2.234 // Test double constants
+ expression 2+3
+ expression argc
+ expression argc + 22
+ expression argv
+ expression argv[0]
+ expression argv[1]
+ expression argv[-1]
+ expression puts("bonjour") // Test constant strings...
+ expression printf("\t\x68\n") // Test constant strings that contain the \xXX (TAB, 'h', '\n' should be printed) (this is broken: <rdar://problem/8686536>)
+ expression printf("\"\n") // Test constant strings that contains an escaped double quote char (this is broken: <rdar://problem/8686536>)
+ expression printf("\'\n") // Test constant strings that contains an escaped single quote char (this is broken: <rdar://problem/8686536>)
+ expression printf ("one: %i\n", 1)
+ expression printf ("1.234 as float: %f\n", 1.234f)
+ expression printf ("1.234 as double: %g\n", 1.234)
+ expression printf ("one: %i, two: %llu\n", 1, 2ull)
+ expression printf ("two: %llu, one: %i\n", 2ull, 1)
+ expression random() % 255l
+#endif
+
+ a_function_to_call();
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/expression_command/timeout/Makefile b/packages/Python/lldbsuite/test/expression_command/timeout/Makefile
new file mode 100644
index 000000000000..c9cff412c1b2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/timeout/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := wait-a-while.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/expression_command/timeout/TestCallWithTimeout.py b/packages/Python/lldbsuite/test/expression_command/timeout/TestCallWithTimeout.py
new file mode 100644
index 000000000000..a602afc47edb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/timeout/TestCallWithTimeout.py
@@ -0,0 +1,92 @@
+"""
+Test calling a function that waits a while, and make sure the timeout option to expr works.
+"""
+
+from __future__ import print_function
+
+
+
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ExprCommandWithTimeoutsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+
+ self.main_source = "wait-a-while.cpp"
+ self.main_source_spec = lldb.SBFileSpec (self.main_source)
+
+
+ @expectedFlakeyFreeBSD("llvm.org/pr19605")
+ @expectedFlakeyLinux("llvm.org/pr20275")
+ @expectedFailureWindows("llvm.org/pr21765")
+ def test(self):
+ """Test calling std::String member function."""
+ self.build()
+
+ exe_name = "a.out"
+ exe = os.path.join(os.getcwd(), exe_name)
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateBySourceRegex('stop here in main.',self.main_source_spec)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+ self.runCmd("breakpoint list")
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Frame #0 should be on self.step_out_of_malloc.
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint)
+
+ self.assertTrue(len(threads) == 1)
+ thread = threads[0]
+
+ # First set the timeout too short, and make sure we fail.
+ options = lldb.SBExpressionOptions()
+ options.SetTimeoutInMicroSeconds(10)
+ options.SetUnwindOnError(True)
+
+ frame = thread.GetFrameAtIndex(0)
+
+ value = frame.EvaluateExpression ("wait_a_while (200000)", options)
+ self.assertTrue (value.IsValid())
+ self.assertFalse (value.GetError().Success())
+
+ # Now do the same thing with the command line command, and make sure it works too.
+ interp = self.dbg.GetCommandInterpreter()
+
+ result = lldb.SBCommandReturnObject()
+ return_value = interp.HandleCommand ("expr -t 100 -u true -- wait_a_while(200000)", result)
+ self.assertTrue (return_value == lldb.eReturnStatusFailed)
+
+ # Okay, now do it again with long enough time outs:
+
+ options.SetTimeoutInMicroSeconds(1000000)
+ value = frame.EvaluateExpression ("wait_a_while (1000)", options)
+ self.assertTrue(value.IsValid())
+ self.assertTrue (value.GetError().Success() == True)
+
+ # Now do the same thingwith the command line command, and make sure it works too.
+ interp = self.dbg.GetCommandInterpreter()
+
+ result = lldb.SBCommandReturnObject()
+ return_value = interp.HandleCommand ("expr -t 1000000 -u true -- wait_a_while(1000)", result)
+ self.assertTrue(return_value == lldb.eReturnStatusSuccessFinishResult)
+
+
+ # Finally set the one thread timeout and make sure that doesn't change things much:
+
+ options.SetTimeoutInMicroSeconds(1000000)
+ options.SetOneThreadTimeoutInMicroSeconds(500000)
+ value = frame.EvaluateExpression ("wait_a_while (1000)", options)
+ self.assertTrue(value.IsValid())
+ self.assertTrue (value.GetError().Success() == True)
diff --git a/packages/Python/lldbsuite/test/expression_command/timeout/wait-a-while.cpp b/packages/Python/lldbsuite/test/expression_command/timeout/wait-a-while.cpp
new file mode 100644
index 000000000000..ac37c5d243b2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/timeout/wait-a-while.cpp
@@ -0,0 +1,35 @@
+#include <stdio.h>
+#include <stdint.h>
+
+#include <chrono>
+#include <thread>
+
+
+int
+wait_a_while (int microseconds)
+{
+ int num_times = 0;
+ auto end_time = std::chrono::system_clock::now() + std::chrono::microseconds(microseconds);
+
+ while (1)
+ {
+ num_times++;
+ auto wait_time = end_time - std::chrono::system_clock::now();
+
+ std::this_thread::sleep_for(wait_time);
+ if (std::chrono::system_clock::now() > end_time)
+ break;
+ }
+ return num_times;
+}
+
+int
+main (int argc, char **argv)
+{
+ printf ("stop here in main.\n");
+ int num_times = wait_a_while (argc * 1000);
+ printf ("Done, took %d times.\n", num_times);
+
+ return 0;
+
+}
diff --git a/packages/Python/lldbsuite/test/expression_command/two-files/Makefile b/packages/Python/lldbsuite/test/expression_command/two-files/Makefile
new file mode 100644
index 000000000000..5974461e256f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/two-files/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../make
+
+OBJC_SOURCES := main.m foo.m
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/expression_command/two-files/TestObjCTypeQueryFromOtherCompileUnit.py b/packages/Python/lldbsuite/test/expression_command/two-files/TestObjCTypeQueryFromOtherCompileUnit.py
new file mode 100644
index 000000000000..5b0233509112
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/two-files/TestObjCTypeQueryFromOtherCompileUnit.py
@@ -0,0 +1,39 @@
+"""
+Regression test for <rdar://problem/8981098>:
+
+The expression parser's type search only looks in the current compilation unit for types.
+"""
+
+from __future__ import print_function
+
+
+
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ObjCTypeQueryTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break for main.m.
+ self.line = line_number('main.m',
+ "// Set breakpoint here, then do 'expr (NSArray*)array_token'.")
+
+ @skipUnlessDarwin
+ def test(self):
+ """The expression parser's type search should be wider than the current compilation unit."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Now do a NSArry type query from the 'main.m' compile uint.
+ self.expect("expression (NSArray*)array_token",
+ substrs = ['(NSArray *) $0 = 0x'])
+ # (NSArray *) $0 = 0x00007fff70118398
diff --git a/packages/Python/lldbsuite/test/expression_command/two-files/foo.m b/packages/Python/lldbsuite/test/expression_command/two-files/foo.m
new file mode 100644
index 000000000000..1609ebd838f6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/two-files/foo.m
@@ -0,0 +1,28 @@
+#import <Foundation/Foundation.h>
+
+NSMutableArray *
+GetArray ()
+{
+ static NSMutableArray *the_array = NULL;
+ if (the_array == NULL)
+ the_array = [[NSMutableArray alloc] init];
+ return the_array;
+}
+
+int
+AddElement (char *value)
+{
+ NSString *element = [NSString stringWithUTF8String: value];
+ int cur_elem = [GetArray() count];
+ [GetArray() addObject: element];
+ return cur_elem;
+}
+
+const char *
+GetElement (int idx)
+{
+ if (idx >= [GetArray() count])
+ return NULL;
+ else
+ return [[GetArray() objectAtIndex: idx] UTF8String];
+}
diff --git a/packages/Python/lldbsuite/test/expression_command/two-files/main.m b/packages/Python/lldbsuite/test/expression_command/two-files/main.m
new file mode 100644
index 000000000000..3f5738314e6b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/expression_command/two-files/main.m
@@ -0,0 +1,22 @@
+#import <Foundation/Foundation.h>
+#include <stdio.h>
+
+extern int AddElement (char *value);
+extern char *GetElement (int idx);
+extern void *GetArray();
+
+int
+main ()
+{
+ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+
+ int idx = AddElement ("some string");
+ void *array_token = GetArray();
+
+ char *string = GetElement (0); // Set breakpoint here, then do 'expr (NSArray*)array_token'.
+ if (string)
+ printf ("This: %s.\n", string);
+
+ [pool release];
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/abbreviation/.categories b/packages/Python/lldbsuite/test/functionalities/abbreviation/.categories
new file mode 100644
index 000000000000..3a3f4df6416b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/abbreviation/.categories
@@ -0,0 +1 @@
+cmdline
diff --git a/packages/Python/lldbsuite/test/functionalities/abbreviation/TestAbbreviations.py b/packages/Python/lldbsuite/test/functionalities/abbreviation/TestAbbreviations.py
new file mode 100644
index 000000000000..1bce5bed491f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/abbreviation/TestAbbreviations.py
@@ -0,0 +1,101 @@
+"""
+Test some lldb command abbreviations and aliases for proper resolution.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class AbbreviationsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFlakeyFreeBSD("llvm.org/pr22611 thread race condition breaks prompt setting")
+ @no_debug_info_test
+ def test_command_abbreviations_and_aliases (self):
+ command_interpreter = self.dbg.GetCommandInterpreter()
+ self.assertTrue(command_interpreter, VALID_COMMAND_INTERPRETER)
+ result = lldb.SBCommandReturnObject()
+
+ # Check that abbreviations are expanded to the full command.
+ command_interpreter.ResolveCommand("ap script", result)
+ self.assertTrue(result.Succeeded())
+ self.assertEqual("apropos script", result.GetOutput())
+
+ command_interpreter.ResolveCommand("h", result)
+ self.assertTrue(result.Succeeded())
+ self.assertEqual("help", result.GetOutput())
+
+ # Check resolution of abbreviations for multi-word commands.
+ command_interpreter.ResolveCommand("lo li", result)
+ self.assertTrue(result.Succeeded())
+ self.assertEqual("log list", result.GetOutput())
+
+ command_interpreter.ResolveCommand("br s", result)
+ self.assertTrue(result.Succeeded())
+ self.assertEqual("breakpoint set", result.GetOutput())
+
+ # Try an ambiguous abbreviation.
+ # "pl" could be "platform" or "plugin".
+ command_interpreter.ResolveCommand("pl", result)
+ self.assertFalse(result.Succeeded())
+ self.assertTrue(result.GetError().startswith("Ambiguous command"))
+
+ # Make sure an unabbreviated command is not mangled.
+ command_interpreter.ResolveCommand("breakpoint set --name main --line 123", result)
+ self.assertTrue(result.Succeeded())
+ self.assertEqual("breakpoint set --name main --line 123", result.GetOutput())
+
+ # Create some aliases.
+ self.runCmd("com a alias com al")
+ self.runCmd("alias gurp help")
+
+ # Check that an alias is replaced with the actual command
+ command_interpreter.ResolveCommand("gurp target create", result)
+ self.assertTrue(result.Succeeded())
+ self.assertEqual("help target create", result.GetOutput())
+
+ # Delete the alias and make sure it no longer has an effect.
+ self.runCmd("com u gurp")
+ command_interpreter.ResolveCommand("gurp", result)
+ self.assertFalse(result.Succeeded())
+
+ # Check aliases with text replacement.
+ self.runCmd("alias pltty process launch -s -o %1 -e %1")
+ command_interpreter.ResolveCommand("pltty /dev/tty0", result)
+ self.assertTrue(result.Succeeded())
+ self.assertEqual("process launch -s -o /dev/tty0 -e /dev/tty0", result.GetOutput())
+
+ self.runCmd("alias xyzzy breakpoint set -n %1 -l %2")
+ command_interpreter.ResolveCommand("xyzzy main 123", result)
+ self.assertTrue(result.Succeeded())
+ self.assertEqual("breakpoint set -n main -l 123", result.GetOutput().strip())
+
+ # And again, without enough parameters.
+ command_interpreter.ResolveCommand("xyzzy main", result)
+ self.assertFalse(result.Succeeded())
+
+ # Check a command that wants the raw input.
+ command_interpreter.ResolveCommand(r'''sc print("\n\n\tHello!\n")''', result)
+ self.assertTrue(result.Succeeded())
+ self.assertEqual(r'''script print("\n\n\tHello!\n")''', result.GetOutput())
+
+ # Prompt changing stuff should be tested, but this doesn't seem like the
+ # right test to do it in. It has nothing to do with aliases or abbreviations.
+ #self.runCmd("com sou ./change_prompt.lldb")
+ #self.expect("settings show prompt",
+ # startstr = 'prompt (string) = "[with-three-trailing-spaces] "')
+ #self.runCmd("settings clear prompt")
+ #self.expect("settings show prompt",
+ # startstr = 'prompt (string) = "(lldb) "')
+ #self.runCmd("se se prompt 'Sycamore> '")
+ #self.expect("se sh prompt",
+ # startstr = 'prompt (string) = "Sycamore> "')
+ #self.runCmd("se cl prompt")
+ #self.expect("set sh prompt",
+ # startstr = 'prompt (string) = "(lldb) "')
diff --git a/packages/Python/lldbsuite/test/functionalities/abbreviation/TestCommonShortSpellings.py b/packages/Python/lldbsuite/test/functionalities/abbreviation/TestCommonShortSpellings.py
new file mode 100644
index 000000000000..9edbf212278c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/abbreviation/TestCommonShortSpellings.py
@@ -0,0 +1,39 @@
+"""
+Test some lldb command abbreviations to make sure the common short spellings of
+many commands remain available even after we add/delete commands in the future.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class CommonShortSpellingsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @no_debug_info_test
+ def test_abbrevs2 (self):
+ command_interpreter = self.dbg.GetCommandInterpreter()
+ self.assertTrue(command_interpreter, VALID_COMMAND_INTERPRETER)
+ result = lldb.SBCommandReturnObject()
+
+ abbrevs = [
+ ('br s', 'breakpoint set'),
+ ('disp', '_regexp-display'), # a.k.a., 'display'
+ ('di', 'disassemble'),
+ ('dis', 'disassemble'),
+ ('ta st a', 'target stop-hook add'),
+ ('fr v', 'frame variable'),
+ ('f 1', 'frame select 1'),
+ ('ta st li', 'target stop-hook list'),
+ ]
+
+ for (short_val, long_val) in abbrevs:
+ command_interpreter.ResolveCommand(short_val, result)
+ self.assertTrue(result.Succeeded())
+ self.assertEqual(long_val, result.GetOutput())
diff --git a/packages/Python/lldbsuite/test/functionalities/alias/.categories b/packages/Python/lldbsuite/test/functionalities/alias/.categories
new file mode 100644
index 000000000000..3a3f4df6416b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/alias/.categories
@@ -0,0 +1 @@
+cmdline
diff --git a/packages/Python/lldbsuite/test/functionalities/archives/Makefile b/packages/Python/lldbsuite/test/functionalities/archives/Makefile
new file mode 100644
index 000000000000..64da83becbda
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/archives/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+MAKE_DSYM := NO
+ARCHIVE_NAME := libfoo.a
+ARCHIVE_C_SOURCES := a.c b.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/archives/README b/packages/Python/lldbsuite/test/functionalities/archives/README
new file mode 100644
index 000000000000..d327f4585c67
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/archives/README
@@ -0,0 +1,62 @@
+a.out file refers to libfoo.a for a.o and b.o, which is what we want to accomplish for
+this test case.
+
+[16:17:44] johnny:/Volumes/data/lldb/svn/latest/test/functionalities/archives $ dsymutil -s a.out
+----------------------------------------------------------------------
+Symbol table for: 'a.out' (x86_64)
+----------------------------------------------------------------------
+Index n_strx n_type n_sect n_desc n_value
+======== -------- ------------------ ------ ------ ----------------
+[ 0] 00000002 64 (N_SO ) 00 0000 0000000000000000 '/Volumes/data/lldb/svn/latest/test/functionalities/archives/'
+[ 1] 0000003f 64 (N_SO ) 00 0000 0000000000000000 'main.c'
+[ 2] 00000046 66 (N_OSO ) 03 0001 000000004f0f780c '/Volumes/data/lldb/svn/latest/test/functionalities/archives/main.o'
+[ 3] 00000001 2e (N_BNSYM ) 01 0000 0000000100000d70
+[ 4] 00000089 24 (N_FUN ) 01 0000 0000000100000d70 '_main'
+[ 5] 00000001 24 (N_FUN ) 00 0000 000000000000005d
+[ 6] 00000001 4e (N_ENSYM ) 01 0000 000000000000005d
+[ 7] 00000001 64 (N_SO ) 01 0000 0000000000000000
+[ 8] 00000002 64 (N_SO ) 00 0000 0000000000000000 '/Volumes/data/lldb/svn/latest/test/functionalities/archives/'
+[ 9] 0000008f 64 (N_SO ) 00 0000 0000000000000000 'a.c'
+[ 10] 00000093 66 (N_OSO ) 03 0001 000000004f0f780c '/Volumes/data/lldb/svn/latest/test/functionalities/archives/libfoo.a(a.o)'
+[ 11] 00000001 2e (N_BNSYM ) 01 0000 0000000100000dd0
+[ 12] 000000dd 24 (N_FUN ) 01 0000 0000000100000dd0 '_a'
+[ 13] 00000001 24 (N_FUN ) 00 0000 0000000000000020
+[ 14] 00000001 4e (N_ENSYM ) 01 0000 0000000000000020
+[ 15] 00000001 2e (N_BNSYM ) 01 0000 0000000100000df0
+[ 16] 000000e0 24 (N_FUN ) 01 0000 0000000100000df0 '_aa'
+[ 17] 00000001 24 (N_FUN ) 00 0000 0000000000000018
+[ 18] 00000001 4e (N_ENSYM ) 01 0000 0000000000000018
+[ 19] 000000e4 20 (N_GSYM ) 00 0000 0000000000000000 '___a_global'
+[ 20] 00000001 64 (N_SO ) 01 0000 0000000000000000
+[ 21] 00000002 64 (N_SO ) 00 0000 0000000000000000 '/Volumes/data/lldb/svn/latest/test/functionalities/archives/'
+[ 22] 000000f0 64 (N_SO ) 00 0000 0000000000000000 'b.c'
+[ 23] 000000f4 66 (N_OSO ) 03 0001 000000004f0f780c '/Volumes/data/lldb/svn/latest/test/functionalities/archives/libfoo.a(b.o)'
+[ 24] 00000001 2e (N_BNSYM ) 01 0000 0000000100000e10
+[ 25] 0000013e 24 (N_FUN ) 01 0000 0000000100000e10 '_b'
+[ 26] 00000001 24 (N_FUN ) 00 0000 0000000000000020
+[ 27] 00000001 4e (N_ENSYM ) 01 0000 0000000000000020
+[ 28] 00000001 2e (N_BNSYM ) 01 0000 0000000100000e30
+[ 29] 00000141 24 (N_FUN ) 01 0000 0000000100000e30 '_bb'
+[ 30] 00000001 24 (N_FUN ) 00 0000 0000000000000018
+[ 31] 00000001 4e (N_ENSYM ) 01 0000 0000000000000018
+[ 32] 00000145 26 (N_STSYM ) 0a 0000 000000010000104c '___b_global'
+[ 33] 00000001 64 (N_SO ) 01 0000 0000000000000000
+[ 34] 00000151 0e ( SECT ) 07 0000 0000000100001000 '_pvars'
+[ 35] 00000158 0e ( SECT ) 0a 0000 000000010000104c '___b_global'
+[ 36] 00000164 0f ( SECT EXT) 0b 0000 0000000100001050 '_NXArgc'
+[ 37] 0000016c 0f ( SECT EXT) 0b 0000 0000000100001058 '_NXArgv'
+[ 38] 00000174 0f ( SECT EXT) 0a 0000 0000000100001048 '___a_global'
+[ 39] 00000180 0f ( SECT EXT) 0b 0000 0000000100001068 '___progname'
+[ 40] 0000018c 03 ( ABS EXT) 01 0010 0000000100000000 '__mh_execute_header'
+[ 41] 000001a0 0f ( SECT EXT) 01 0000 0000000100000dd0 '_a'
+[ 42] 000001a3 0f ( SECT EXT) 01 0000 0000000100000df0 '_aa'
+[ 43] 000001a7 0f ( SECT EXT) 01 0000 0000000100000e10 '_b'
+[ 44] 000001aa 0f ( SECT EXT) 01 0000 0000000100000e30 '_bb'
+[ 45] 000001ae 0f ( SECT EXT) 0b 0000 0000000100001060 '_environ'
+[ 46] 000001b7 0f ( SECT EXT) 01 0000 0000000100000d70 '_main'
+[ 47] 000001bd 0f ( SECT EXT) 01 0000 0000000100000d30 'start'
+[ 48] 000001c3 01 ( UNDF EXT) 00 0100 0000000000000000 '_exit'
+[ 49] 000001c9 01 ( UNDF EXT) 00 0100 0000000000000000 '_printf'
+[ 50] 000001d1 01 ( UNDF EXT) 00 0100 0000000000000000 'dyld_stub_binder'
+
+
diff --git a/packages/Python/lldbsuite/test/functionalities/archives/TestBSDArchives.py b/packages/Python/lldbsuite/test/functionalities/archives/TestBSDArchives.py
new file mode 100644
index 000000000000..02e1b9551853
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/archives/TestBSDArchives.py
@@ -0,0 +1,57 @@
+"""Test breaking inside functions defined within a BSD archive file libfoo.a."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class BSDArchivesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number in a(int) to break at.
+ self.line = line_number('a.c', '// Set file and line breakpoint inside a().')
+
+ @expectedFailureWindows("llvm.org/pr24527") # Makefile.rules doesn't know how to build static libs on Windows.
+ def test(self):
+ """Break inside a() and b() defined within libfoo.a."""
+ self.build()
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break inside a() by file and line first.
+ lldbutil.run_break_set_by_file_and_line (self, "a.c", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Break at a(int) first.
+ self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['(int) arg = 1'])
+ self.expect("frame variable __a_global", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['(int) __a_global = 1'])
+
+ # Set breakpoint for b() next.
+ lldbutil.run_break_set_by_symbol (self, "b", num_expected_locations=1, sym_exact=True)
+
+ # Continue the program, we should break at b(int) next.
+ self.runCmd("continue")
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+ self.expect("frame variable", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['(int) arg = 2'])
+ self.expect("frame variable __b_global", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['(int) __b_global = 2'])
diff --git a/packages/Python/lldbsuite/test/functionalities/archives/a.c b/packages/Python/lldbsuite/test/functionalities/archives/a.c
new file mode 100644
index 000000000000..2b6ebbe47a76
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/archives/a.c
@@ -0,0 +1,19 @@
+//===-- a.c -----------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+int __a_global = 1;
+
+int a(int arg) {
+ int result = arg + __a_global;
+ return result; // Set file and line breakpoint inside a().
+}
+
+int aa(int arg1) {
+ int result1 = arg1 - __a_global;
+ return result1;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/archives/b.c b/packages/Python/lldbsuite/test/functionalities/archives/b.c
new file mode 100644
index 000000000000..51d77dd4bcdc
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/archives/b.c
@@ -0,0 +1,19 @@
+//===-- b.c -----------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+static int __b_global = 2;
+
+int b(int arg) {
+ int result = arg + __b_global;
+ return result;
+}
+
+int bb(int arg1) {
+ int result2 = arg1 - __b_global;
+ return result2;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/archives/main.c b/packages/Python/lldbsuite/test/functionalities/archives/main.c
new file mode 100644
index 000000000000..c5b1cc2f0d1c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/archives/main.c
@@ -0,0 +1,17 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+extern int a(int);
+extern int b(int);
+int main (int argc, char const *argv[])
+{
+ printf ("a(1) returns %d\n", a(1));
+ printf ("b(2) returns %d\n", b(2));
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/asan/Makefile b/packages/Python/lldbsuite/test/functionalities/asan/Makefile
new file mode 100644
index 000000000000..26654a023ed1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/asan/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+CFLAGS_EXTRAS := -fsanitize=address -g
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/asan/TestMemoryHistory.py b/packages/Python/lldbsuite/test/functionalities/asan/TestMemoryHistory.py
new file mode 100644
index 000000000000..e92b967d8adf
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/asan/TestMemoryHistory.py
@@ -0,0 +1,103 @@
+"""
+Test that ASan memory history provider returns correct stack traces
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class AsanTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureLinux # non-core functionality, need to reenable and fix later (DES 2014.11.07)
+ @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default
+ @skipIfRemote
+ @skipUnlessCompilerRt
+ @expectedFailureDarwin
+ def test (self):
+ self.build ()
+ self.asan_tests ()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ self.line_malloc = line_number('main.c', '// malloc line')
+ self.line_malloc2 = line_number('main.c', '// malloc2 line')
+ self.line_free = line_number('main.c', '// free line')
+ self.line_breakpoint = line_number('main.c', '// break line')
+
+ def asan_tests (self):
+ exe = os.path.join (os.getcwd(), "a.out")
+ self.expect("file " + exe, patterns = [ "Current executable set to .*a.out" ])
+
+ self.runCmd("breakpoint set -f main.c -l %d" % self.line_breakpoint)
+
+ # "memory history" command should not work without a process
+ self.expect("memory history 0",
+ error = True,
+ substrs = ["invalid process"])
+
+ self.runCmd("run")
+
+ # ASan will relaunch the process to insert its library.
+ self.expect("thread list", "Process should be stopped due to exec.",
+ substrs = ['stopped', 'stop reason = '])
+
+ self.runCmd("continue")
+
+ # the stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped', 'stop reason = breakpoint'])
+
+ # test that the ASan dylib is present
+ self.expect("image lookup -n __asan_describe_address", "__asan_describe_address should be present",
+ substrs = ['1 match found'])
+
+ # test the 'memory history' command
+ self.expect("memory history 'pointer'",
+ substrs = [
+ 'Memory allocated at', 'a.out`f1', 'main.c:%d' % self.line_malloc,
+ 'Memory deallocated at', 'a.out`f2', 'main.c:%d' % self.line_free])
+
+ # do the same using SB API
+ process = self.dbg.GetSelectedTarget().process
+ val = process.GetSelectedThread().GetSelectedFrame().EvaluateExpression("pointer")
+ addr = val.GetValueAsUnsigned()
+ threads = process.GetHistoryThreads(addr);
+ self.assertEqual(threads.GetSize(), 2)
+
+ history_thread = threads.GetThreadAtIndex(0)
+ self.assertTrue(history_thread.num_frames >= 2)
+ self.assertEqual(history_thread.frames[1].GetLineEntry().GetFileSpec().GetFilename(), "main.c")
+ self.assertEqual(history_thread.frames[1].GetLineEntry().GetLine(), self.line_free)
+
+ history_thread = threads.GetThreadAtIndex(1)
+ self.assertTrue(history_thread.num_frames >= 2)
+ self.assertEqual(history_thread.frames[1].GetLineEntry().GetFileSpec().GetFilename(), "main.c")
+ self.assertEqual(history_thread.frames[1].GetLineEntry().GetLine(), self.line_malloc)
+
+ # let's free the container (SBThreadCollection) and see if the SBThreads still live
+ threads = None
+ self.assertTrue(history_thread.num_frames >= 2)
+ self.assertEqual(history_thread.frames[1].GetLineEntry().GetFileSpec().GetFilename(), "main.c")
+ self.assertEqual(history_thread.frames[1].GetLineEntry().GetLine(), self.line_malloc)
+
+ # now let's break when an ASan report occurs and try the API then
+ self.runCmd("breakpoint set -n __asan_report_error")
+
+ self.runCmd("continue")
+
+ # the stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped', 'stop reason = breakpoint'])
+
+ # make sure the 'memory history' command still works even when we're generating a report now
+ self.expect("memory history 'another_pointer'",
+ substrs = [
+ 'Memory allocated at', 'a.out`f1', 'main.c:%d' % self.line_malloc2])
diff --git a/packages/Python/lldbsuite/test/functionalities/asan/TestReportData.py b/packages/Python/lldbsuite/test/functionalities/asan/TestReportData.py
new file mode 100644
index 000000000000..4ef587895196
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/asan/TestReportData.py
@@ -0,0 +1,79 @@
+"""
+Test the AddressSanitizer runtime support for report breakpoint and data extraction.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+import json
+
+class AsanTestReportDataCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureLinux # non-core functionality, need to reenable and fix later (DES 2014.11.07)
+ @skipIfFreeBSD # llvm.org/pr21136 runtimes not yet available by default
+ @skipIfRemote
+ @skipUnlessCompilerRt
+ @expectedFailureDarwin
+ def test(self):
+ self.build ()
+ self.asan_tests ()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ self.line_malloc = line_number('main.c', '// malloc line')
+ self.line_malloc2 = line_number('main.c', '// malloc2 line')
+ self.line_free = line_number('main.c', '// free line')
+ self.line_breakpoint = line_number('main.c', '// break line')
+ self.line_crash = line_number('main.c', '// BOOM line')
+
+ def asan_tests (self):
+ exe = os.path.join (os.getcwd(), "a.out")
+ self.expect("file " + exe, patterns = [ "Current executable set to .*a.out" ])
+ self.runCmd("run")
+
+ # ASan will relaunch the process to insert its library.
+ self.expect("thread list", "Process should be stopped due to exec.",
+ substrs = ['stopped', 'stop reason = '])
+
+ # no extended info when we have no ASan report
+ thread = self.dbg.GetSelectedTarget().process.GetSelectedThread()
+ s = lldb.SBStream()
+ self.assertFalse(thread.GetStopReasonExtendedInfoAsJSON(s))
+
+ self.runCmd("continue")
+
+ self.expect("thread list", "Process should be stopped due to ASan report",
+ substrs = ['stopped', 'stop reason = Use of deallocated memory detected'])
+
+ self.assertEqual(self.dbg.GetSelectedTarget().process.GetSelectedThread().GetStopReason(), lldb.eStopReasonInstrumentation)
+
+ self.expect("bt", "The backtrace should show the crashing line",
+ substrs = ['main.c:%d' % self.line_crash])
+
+ self.expect("thread info -s", "The extended stop info should contain the ASan provided fields",
+ substrs = ["access_size", "access_type", "address", "pc", "description", "heap-use-after-free"])
+
+ output_lines = self.res.GetOutput().split('\n')
+ json_line = output_lines[2]
+ data = json.loads(json_line)
+ self.assertEqual(data["description"], "heap-use-after-free")
+ self.assertEqual(data["instrumentation_class"], "AddressSanitizer")
+ self.assertEqual(data["stop_type"], "fatal_error")
+
+ # now let's try the SB API
+ process = self.dbg.GetSelectedTarget().process
+ thread = process.GetSelectedThread()
+
+ s = lldb.SBStream()
+ self.assertTrue(thread.GetStopReasonExtendedInfoAsJSON(s))
+ s = s.GetData()
+ data2 = json.loads(s)
+ self.assertEqual(data, data2)
diff --git a/packages/Python/lldbsuite/test/functionalities/asan/main.c b/packages/Python/lldbsuite/test/functionalities/asan/main.c
new file mode 100644
index 000000000000..fab760e49f00
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/asan/main.c
@@ -0,0 +1,34 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+#include <stdlib.h>
+
+char *pointer;
+char *another_pointer;
+
+void f1() {
+ pointer = malloc(10); // malloc line
+ another_pointer = malloc(20); // malloc2 line
+}
+
+void f2() {
+ free(pointer); // free line
+}
+
+int main (int argc, char const *argv[])
+{
+ f1();
+ f2();
+
+ printf("Hello world!\n"); // break line
+
+ pointer[0] = 'A'; // BOOM line
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/attach_resume/Makefile b/packages/Python/lldbsuite/test/functionalities/attach_resume/Makefile
new file mode 100644
index 000000000000..13d40a13b3e3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/attach_resume/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+ENABLE_THREADS := YES
+EXE := AttachResume
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/attach_resume/TestAttachResume.py b/packages/Python/lldbsuite/test/functionalities/attach_resume/TestAttachResume.py
new file mode 100644
index 000000000000..693c0a70fd62
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/attach_resume/TestAttachResume.py
@@ -0,0 +1,73 @@
+"""
+Test process attach/resume.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+exe_name = "AttachResume" # Must match Makefile
+
+class AttachResumeTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfRemote
+ @expectedFailureFreeBSD('llvm.org/pr19310')
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test_attach_continue_interrupt_detach(self):
+ """Test attach/continue/interrupt/detach"""
+ self.build()
+ self.process_attach_continue_interrupt_detach()
+
+ def process_attach_continue_interrupt_detach(self):
+ """Test attach/continue/interrupt/detach"""
+
+ exe = os.path.join(os.getcwd(), exe_name)
+
+ popen = self.spawnSubprocess(exe)
+ self.addTearDownHook(self.cleanupSubprocesses)
+
+ self.runCmd("process attach -p " + str(popen.pid))
+
+ self.setAsync(True)
+ listener = self.dbg.GetListener()
+
+ self.runCmd("c")
+ lldbutil.expect_state_changes(self, listener, [lldb.eStateRunning])
+
+ self.runCmd("process interrupt")
+ lldbutil.expect_state_changes(self, listener, [lldb.eStateStopped])
+
+ # be sure to continue/interrupt/continue (r204504)
+ self.runCmd("c")
+ lldbutil.expect_state_changes(self, listener, [lldb.eStateRunning])
+
+ self.runCmd("process interrupt")
+ lldbutil.expect_state_changes(self, listener, [lldb.eStateStopped])
+
+ # Second interrupt should have no effect.
+ self.expect("process interrupt", patterns=["Process is not running"], error=True)
+
+ # check that this breakpoint is auto-cleared on detach (r204752)
+ self.runCmd("br set -f main.cpp -l %u" % (line_number('main.cpp', '// Set breakpoint here')))
+
+ self.runCmd("c")
+ lldbutil.expect_state_changes(self, listener, [lldb.eStateRunning, lldb.eStateStopped])
+ self.expect('br list', 'Breakpoint not hit',
+ substrs = ['hit count = 1'])
+
+ # Make sure the breakpoint is not hit again.
+ self.expect("expr debugger_flag = false", substrs=[" = false"]);
+
+ self.runCmd("c")
+ lldbutil.expect_state_changes(self, listener, [lldb.eStateRunning])
+
+ # make sure to detach while in running state (r204759)
+ self.runCmd("detach")
+ lldbutil.expect_state_changes(self, listener, [lldb.eStateDetached])
diff --git a/packages/Python/lldbsuite/test/functionalities/attach_resume/main.cpp b/packages/Python/lldbsuite/test/functionalities/attach_resume/main.cpp
new file mode 100644
index 000000000000..7cf360258546
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/attach_resume/main.cpp
@@ -0,0 +1,50 @@
+#include <stdio.h>
+#include <fcntl.h>
+
+#include <chrono>
+#include <thread>
+
+#if defined(__linux__)
+#include <sys/prctl.h>
+#endif
+
+volatile bool debugger_flag = true; // The debugger will flip this to false
+
+void *start(void *data)
+{
+ int i;
+ size_t idx = (size_t)data;
+ for (i=0; i<30; i++)
+ {
+ if ( idx == 0 && debugger_flag)
+ std::this_thread::sleep_for(std::chrono::microseconds(1)); // Set breakpoint here
+ std::this_thread::sleep_for(std::chrono::seconds(1));
+ }
+ return 0;
+}
+
+int main(int argc, char const *argv[])
+{
+#if defined(__linux__)
+ // Immediately enable any ptracer so that we can allow the stub attach
+ // operation to succeed. Some Linux kernels are locked down so that
+ // only an ancestor process can be a ptracer of a process. This disables that
+ // restriction. Without it, attach-related stub tests will fail.
+#if defined(PR_SET_PTRACER) && defined(PR_SET_PTRACER_ANY)
+ // For now we execute on best effort basis. If this fails for
+ // some reason, so be it.
+ const int prctl_result = prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
+ static_cast<void> (prctl_result);
+#endif
+#endif
+
+ static const size_t nthreads = 16;
+ std::thread threads[nthreads];
+ size_t i;
+
+ for (i=0; i<nthreads; i++)
+ threads[i] = std::move(std::thread(start, (void*)i));
+
+ for (i=0; i<nthreads; i++)
+ threads[i].join();
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/Makefile b/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/TestFdLeak.py b/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/TestFdLeak.py
new file mode 100644
index 000000000000..e4bc08711f4c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/TestFdLeak.py
@@ -0,0 +1,78 @@
+"""
+Test whether a process started by lldb has no extra file descriptors open.
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+
+def python_leaky_fd_version(test):
+ import sys
+ # Python random module leaks file descriptors on some versions.
+ return sys.version_info >= (2, 7, 8) and sys.version_info < (2, 7, 10)
+
+
+class AvoidsFdLeakTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailure(python_leaky_fd_version, "bugs.freebsd.org/197376")
+ @expectedFailureFreeBSD("llvm.org/pr25624 still failing with Python 2.7.10")
+ @skipIfWindows # The check for descriptor leakage needs to be implemented differently here.
+ @skipIfTargetAndroid() # Android have some other file descriptors open by the shell
+ def test_fd_leak_basic (self):
+ self.do_test([])
+
+ @expectedFailure(python_leaky_fd_version, "bugs.freebsd.org/197376")
+ @expectedFailureFreeBSD("llvm.org/pr25624 still failing with Python 2.7.10")
+ @skipIfWindows # The check for descriptor leakage needs to be implemented differently here.
+ @skipIfTargetAndroid() # Android have some other file descriptors open by the shell
+ def test_fd_leak_log (self):
+ self.do_test(["log enable -f '/dev/null' lldb commands"])
+
+ def do_test (self, commands):
+ self.build()
+ exe = os.path.join (os.getcwd(), "a.out")
+
+ for c in commands:
+ self.runCmd(c)
+
+ target = self.dbg.CreateTarget(exe)
+
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ self.assertTrue(process.GetState() == lldb.eStateExited, "Process should have exited.")
+ self.assertTrue(process.GetExitStatus() == 0,
+ "Process returned non-zero status. Were incorrect file descriptors passed?")
+
+ @expectedFailure(python_leaky_fd_version, "bugs.freebsd.org/197376")
+ @expectedFailureFreeBSD("llvm.org/pr25624 still failing with Python 2.7.10")
+ @expectedFlakeyLinux
+ @skipIfWindows # The check for descriptor leakage needs to be implemented differently here.
+ @skipIfTargetAndroid() # Android have some other file descriptors open by the shell
+ def test_fd_leak_multitarget (self):
+ self.build()
+ exe = os.path.join (os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ breakpoint = target.BreakpointCreateBySourceRegex ('Set breakpoint here', lldb.SBFileSpec ("main.c", False))
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ process1 = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process1, PROCESS_IS_VALID)
+ self.assertTrue(process1.GetState() == lldb.eStateStopped, "Process should have been stopped.")
+
+ target2 = self.dbg.CreateTarget(exe)
+ process2 = target2.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process2, PROCESS_IS_VALID)
+
+ self.assertTrue(process2.GetState() == lldb.eStateExited, "Process should have exited.")
+ self.assertTrue(process2.GetExitStatus() == 0,
+ "Process returned non-zero status. Were incorrect file descriptors passed?")
diff --git a/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/main.c b/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/main.c
new file mode 100644
index 000000000000..5bdf227928ed
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/avoids-fd-leak/main.c
@@ -0,0 +1,28 @@
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <errno.h>
+#include <stdio.h>
+
+int
+main (int argc, char const **argv)
+{
+ struct stat buf;
+ int i, rv = 0; // Set breakpoint here.
+
+ // Make sure stdin/stdout/stderr exist.
+ for (i = 0; i <= 2; ++i) {
+ if (fstat(i, &buf) != 0)
+ return 1;
+ }
+
+ // Make sure no other file descriptors are open.
+ for (i = 3; i <= 256; ++i) {
+ if (fstat(i, &buf) == 0 || errno != EBADF) {
+ fprintf(stderr, "File descriptor %d is open.\n", i);
+ rv = 2;
+ }
+ }
+
+ return rv;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/backticks/.categories b/packages/Python/lldbsuite/test/functionalities/backticks/.categories
new file mode 100644
index 000000000000..3a3f4df6416b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/backticks/.categories
@@ -0,0 +1 @@
+cmdline
diff --git a/packages/Python/lldbsuite/test/functionalities/backticks/TestBackticksWithoutATarget.py b/packages/Python/lldbsuite/test/functionalities/backticks/TestBackticksWithoutATarget.py
new file mode 100644
index 000000000000..d31412bc783c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/backticks/TestBackticksWithoutATarget.py
@@ -0,0 +1,21 @@
+"""
+Test that backticks without a target should work (not infinite looping).
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class BackticksWithNoTargetTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @no_debug_info_test
+ def test_backticks_no_target(self):
+ """A simple test of backticks without a target."""
+ self.expect("print `1+2-3`",
+ substrs = [' = 0'])
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/Makefile b/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/Makefile
new file mode 100644
index 000000000000..6067ee45e984
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+CFLAGS_EXTRAS += -std=c99
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/TestAddressBreakpoints.py b/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/TestAddressBreakpoints.py
new file mode 100644
index 000000000000..9442a076e2a3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/TestAddressBreakpoints.py
@@ -0,0 +1,91 @@
+"""
+Test address breakpoints set with shared library of SBAddress work correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class AddressBreakpointTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test_address_breakpoints (self):
+ """Test address breakpoints set with shared library of SBAddress work correctly."""
+ self.build()
+ self.address_breakpoints()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+
+ def address_breakpoints(self):
+ """Test address breakpoints set with shared library of SBAddress work correctly."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create a breakpoint on main.c by name 'c'.
+ breakpoint = target.BreakpointCreateBySourceRegex("Set a breakpoint here", lldb.SBFileSpec("main.c"))
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Get the breakpoint location from breakpoint after we verified that,
+ # indeed, it has one location.
+ location = breakpoint.GetLocationAtIndex(0)
+ self.assertTrue(location and
+ location.IsEnabled(),
+ VALID_BREAKPOINT_LOCATION)
+
+ # Next get the address from the location, and create an address breakpoint using
+ # that address:
+
+ address = location.GetAddress()
+ target.BreakpointDelete(breakpoint.GetID())
+
+ breakpoint = target.BreakpointCreateBySBAddress(address)
+
+ # Disable ASLR. This will allow us to actually test (on platforms that support this flag)
+ # that the breakpoint was able to track the module.
+
+ launch_info = lldb.SBLaunchInfo(None)
+ flags = launch_info.GetLaunchFlags()
+ flags &= ~lldb.eLaunchFlagDisableASLR
+ launch_info.SetLaunchFlags(flags)
+
+ error = lldb.SBError()
+
+ process = target.Launch (launch_info, error)
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Did we hit our breakpoint?
+ from lldbsuite.test.lldbutil import get_threads_stopped_at_breakpoint
+ threads = get_threads_stopped_at_breakpoint (process, breakpoint)
+ self.assertTrue(len(threads) == 1, "There should be a thread stopped at our breakpoint")
+
+ # The hit count for the breakpoint should be 1.
+ self.assertTrue(breakpoint.GetHitCount() == 1)
+
+ process.Kill()
+
+ # Now re-launch and see that we hit the breakpoint again:
+ launch_info.Clear()
+ launch_info.SetLaunchFlags(flags)
+
+ process = target.Launch(launch_info, error)
+ self.assertTrue (process, PROCESS_IS_VALID)
+
+ thread = get_threads_stopped_at_breakpoint (process, breakpoint)
+ self.assertTrue(len(threads) == 1, "There should be a thread stopped at our breakpoint")
+
+ # The hit count for the breakpoint should now be 2.
+ self.assertTrue(breakpoint.GetHitCount() == 2)
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/main.c b/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/main.c
new file mode 100644
index 000000000000..6b779296e188
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/address_breakpoints/main.c
@@ -0,0 +1,8 @@
+#include <stdio.h>
+
+int
+main()
+{
+ printf ("Set a breakpoint here.\n");
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/Makefile b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/Makefile
new file mode 100644
index 000000000000..a6376f9b165d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c a.c b.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py
new file mode 100644
index 000000000000..8cf7539432ba
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommand.py
@@ -0,0 +1,206 @@
+"""
+Test lldb breakpoint command add/list/delete.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class BreakpointCommandTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @classmethod
+ def classCleanup(cls):
+ """Cleanup the test byproduct of breakpoint_command_sequence(self)."""
+ cls.RemoveTempFile("output.txt")
+ cls.RemoveTempFile("output2.txt")
+
+ @expectedFailureWindows("llvm.org/pr24528")
+ def test(self):
+ """Test a sequence of breakpoint command add, list, and delete."""
+ self.build()
+ self.breakpoint_command_sequence()
+ self.breakpoint_command_script_parameters ()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.c', '// Set break point at this line.')
+ # disable "There is a running process, kill it and restart?" prompt
+ self.runCmd("settings set auto-confirm true")
+ self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm"))
+
+ def breakpoint_command_sequence(self):
+ """Test a sequence of breakpoint command add, list, and delete."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Add three breakpoints on the same line. The first time we don't specify the file,
+ # since the default file is the one containing main:
+ lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1, loc_exact=True)
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=True)
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=True)
+ # Breakpoint 4 - set at the same location as breakpoint 1 to test setting breakpoint commands on two breakpoints at a time
+ lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1, loc_exact=True)
+
+ # Now add callbacks for the breakpoints just created.
+ self.runCmd("breakpoint command add -s command -o 'frame variable --show-types --scope' 1 4")
+ self.runCmd("breakpoint command add -s python -o 'here = open(\"output.txt\", \"w\"); here.write(\"lldb\\n\"); here.close()' 2")
+ self.runCmd("breakpoint command add --python-function bktptcmd.function 3")
+
+ # Check that the breakpoint commands are correctly set.
+
+ # The breakpoint list now only contains breakpoint 1.
+ self.expect("breakpoint list", "Breakpoints 1 & 2 created",
+ substrs = ["2: file = 'main.c', line = %d, exact_match = 0, locations = 1" % self.line],
+ patterns = ["1: file = '.*main.c', line = %d, exact_match = 0, locations = 1" % self.line] )
+
+ self.expect("breakpoint list -f", "Breakpoints 1 & 2 created",
+ substrs = ["2: file = 'main.c', line = %d, exact_match = 0, locations = 1" % self.line],
+ patterns = ["1: file = '.*main.c', line = %d, exact_match = 0, locations = 1" % self.line,
+ "1.1: .+at main.c:%d, .+unresolved, hit count = 0" % self.line,
+ "2.1: .+at main.c:%d, .+unresolved, hit count = 0" % self.line])
+
+ self.expect("breakpoint command list 1", "Breakpoint 1 command ok",
+ substrs = ["Breakpoint commands:",
+ "frame variable --show-types --scope"])
+ self.expect("breakpoint command list 2", "Breakpoint 2 command ok",
+ substrs = ["Breakpoint commands:",
+ "here = open",
+ "here.write",
+ "here.close()"])
+ self.expect("breakpoint command list 3", "Breakpoint 3 command ok",
+ substrs = ["Breakpoint commands:",
+ "bktptcmd.function(frame, bp_loc, internal_dict)"])
+
+ self.expect("breakpoint command list 4", "Breakpoint 4 command ok",
+ substrs = ["Breakpoint commands:",
+ "frame variable --show-types --scope"])
+
+ self.runCmd("breakpoint delete 4")
+
+ self.runCmd("command script import --allow-reload ./bktptcmd.py")
+
+ # Next lets try some other breakpoint kinds. First break with a regular expression
+ # and then specify only one file. The first time we should get two locations,
+ # the second time only one:
+
+ lldbutil.run_break_set_by_regexp (self, r"._MyFunction", num_expected_locations=2)
+
+ lldbutil.run_break_set_by_regexp (self, r"._MyFunction", extra_options="-f a.c", num_expected_locations=1)
+
+ lldbutil.run_break_set_by_regexp (self, r"._MyFunction", extra_options="-f a.c -f b.c", num_expected_locations=2)
+
+ # Now try a source regex breakpoint:
+ lldbutil.run_break_set_by_source_regexp (self, r"is about to return [12]0", extra_options="-f a.c -f b.c", num_expected_locations=2)
+
+ lldbutil.run_break_set_by_source_regexp (self, r"is about to return [12]0", extra_options="-f a.c", num_expected_locations=1)
+
+ # Run the program. Remove 'output.txt' if it exists.
+ self.RemoveTempFile("output.txt")
+ self.RemoveTempFile("output2.txt")
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Check that the file 'output.txt' exists and contains the string "lldb".
+
+ # The 'output.txt' file should now exist.
+ self.assertTrue(os.path.isfile("output.txt"),
+ "'output.txt' exists due to breakpoint command for breakpoint 2.")
+ self.assertTrue(os.path.isfile("output2.txt"),
+ "'output2.txt' exists due to breakpoint command for breakpoint 3.")
+
+ # Read the output file produced by running the program.
+ with open('output.txt', 'r') as f:
+ output = f.read()
+
+ self.expect(output, "File 'output.txt' and the content matches", exe=False,
+ startstr = "lldb")
+
+ with open('output2.txt', 'r') as f:
+ output = f.read()
+
+ self.expect(output, "File 'output2.txt' and the content matches", exe=False,
+ startstr = "lldb")
+
+
+ # Finish the program.
+ self.runCmd("process continue")
+
+ # Remove the breakpoint command associated with breakpoint 1.
+ self.runCmd("breakpoint command delete 1")
+
+ # Remove breakpoint 2.
+ self.runCmd("breakpoint delete 2")
+
+ self.expect("breakpoint command list 1",
+ startstr = "Breakpoint 1 does not have an associated command.")
+ self.expect("breakpoint command list 2", error=True,
+ startstr = "error: '2' is not a currently valid breakpoint id.")
+
+ # The breakpoint list now only contains breakpoint 1.
+ self.expect("breakpoint list -f", "Breakpoint 1 exists",
+ patterns = ["1: file = '.*main.c', line = %d, exact_match = 0, locations = 1, resolved = 1" %
+ self.line,
+ "hit count = 1"])
+
+ # Not breakpoint 2.
+ self.expect("breakpoint list -f", "No more breakpoint 2", matching=False,
+ substrs = ["2: file = 'main.c', line = %d, exact_match = 0, locations = 1, resolved = 1" %
+ self.line])
+
+ # Run the program again, with breakpoint 1 remaining.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # We should be stopped again due to breakpoint 1.
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 2.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_TWICE,
+ substrs = ['resolved, hit count = 2'])
+
+ def breakpoint_command_script_parameters (self):
+ """Test that the frame and breakpoint location are being properly passed to the script breakpoint command function."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Add a breakpoint.
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=True)
+
+ # Now add callbacks for the breakpoints just created.
+ self.runCmd("breakpoint command add -s python -o 'here = open(\"output-2.txt\", \"w\"); here.write(str(frame) + \"\\n\"); here.write(str(bp_loc) + \"\\n\"); here.close()' 1")
+
+ # Remove 'output-2.txt' if it already exists.
+
+ if (os.path.exists('output-2.txt')):
+ os.remove ('output-2.txt')
+
+ # Run program, hit breakpoint, and hopefully write out new version of 'output-2.txt'
+ self.runCmd ("run", RUN_SUCCEEDED)
+
+ # Check that the file 'output.txt' exists and contains the string "lldb".
+
+ # The 'output-2.txt' file should now exist.
+ self.assertTrue(os.path.isfile("output-2.txt"),
+ "'output-2.txt' exists due to breakpoint command for breakpoint 1.")
+
+ # Read the output file produced by running the program.
+ with open('output-2.txt', 'r') as f:
+ output = f.read()
+
+ self.expect (output, "File 'output-2.txt' and the content matches", exe=False,
+ startstr = "frame #0:",
+ patterns = ["1.* where = .*main .* resolved, hit count = 1" ])
+
+ # Now remove 'output-2.txt'
+ os.remove ('output-2.txt')
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommandsFromPython.py b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommandsFromPython.py
new file mode 100644
index 000000000000..7a9cc744d528
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestBreakpointCommandsFromPython.py
@@ -0,0 +1,95 @@
+"""
+Test that you can set breakpoint commands successfully with the Python API's:
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+import sys
+from lldbsuite.test.lldbtest import *
+
+class PythonBreakpointCommandSettingTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+ my_var = 10
+
+ @add_test_categories(['pyapi'])
+ def test_step_out_python(self):
+ """Test stepping out using avoid-no-debug with dsyms."""
+ self.build()
+ self.do_set_python_command_from_python ()
+
+ def setUp (self):
+ TestBase.setUp(self)
+ self.main_source = "main.c"
+ self.main_source_spec = lldb.SBFileSpec(self.main_source)
+
+
+ def do_set_python_command_from_python (self):
+ exe = os.path.join(os.getcwd(), "a.out")
+ error = lldb.SBError()
+
+ self.target = self.dbg.CreateTarget(exe)
+ self.assertTrue(self.target, VALID_TARGET)
+
+ body_bkpt = self.target.BreakpointCreateBySourceRegex("Set break point at this line.", self.main_source_spec)
+ self.assertTrue(body_bkpt, VALID_BREAKPOINT)
+
+ func_bkpt = self.target.BreakpointCreateBySourceRegex("Set break point at this line.", self.main_source_spec)
+ self.assertTrue(func_bkpt, VALID_BREAKPOINT)
+
+ # Also test that setting a source regex breakpoint with an empty file spec list sets it on all files:
+ no_files_bkpt = self.target.BreakpointCreateBySourceRegex("Set a breakpoint here", lldb.SBFileSpecList(), lldb.SBFileSpecList())
+ self.assertTrue(no_files_bkpt, VALID_BREAKPOINT)
+ num_locations = no_files_bkpt.GetNumLocations()
+ self.assertTrue(num_locations >= 2, "Got at least two breakpoint locations")
+ got_one_in_A = False
+ got_one_in_B = False
+ for idx in range(0, num_locations):
+ comp_unit = no_files_bkpt.GetLocationAtIndex(idx).GetAddress().GetSymbolContext(lldb.eSymbolContextCompUnit).GetCompileUnit().GetFileSpec()
+ print("Got comp unit: ", comp_unit.GetFilename())
+ if comp_unit.GetFilename() == "a.c":
+ got_one_in_A = True
+ elif comp_unit.GetFilename() == "b.c":
+ got_one_in_B = True
+
+ self.assertTrue(got_one_in_A, "Failed to match the pattern in A")
+ self.assertTrue(got_one_in_B, "Failed to match the pattern in B")
+ self.target.BreakpointDelete(no_files_bkpt.GetID())
+
+ PythonBreakpointCommandSettingTestCase.my_var = 10
+ error = lldb.SBError()
+ error = body_bkpt.SetScriptCallbackBody("\
+import TestBreakpointCommandsFromPython\n\
+TestBreakpointCommandsFromPython.PythonBreakpointCommandSettingTestCase.my_var = 20\n\
+print('Hit breakpoint')")
+ self.assertTrue (error.Success(), "Failed to set the script callback body: %s."%(error.GetCString()))
+
+ self.dbg.HandleCommand("command script import --allow-reload ./bktptcmd.py")
+ func_bkpt.SetScriptCallbackFunction("bktptcmd.function")
+
+ # We will use the function that touches a text file, so remove it first:
+ self.RemoveTempFile("output2.txt")
+
+ # Now launch the process, and do not stop at entry point.
+ self.process = self.target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(self.process, PROCESS_IS_VALID)
+
+ # Now finish, and make sure the return value is correct.
+ threads = lldbutil.get_threads_stopped_at_breakpoint (self.process, body_bkpt)
+ self.assertTrue(len(threads) == 1, "Stopped at inner breakpoint.")
+ self.thread = threads[0]
+
+ self.assertTrue(PythonBreakpointCommandSettingTestCase.my_var == 20)
+
+ # Check for the function version as well, which produced this file:
+ # Remember to clean up after ourselves...
+ self.assertTrue(os.path.isfile("output2.txt"),
+ "'output2.txt' exists due to breakpoint command for breakpoint function.")
+ self.RemoveTempFile("output2.txt")
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestRegexpBreakCommand.py b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestRegexpBreakCommand.py
new file mode 100644
index 000000000000..1ea71cbde45c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/TestRegexpBreakCommand.py
@@ -0,0 +1,51 @@
+"""
+Test _regexp-break command which uses regular expression matching to dispatch to other built in breakpoint commands.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class RegexpBreakCommandTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test(self):
+ """Test _regexp-break command."""
+ self.build()
+ self.regexp_break_command()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.source = 'main.c'
+ self.line = line_number(self.source, '// Set break point at this line.')
+
+ def regexp_break_command(self):
+ """Test the super consie "b" command, which is analias for _regexp-break."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ break_results = lldbutil.run_break_set_command (self, "b %d" % self.line)
+ lldbutil.check_breakpoint_result (self, break_results, file_name='main.c', line_number=self.line, num_locations=1)
+
+ break_results = lldbutil.run_break_set_command (self, "b %s:%d" % (self.source, self.line))
+ lldbutil.check_breakpoint_result (self, break_results, file_name='main.c', line_number=self.line, num_locations=1)
+
+ # Check breakpoint with full file path.
+ full_path = os.path.join(os.getcwd(), self.source)
+ break_results = lldbutil.run_break_set_command (self, "b %s:%d" % (full_path, self.line))
+ lldbutil.check_breakpoint_result (self, break_results, file_name='main.c', line_number=self.line, num_locations=1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/a.c b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/a.c
new file mode 100644
index 000000000000..870e4a6ab166
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/a.c
@@ -0,0 +1,9 @@
+#include <stdio.h>
+
+int
+a_MyFunction ()
+{
+ // Set a breakpoint here.
+ printf ("a is about to return 10.\n");
+ return 10;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/b.c b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/b.c
new file mode 100644
index 000000000000..02b78e7bd855
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/b.c
@@ -0,0 +1,9 @@
+#include <stdio.h>
+
+int
+b_MyFunction ()
+{
+ // Set a breakpoint here.
+ printf ("b is about to return 20.\n");
+ return 20;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/bktptcmd.py b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/bktptcmd.py
new file mode 100644
index 000000000000..4bbb0327eacd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/bktptcmd.py
@@ -0,0 +1,6 @@
+from __future__ import print_function
+
+def function(frame, bp_loc, dict):
+ there = open("output2.txt", "w");
+ print("lldb", file=there)
+ there.close()
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/main.c b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/main.c
new file mode 100644
index 000000000000..62ec97f43284
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_command/main.c
@@ -0,0 +1,13 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+int main (int argc, char const *argv[])
+{
+ return 0; // Set break point at this line.
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/Makefile b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/Makefile
new file mode 100644
index 000000000000..6067ee45e984
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+CFLAGS_EXTRAS += -std=c99
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/TestBreakpointConditions.py b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/TestBreakpointConditions.py
new file mode 100644
index 000000000000..8c22c8fe869c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/TestBreakpointConditions.py
@@ -0,0 +1,181 @@
+"""
+Test breakpoint conditions with 'breakpoint modify -c <expr> id'.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class BreakpointConditionsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfWindows # Requires EE to support COFF on Windows (http://llvm.org/pr22232)
+ def test_breakpoint_condition_and_run_command(self):
+ """Exercise breakpoint condition with 'breakpoint modify -c <expr> id'."""
+ self.build()
+ self.breakpoint_conditions()
+
+ @skipIfWindows # Requires EE to support COFF on Windows (http://llvm.org/pr22232)
+ def test_breakpoint_condition_inline_and_run_command(self):
+ """Exercise breakpoint condition inline with 'breakpoint set'."""
+ self.build()
+ self.breakpoint_conditions(inline=True)
+
+ @skipIfWindows # Requires EE to support COFF on Windows (http://llvm.org/pr22232)
+ @add_test_categories(['pyapi'])
+ def test_breakpoint_condition_and_python_api(self):
+ """Use Python APIs to set breakpoint conditions."""
+ self.build()
+ self.breakpoint_conditions_python()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to of function 'c'.
+ self.line1 = line_number('main.c', '// Find the line number of function "c" here.')
+ self.line2 = line_number('main.c', "// Find the line number of c's parent call here.")
+
+ def breakpoint_conditions(self, inline=False):
+ """Exercise breakpoint condition with 'breakpoint modify -c <expr> id'."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ if inline:
+ # Create a breakpoint by function name 'c' and set the condition.
+ lldbutil.run_break_set_by_symbol (self, "c", extra_options="-c 'val == 3'", num_expected_locations=1, sym_exact=True)
+ else:
+ # Create a breakpoint by function name 'c'.
+ lldbutil.run_break_set_by_symbol (self, "c", num_expected_locations=1, sym_exact=True)
+
+ # And set a condition on the breakpoint to stop on when 'val == 3'.
+ self.runCmd("breakpoint modify -c 'val == 3' 1")
+
+ # Now run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The process should be stopped at this point.
+ self.expect("process status", PROCESS_STOPPED,
+ patterns = ['Process .* stopped'])
+
+ # 'frame variable --show-types val' should return 3 due to breakpoint condition.
+ self.expect("frame variable --show-types val", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = '(int) val = 3')
+
+ # Also check the hit count, which should be 3, by design.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = ["resolved = 1",
+ "Condition: val == 3",
+ "hit count = 1"])
+
+ # The frame #0 should correspond to main.c:36, the executable statement
+ # in function name 'c'. And the parent frame should point to main.c:24.
+ self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT_CONDITION,
+ #substrs = ["stop reason = breakpoint"],
+ patterns = ["frame #0.*main.c:%d" % self.line1,
+ "frame #1.*main.c:%d" % self.line2])
+
+ # Test that "breakpoint modify -c ''" clears the condition for the last
+ # created breakpoint, so that when the breakpoint hits, val == 1.
+ self.runCmd("process kill")
+ self.runCmd("breakpoint modify -c ''")
+ self.expect("breakpoint list -f", BREAKPOINT_STATE_CORRECT, matching=False,
+ substrs = ["Condition:"])
+
+ # Now run the program again.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The process should be stopped at this point.
+ self.expect("process status", PROCESS_STOPPED,
+ patterns = ['Process .* stopped'])
+
+ # 'frame variable --show-types val' should return 1 since it is the first breakpoint hit.
+ self.expect("frame variable --show-types val", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = '(int) val = 1')
+
+ self.runCmd("process kill")
+ self.runCmd("breakpoint disable")
+
+ self.runCmd("breakpoint set -p Loop")
+ arch = self.getArchitecture()
+ if arch in ['x86_64', 'i386']:
+ self.runCmd("breakpoint modify -c ($eax&&i)")
+ elif arch in ['aarch64']:
+ self.runCmd("breakpoint modify -c ($x1&&i)")
+ elif arch in ['arm']:
+ self.runCmd("breakpoint modify -c ($r0&&i)")
+ elif re.match("mips",arch):
+ self.runCmd("breakpoint modify -c ($r2&&i)")
+ self.runCmd("run")
+
+ self.expect("process status", PROCESS_STOPPED,
+ patterns = ['Process .* stopped'])
+
+ self.runCmd("continue")
+
+ self.expect("process status", PROCESS_EXITED,
+ patterns = ['Process .* exited'])
+
+ def breakpoint_conditions_python(self):
+ """Use Python APIs to set breakpoint conditions."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create a breakpoint on main.c by name 'c'.
+ breakpoint = target.BreakpointCreateByName('c', 'a.out')
+ #print("breakpoint:", breakpoint)
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # We didn't associate a thread index with the breakpoint, so it should be invalid.
+ self.assertTrue(breakpoint.GetThreadIndex() == lldb.UINT32_MAX,
+ "The thread index should be invalid")
+ # The thread name should be invalid, too.
+ self.assertTrue(breakpoint.GetThreadName() is None,
+ "The thread name should be invalid")
+
+ # Let's set the thread index for this breakpoint and verify that it is,
+ # indeed, being set correctly.
+ breakpoint.SetThreadIndex(1) # There's only one thread for the process.
+ self.assertTrue(breakpoint.GetThreadIndex() == 1,
+ "The thread index has been set correctly")
+
+ # Get the breakpoint location from breakpoint after we verified that,
+ # indeed, it has one location.
+ location = breakpoint.GetLocationAtIndex(0)
+ self.assertTrue(location and
+ location.IsEnabled(),
+ VALID_BREAKPOINT_LOCATION)
+
+ # Set the condition on the breakpoint location.
+ location.SetCondition('val == 3')
+ self.expect(location.GetCondition(), exe=False,
+ startstr = 'val == 3')
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Frame #0 should be on self.line1 and the break condition should hold.
+ from lldbsuite.test.lldbutil import get_stopped_thread
+ thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
+ frame0 = thread.GetFrameAtIndex(0)
+ var = frame0.FindValue('val', lldb.eValueTypeVariableArgument)
+ self.assertTrue(frame0.GetLineEntry().GetLine() == self.line1 and
+ var.GetValue() == '3')
+
+ # The hit count for the breakpoint should be 1.
+ self.assertTrue(breakpoint.GetHitCount() == 1)
+
+ process.Continue()
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/main.c b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/main.c
new file mode 100644
index 000000000000..1aa8235e1b0c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_conditions/main.c
@@ -0,0 +1,54 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+// This simple program is to demonstrate the capability of the lldb command
+// "breakpoint modify -c 'val == 3' breakpt-id" to break within c(int val) only
+// when the value of the arg is 3.
+
+int a(int);
+int b(int);
+int c(int);
+
+int a(int val)
+{
+ if (val <= 1)
+ return b(val);
+ else if (val >= 3)
+ return c(val); // Find the line number of c's parent call here.
+
+ return val;
+}
+
+int b(int val)
+{
+ return c(val);
+}
+
+int c(int val)
+{
+ return val + 3; // Find the line number of function "c" here.
+}
+
+int main (int argc, char const *argv[])
+{
+ int A1 = a(1); // a(1) -> b(1) -> c(1)
+ printf("a(1) returns %d\n", A1);
+
+ int B2 = b(2); // b(2) -> c(2)
+ printf("b(2) returns %d\n", B2);
+
+ int A3 = a(3); // a(3) -> c(3)
+ printf("a(3) returns %d\n", A3);
+
+ for (int i = 0; i < 2; ++i)
+ printf("Loop\n");
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/Makefile b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/Makefile
new file mode 100644
index 000000000000..f89b52a972e9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+ifneq (,$(findstring icc,$(CC)))
+ CXXFLAGS += -debug inline-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/TestBreakpointIDs.py b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/TestBreakpointIDs.py
new file mode 100644
index 000000000000..b7edf2a6e4d5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/TestBreakpointIDs.py
@@ -0,0 +1,51 @@
+"""
+Test lldb breakpoint ids.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class BreakpointIDTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test (self):
+ self.build()
+
+ exe = os.path.join (os.getcwd(), "a.out")
+ self.expect("file " + exe,
+ patterns = [ "Current executable set to .*a.out" ])
+
+
+ bpno = lldbutil.run_break_set_by_symbol (self, 'product', num_expected_locations=-1, sym_exact=False)
+ self.assertTrue (bpno == 1, "First breakpoint number is 1.")
+
+ bpno = lldbutil.run_break_set_by_symbol (self, 'sum', num_expected_locations=-1, sym_exact=False)
+ self.assertTrue (bpno == 2, "Second breakpoint number is 2.")
+
+ bpno = lldbutil.run_break_set_by_symbol (self, 'junk', num_expected_locations=0, sym_exact=False)
+ self.assertTrue (bpno == 3, "Third breakpoint number is 3.")
+
+ self.expect ("breakpoint disable 1.1 - 2.2 ",
+ COMMAND_FAILED_AS_EXPECTED, error = True,
+ startstr = "error: Invalid range: Ranges that specify particular breakpoint locations must be within the same major breakpoint; you specified two different major breakpoints, 1 and 2.")
+
+ self.expect ("breakpoint disable 2 - 2.2",
+ COMMAND_FAILED_AS_EXPECTED, error = True,
+ startstr = "error: Invalid breakpoint id range: Either both ends of range must specify a breakpoint location, or neither can specify a breakpoint location.")
+
+ self.expect ("breakpoint disable 2.1 - 2",
+ COMMAND_FAILED_AS_EXPECTED, error = True,
+ startstr = "error: Invalid breakpoint id range: Either both ends of range must specify a breakpoint location, or neither can specify a breakpoint location.")
+
+ self.expect ("breakpoint disable 2.1 - 2.2",
+ startstr = "2 breakpoints disabled.")
+
+ self.expect ("breakpoint enable 2.*",
+ patterns = [ ".* breakpoints enabled."] )
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/main.cpp b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/main.cpp
new file mode 100644
index 000000000000..3deef22c93c8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ids/main.cpp
@@ -0,0 +1,65 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <cstdlib>
+#include <string>
+#include <fstream>
+#include <iostream>
+
+
+#define INLINE inline __attribute__((always_inline))
+
+INLINE int
+product (int x, int y)
+{
+ int result = x * y;
+ return result;
+}
+
+INLINE int
+sum (int a, int b)
+{
+ int result = a + b;
+ return result;
+}
+
+int
+strange_max (int m, int n)
+{
+ if (m > n)
+ return m;
+ else if (n > m)
+ return n;
+ else
+ return 0;
+}
+
+int
+foo (int i, int j)
+{
+ if (strange_max (i, j) == i)
+ return product (i, j);
+ else if (strange_max (i, j) == j)
+ return sum (i, j);
+ else
+ return product (sum (i, i), sum (j, j));
+}
+
+int
+main(int argc, char const *argv[])
+{
+
+ int array[3];
+
+ array[0] = foo (1238, 78392);
+ array[1] = foo (379265, 23674);
+ array[2] = foo (872934, 234);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/Makefile b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/TestBreakpointIgnoreCount.py b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/TestBreakpointIgnoreCount.py
new file mode 100644
index 000000000000..8a83cb627f7a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/TestBreakpointIgnoreCount.py
@@ -0,0 +1,136 @@
+"""
+Test breakpoint ignore count features.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class BreakpointIgnoreCountTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test_with_run_command(self):
+ """Exercise breakpoint ignore count with 'breakpoint set -i <count>'."""
+ self.build()
+ self.breakpoint_ignore_count()
+
+ @add_test_categories(['pyapi'])
+ def test_with_python_api(self):
+ """Use Python APIs to set breakpoint ignore count."""
+ self.build()
+ self.breakpoint_ignore_count_python()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to of function 'c'.
+ self.line1 = line_number('main.c', '// Find the line number of function "c" here.')
+ self.line2 = line_number('main.c', '// b(2) -> c(2) Find the call site of b(2).')
+ self.line3 = line_number('main.c', '// a(3) -> c(3) Find the call site of c(3).')
+ self.line4 = line_number('main.c', '// a(3) -> c(3) Find the call site of a(3).')
+ self.line5 = line_number('main.c', '// Find the call site of c in main.')
+
+ def breakpoint_ignore_count(self):
+ """Exercise breakpoint ignore count with 'breakpoint set -i <count>'."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Create a breakpoint in main.c at line1.
+ lldbutil.run_break_set_by_file_and_line (self, 'main.c', self.line1, extra_options='-i 1', num_expected_locations=1, loc_exact=True)
+
+ # Now run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The process should be stopped at this point.
+ self.expect("process status", PROCESS_STOPPED,
+ patterns = ['Process .* stopped'])
+
+ # Also check the hit count, which should be 2, due to ignore count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_THRICE,
+ substrs = ["resolved = 1",
+ "hit count = 2"])
+
+ # The frame #0 should correspond to main.c:37, the executable statement
+ # in function name 'c'. And frame #2 should point to main.c:45.
+ self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT,
+ #substrs = ["stop reason = breakpoint"],
+ patterns = ["frame #0.*main.c:%d" % self.line1,
+ "frame #2.*main.c:%d" % self.line2])
+
+ # continue -i 1 is the same as setting the ignore count to 1 again, try that:
+ # Now run the program.
+ self.runCmd("process continue -i 1", RUN_SUCCEEDED)
+
+ # The process should be stopped at this point.
+ self.expect("process status", PROCESS_STOPPED,
+ patterns = ['Process .* stopped'])
+
+ # Also check the hit count, which should be 2, due to ignore count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_THRICE,
+ substrs = ["resolved = 1",
+ "hit count = 4"])
+
+ # The frame #0 should correspond to main.c:37, the executable statement
+ # in function name 'c'. And frame #2 should point to main.c:45.
+ self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT,
+ #substrs = ["stop reason = breakpoint"],
+ patterns = ["frame #0.*main.c:%d" % self.line1,
+ "frame #1.*main.c:%d" % self.line5])
+
+
+
+ def breakpoint_ignore_count_python(self):
+ """Use Python APIs to set breakpoint ignore count."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create a breakpoint on main.c by name 'c'.
+ breakpoint = target.BreakpointCreateByName('c', 'a.out')
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Get the breakpoint location from breakpoint after we verified that,
+ # indeed, it has one location.
+ location = breakpoint.GetLocationAtIndex(0)
+ self.assertTrue(location and
+ location.IsEnabled(),
+ VALID_BREAKPOINT_LOCATION)
+
+ # Set the ignore count on the breakpoint location.
+ location.SetIgnoreCount(2)
+ self.assertTrue(location.GetIgnoreCount() == 2,
+ "SetIgnoreCount() works correctly")
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Frame#0 should be on main.c:37, frame#1 should be on main.c:25, and
+ # frame#2 should be on main.c:48.
+ #lldbutil.print_stacktraces(process)
+ from lldbsuite.test.lldbutil import get_stopped_thread
+ thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint")
+ frame0 = thread.GetFrameAtIndex(0)
+ frame1 = thread.GetFrameAtIndex(1)
+ frame2 = thread.GetFrameAtIndex(2)
+ self.assertTrue(frame0.GetLineEntry().GetLine() == self.line1 and
+ frame1.GetLineEntry().GetLine() == self.line3 and
+ frame2.GetLineEntry().GetLine() == self.line4,
+ STOPPED_DUE_TO_BREAKPOINT_IGNORE_COUNT)
+
+ # The hit count for the breakpoint should be 3.
+ self.assertTrue(breakpoint.GetHitCount() == 3)
+
+ process.Continue()
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/main.c b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/main.c
new file mode 100644
index 000000000000..b74b37b48b08
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_ignore_count/main.c
@@ -0,0 +1,54 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+// This simple program is to demonstrate the capability of the lldb command
+// "breakpoint modify -i <count> breakpt-id" to set the number of times a
+// breakpoint is skipped before stopping. Ignore count can also be set upon
+// breakpoint creation by 'breakpoint set ... -i <count>'.
+
+int a(int);
+int b(int);
+int c(int);
+
+int a(int val)
+{
+ if (val <= 1)
+ return b(val);
+ else if (val >= 3)
+ return c(val); // a(3) -> c(3) Find the call site of c(3).
+
+ return val;
+}
+
+int b(int val)
+{
+ return c(val);
+}
+
+int c(int val)
+{
+ return val + 3; // Find the line number of function "c" here.
+}
+
+int main (int argc, char const *argv[])
+{
+ int A1 = a(1); // a(1) -> b(1) -> c(1)
+ printf("a(1) returns %d\n", A1);
+
+ int B2 = b(2); // b(2) -> c(2) Find the call site of b(2).
+ printf("b(2) returns %d\n", B2);
+
+ int A3 = a(3); // a(3) -> c(3) Find the call site of a(3).
+ printf("a(3) returns %d\n", A3);
+
+ int C1 = c(5); // Find the call site of c in main.
+ printf ("c(5) returns %d\n", C1);
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/Makefile b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/Makefile
new file mode 100644
index 000000000000..4f6b058fa324
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+C_SOURCES := a.c
+CXX_SOURCES := main.cpp b.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/TestBreakpointLanguage.py b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/TestBreakpointLanguage.py
new file mode 100644
index 000000000000..94fc7bf79f63
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/TestBreakpointLanguage.py
@@ -0,0 +1,85 @@
+"""
+Test that the language option for breakpoints works correctly
+parser.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+import shutil
+import subprocess
+
+class TestBreakpointLanguage(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+
+ def check_location_file (self, bp, loc, test_name):
+ bp_loc = bp.GetLocationAtIndex(loc)
+ addr = bp_loc.GetAddress()
+ comp_unit = addr.GetCompileUnit()
+ comp_name = comp_unit.GetFileSpec().GetFilename()
+ return comp_name == test_name
+
+ def test_regex_breakpoint_language(self):
+ """Test that the name regex breakpoint commands obey the language filter."""
+
+ self.build()
+ # Create a target by the debugger.
+ exe = os.path.join(os.getcwd(), "a.out")
+ error = lldb.SBError()
+ # Don't read in dependencies so we don't come across false matches that
+ # add unwanted breakpoint hits.
+ self.target = self.dbg.CreateTarget(exe, None, None, False, error)
+ self.assertTrue(self.target, VALID_TARGET)
+
+ cpp_bp = self.target.BreakpointCreateByRegex("func_from", lldb.eLanguageTypeC_plus_plus, lldb.SBFileSpecList(), lldb.SBFileSpecList())
+ self.assertTrue(cpp_bp.GetNumLocations() == 1, "Only one C++ symbol matches")
+ self.assertTrue(self.check_location_file(cpp_bp, 0, "b.cpp"))
+
+ c_bp = self.target.BreakpointCreateByRegex("func_from", lldb.eLanguageTypeC, lldb.SBFileSpecList(), lldb.SBFileSpecList())
+ self.assertTrue(c_bp.GetNumLocations() == 1, "Only one C symbol matches")
+ self.assertTrue(self.check_location_file(c_bp, 0, "a.c"))
+
+ objc_bp = self.target.BreakpointCreateByRegex("func_from", lldb.eLanguageTypeObjC, lldb.SBFileSpecList(), lldb.SBFileSpecList())
+ self.assertTrue(objc_bp.GetNumLocations() == 0, "No ObjC symbol matches")
+
+ def test_by_name_breakpoint_language(self):
+ """Test that the name regex breakpoint commands obey the language filter."""
+
+ self.build()
+ # Create a target by the debugger.
+ exe = os.path.join(os.getcwd(), "a.out")
+ error = lldb.SBError()
+ # Don't read in dependencies so we don't come across false matches that
+ # add unwanted breakpoint hits.
+ self.target = self.dbg.CreateTarget(exe, None, None, False, error)
+ self.assertTrue(self.target, VALID_TARGET)
+
+ cpp_bp = self.target.BreakpointCreateByName("func_from_cpp", lldb.eFunctionNameTypeAuto, lldb.eLanguageTypeC_plus_plus, lldb.SBFileSpecList(), lldb.SBFileSpecList())
+ self.assertTrue(cpp_bp.GetNumLocations() == 1, "Only one C++ symbol matches")
+ self.assertTrue(self.check_location_file(cpp_bp, 0, "b.cpp"))
+
+ no_cpp_bp = self.target.BreakpointCreateByName("func_from_c", lldb.eFunctionNameTypeAuto, lldb.eLanguageTypeC_plus_plus, lldb.SBFileSpecList(), lldb.SBFileSpecList())
+ self.assertTrue(no_cpp_bp.GetNumLocations() == 0, "And the C one doesn't match")
+
+ c_bp = self.target.BreakpointCreateByName("func_from_c", lldb.eFunctionNameTypeAuto, lldb.eLanguageTypeC, lldb.SBFileSpecList(), lldb.SBFileSpecList())
+ self.assertTrue(c_bp.GetNumLocations() == 1, "Only one C symbol matches")
+ self.assertTrue(self.check_location_file(c_bp, 0, "a.c"))
+
+ no_c_bp = self.target.BreakpointCreateByName("func_from_cpp", lldb.eFunctionNameTypeAuto, lldb.eLanguageTypeC, lldb.SBFileSpecList(), lldb.SBFileSpecList())
+ self.assertTrue(no_c_bp.GetNumLocations() == 0, "And the C++ one doesn't match")
+
+ objc_bp = self.target.BreakpointCreateByName("func_from_cpp", lldb.eFunctionNameTypeAuto, lldb.eLanguageTypeObjC, lldb.SBFileSpecList(), lldb.SBFileSpecList())
+ self.assertTrue(objc_bp.GetNumLocations() == 0, "No ObjC symbol matches")
+
+
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/a.c b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/a.c
new file mode 100644
index 000000000000..b90e2bdcca5d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/a.c
@@ -0,0 +1,5 @@
+int
+func_from_c ()
+{
+ return 5;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/b.cpp b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/b.cpp
new file mode 100644
index 000000000000..89373445b9aa
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/b.cpp
@@ -0,0 +1,5 @@
+int
+func_from_cpp()
+{
+ return 10;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/main.cpp b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/main.cpp
new file mode 100644
index 000000000000..b7d00a602029
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_language/main.cpp
@@ -0,0 +1,11 @@
+#include <stdio.h>
+extern "C" int func_from_c();
+extern int func_from_cpp();
+
+int
+main()
+{
+ func_from_c();
+ func_from_cpp();
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/Makefile b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/Makefile
new file mode 100644
index 000000000000..7934cd5db427
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+ifneq (,$(findstring icc,$(CC)))
+ CFLAGS += -debug inline-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/TestBreakpointLocations.py b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/TestBreakpointLocations.py
new file mode 100644
index 000000000000..5c4dc219a106
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/TestBreakpointLocations.py
@@ -0,0 +1,88 @@
+"""
+Test breakpoint commands for a breakpoint ID with multiple locations.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class BreakpointLocationsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureWindows("llvm.org/pr24528")
+ @expectedFailureAll(oslist=["linux"], compiler="clang", compiler_version=["=", "3.8"], archs=["i386"], debug_info="dwo")
+ def test(self):
+ """Test breakpoint enable/disable for a breakpoint ID with multiple locations."""
+ self.build()
+ self.breakpoint_locations_test()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.c', '// Set break point at this line.')
+
+ def breakpoint_locations_test(self):
+ """Test breakpoint enable/disable for a breakpoint ID with multiple locations."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # This should create a breakpoint with 3 locations.
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=3)
+
+ # The breakpoint list should show 3 locations.
+ self.expect("breakpoint list -f", "Breakpoint locations shown correctly",
+ substrs = ["1: file = 'main.c', line = %d, exact_match = 0, locations = 3" % self.line],
+ patterns = ["where = a.out`func_inlined .+unresolved, hit count = 0",
+ "where = a.out`main .+\[inlined\].+unresolved, hit count = 0"])
+
+ # The 'breakpoint disable 3.*' command should fail gracefully.
+ self.expect("breakpoint disable 3.*",
+ "Disabling an invalid breakpoint should fail gracefully",
+ error=True,
+ startstr = "error: '3' is not a valid breakpoint ID.")
+
+ # The 'breakpoint disable 1.*' command should disable all 3 locations.
+ self.expect("breakpoint disable 1.*", "All 3 breakpoint locatons disabled correctly",
+ startstr = "3 breakpoints disabled.")
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # We should not stopped on any breakpoint at all.
+ self.expect("process status", "No stopping on any disabled breakpoint",
+ patterns = ["^Process [0-9]+ exited with status = 0"])
+
+ # The 'breakpoint enable 1.*' command should enable all 3 breakpoints.
+ self.expect("breakpoint enable 1.*", "All 3 breakpoint locatons enabled correctly",
+ startstr = "3 breakpoints enabled.")
+
+ # The 'breakpoint disable 1.1' command should disable 1 location.
+ self.expect("breakpoint disable 1.1", "1 breakpoint locatons disabled correctly",
+ startstr = "1 breakpoints disabled.")
+
+ # Run the program againt. We should stop on the two breakpoint locations.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Stopped once.
+ self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ["stop reason = breakpoint 1."])
+
+ # Continue the program, there should be another stop.
+ self.runCmd("process continue")
+
+ # Stopped again.
+ self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ["stop reason = breakpoint 1."])
+
+ # At this point, 1.1 has a hit count of 0 and the other a hit count of 1".
+ self.expect("breakpoint list -f", "The breakpoints should report correct hit counts",
+ patterns = ["1\.1: .+ unresolved, hit count = 0 +Options: disabled",
+ "1\.2: .+ resolved, hit count = 1",
+ "1\.3: .+ resolved, hit count = 1"])
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/main.c b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/main.c
new file mode 100644
index 000000000000..7ec3ded67b74
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_locations/main.c
@@ -0,0 +1,43 @@
+#include <stdio.h>
+
+#define INLINE inline __attribute__((always_inline))
+
+int
+func_not_inlined (void)
+{
+ printf ("Called func_not_inlined.\n");
+ return 0;
+}
+
+INLINE int
+func_inlined (void)
+{
+ static int func_inline_call_count = 0;
+ printf ("Called func_inlined.\n");
+ ++func_inline_call_count;
+ printf ("Returning func_inlined call count: %d.\n", func_inline_call_count);
+ return func_inline_call_count; // Set break point at this line.
+}
+
+extern int func_inlined (void);
+
+int
+main (int argc, char **argv)
+{
+ printf ("Starting...\n");
+
+ int (*func_ptr) (void);
+ func_ptr = func_inlined;
+
+ int a = func_inlined();
+ printf("First call to func_inlined() returns: %d.\n", a);
+
+ func_not_inlined ();
+
+ func_ptr ();
+
+ printf("Last call to func_inlined() returns: %d.\n", func_inlined ());
+ return 0;
+}
+
+
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/Makefile b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/Makefile
new file mode 100644
index 000000000000..457c4972f2d5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp foo.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/TestBreakpointOptions.py b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/TestBreakpointOptions.py
new file mode 100644
index 000000000000..29afec202339
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/TestBreakpointOptions.py
@@ -0,0 +1,93 @@
+"""
+Test breakpoint command for different options.
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class BreakpointOptionsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test(self):
+ """Test breakpoint command for different options."""
+ self.build()
+ self.breakpoint_options_test()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def breakpoint_options_test(self):
+ """Test breakpoint command for different options."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # This should create a breakpoint with 1 locations.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, extra_options = "-K 1", num_expected_locations = 1)
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, extra_options = "-K 0", num_expected_locations = 1)
+
+ # This should create a breakpoint 0 locations.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, extra_options = "-m 0", num_expected_locations = 0)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Stopped once.
+ self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ["stop reason = breakpoint 2."])
+
+ # Check the list of breakpoint.
+ self.expect("breakpoint list -f", "Breakpoint locations shown correctly",
+ substrs = ["1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % self.line,
+ "2: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % self.line,
+ "3: file = 'main.cpp', line = %d, exact_match = 1, locations = 0" % self.line])
+
+ # Continue the program, there should be another stop.
+ self.runCmd("process continue")
+
+ # Stopped again.
+ self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ["stop reason = breakpoint 1."])
+
+ # Continue the program, we should exit.
+ self.runCmd("process continue")
+
+ # We should exit.
+ self.expect("process status", "Process exited successfully",
+ patterns = ["^Process [0-9]+ exited with status = 0"])
+
+ def breakpoint_options_language_test(self):
+ """Test breakpoint command for language option."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # This should create a breakpoint with 1 locations.
+ lldbutil.run_break_set_by_symbol (self, 'ns::func', sym_exact=False, extra_options = "-L c++", num_expected_locations=1)
+
+ # This should create a breakpoint with 0 locations.
+ lldbutil.run_break_set_by_symbol (self, 'ns::func', sym_exact=False, extra_options = "-L c", num_expected_locations=0)
+ self.runCmd("settings set target.language c")
+ lldbutil.run_break_set_by_symbol (self, 'ns::func', sym_exact=False, num_expected_locations=0)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Stopped once.
+ self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ["stop reason = breakpoint 1."])
+
+ # Continue the program, we should exit.
+ self.runCmd("process continue")
+
+ # We should exit.
+ self.expect("process status", "Process exited successfully",
+ patterns = ["^Process [0-9]+ exited with status = 0"])
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/foo.cpp b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/foo.cpp
new file mode 100644
index 000000000000..e5d0e09803e6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/foo.cpp
@@ -0,0 +1,12 @@
+
+namespace ns {
+ int func(void)
+ {
+ return 0;
+ }
+}
+
+extern "C" int foo(void)
+{
+ return ns::func();
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/main.cpp b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/main.cpp
new file mode 100644
index 000000000000..363b90003d76
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/breakpoint_options/main.cpp
@@ -0,0 +1,8 @@
+// Set break point at this line.
+
+extern "C" int foo(void);
+int
+main (int argc, char **argv)
+{
+ return foo();
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/Makefile b/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/Makefile
new file mode 100644
index 000000000000..0ac34a186b25
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+EXE := CompDirSymLink
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/TestCompDirSymLink.py b/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/TestCompDirSymLink.py
new file mode 100644
index 000000000000..e1de38bcad8c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/TestCompDirSymLink.py
@@ -0,0 +1,63 @@
+"""
+Test breakpoint command with AT_comp_dir set to symbolic link.
+"""
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+import shutil
+
+
+_EXE_NAME = 'CompDirSymLink' # Must match Makefile
+_SRC_FILE = 'main.cpp'
+_COMP_DIR_SYM_LINK_PROP = 'plugin.symbol-file.dwarf.comp-dir-symlink-paths'
+
+class CompDirSymLinkTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number(_SRC_FILE, '// Set break point at this line.')
+ self.src_path = os.path.join(os.getcwd(), _SRC_FILE)
+
+ @skipIfHostWindows
+ def test_symlink_paths_set(self):
+ pwd_symlink = self.create_src_symlink()
+ self.doBuild(pwd_symlink)
+ self.runCmd("settings set %s %s" % (_COMP_DIR_SYM_LINK_PROP, pwd_symlink))
+ lldbutil.run_break_set_by_file_and_line(self, self.src_path, self.line)
+
+ @skipUnlessHostLinux
+ def test_symlink_paths_set_procselfcwd(self):
+ pwd_symlink = '/proc/self/cwd'
+ self.doBuild(pwd_symlink)
+ self.runCmd("settings set %s %s" % (_COMP_DIR_SYM_LINK_PROP, pwd_symlink))
+ lldbutil.run_break_set_by_file_and_line(self, self.src_path, self.line)
+
+ @skipIfHostWindows
+ def test_symlink_paths_unset(self):
+ pwd_symlink = self.create_src_symlink()
+ self.doBuild(pwd_symlink)
+ self.runCmd('settings clear ' + _COMP_DIR_SYM_LINK_PROP)
+ self.assertRaises(AssertionError, lldbutil.run_break_set_by_file_and_line, self, self.src_path, self.line)
+
+ def create_src_symlink(self):
+ pwd_symlink = os.path.join(os.getcwd(), 'pwd_symlink')
+ if os.path.exists(pwd_symlink):
+ os.unlink(pwd_symlink)
+ os.symlink(os.getcwd(), pwd_symlink)
+ self.addTearDownHook(lambda: os.remove(pwd_symlink))
+ return pwd_symlink
+
+ def doBuild(self, pwd_symlink):
+ self.build(None, None, {'PWD': pwd_symlink}, True)
+
+ exe = os.path.join(os.getcwd(), _EXE_NAME)
+ self.runCmd('file ' + exe, CURRENT_EXECUTABLE_SET)
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/main.cpp b/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/main.cpp
new file mode 100644
index 000000000000..fef06a011e92
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/comp_dir_symlink/main.cpp
@@ -0,0 +1,13 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+int main (int argc, char const *argv[])
+{
+ return 0; // Set break point at this line.
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoins/Makefile b/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoins/Makefile
new file mode 100644
index 000000000000..f89b52a972e9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoins/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+ifneq (,$(findstring icc,$(CC)))
+ CXXFLAGS += -debug inline-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoins/TestConsecutiveBreakpoints.py b/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoins/TestConsecutiveBreakpoints.py
new file mode 100644
index 000000000000..af6df3764829
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoins/TestConsecutiveBreakpoints.py
@@ -0,0 +1,59 @@
+"""
+Test continue from a breakpoint when there is a breakpoint on the next instruction also.
+"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ConsecutiveBreakpoitsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureAll("llvm.org/pr23478", oslist = not_in(["macosx"]))
+ def test (self):
+ self.build ()
+ self.consecutive_breakpoints_tests()
+
+ def consecutive_breakpoints_tests(self):
+ exe = os.path.join (os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateBySourceRegex("Set breakpoint here", lldb.SBFileSpec("main.cpp"))
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # We should be stopped at the first breakpoint
+ thread = process.GetThreadAtIndex(0)
+ self.assertEqual(thread.GetStopReason(), lldb.eStopReasonBreakpoint)
+
+ # Set breakpoint to the next instruction
+ frame = thread.GetFrameAtIndex(0)
+
+ address = frame.GetPCAddress()
+ instructions = target.ReadInstructions(address, 2)
+ self.assertTrue(len(instructions) == 2)
+ address = instructions[1].GetAddress()
+
+ target.BreakpointCreateByAddress(address.GetLoadAddress(target))
+ process.Continue()
+
+ # We should be stopped at the second breakpoint
+ thread = process.GetThreadAtIndex(0)
+ self.assertEqual(thread.GetStopReason(), lldb.eStopReasonBreakpoint)
+
+ # Run the process until termination
+ process.Continue()
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoins/main.cpp b/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoins/main.cpp
new file mode 100644
index 000000000000..c1943f03dbf1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/consecutive_breakpoins/main.cpp
@@ -0,0 +1,19 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+int
+main(int argc, char const *argv[])
+{
+ int a = 0;
+ int b = 1;
+ a = b + 1; // Set breakpoint here
+ b = a + 1;
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/Makefile b/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/Makefile
new file mode 100644
index 000000000000..f89b52a972e9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+ifneq (,$(findstring icc,$(CC)))
+ CXXFLAGS += -debug inline-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/TestCPPBreakpointLocations.py b/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/TestCPPBreakpointLocations.py
new file mode 100644
index 000000000000..dea206b9e9d2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/TestCPPBreakpointLocations.py
@@ -0,0 +1,62 @@
+"""
+Test lldb breakpoint ids.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TestCPPBreakpointLocations(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureWindows("llvm.org/pr24764")
+ def test (self):
+ self.build ()
+ self.breakpoint_id_tests ()
+
+ def verify_breakpoint_locations(self, target, bp_dict):
+
+ name = bp_dict['name']
+ names = bp_dict['loc_names']
+ bp = target.BreakpointCreateByName (name)
+ self.assertTrue (bp.GetNumLocations() == len(names), "Make sure we find the right number of breakpoint locations")
+
+ bp_loc_names = list()
+ for bp_loc in bp:
+ bp_loc_names.append(bp_loc.GetAddress().GetFunction().GetName())
+
+ for name in names:
+ found = name in bp_loc_names
+ if not found:
+ print("Didn't find '%s' in: %s" % (name, bp_loc_names))
+ self.assertTrue (found, "Make sure we find all required locations")
+
+ def breakpoint_id_tests (self):
+
+ # Create a target by the debugger.
+ exe = os.path.join(os.getcwd(), "a.out")
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+ bp_dicts = [
+ { 'name' : 'func1', 'loc_names' : [ 'a::c::func1()', 'b::c::func1()'] },
+ { 'name' : 'func2', 'loc_names' : [ 'a::c::func2()', 'c::d::func2()'] },
+ { 'name' : 'func3', 'loc_names' : [ 'a::c::func3()', 'b::c::func3()', 'c::d::func3()'] },
+ { 'name' : 'c::func1', 'loc_names' : [ 'a::c::func1()', 'b::c::func1()'] },
+ { 'name' : 'c::func2', 'loc_names' : [ 'a::c::func2()'] },
+ { 'name' : 'c::func3', 'loc_names' : [ 'a::c::func3()', 'b::c::func3()'] },
+ { 'name' : 'a::c::func1', 'loc_names' : [ 'a::c::func1()'] },
+ { 'name' : 'b::c::func1', 'loc_names' : [ 'b::c::func1()'] },
+ { 'name' : 'c::d::func2', 'loc_names' : [ 'c::d::func2()'] },
+ { 'name' : 'a::c::func1()', 'loc_names' : [ 'a::c::func1()'] },
+ { 'name' : 'b::c::func1()', 'loc_names' : [ 'b::c::func1()'] },
+ { 'name' : 'c::d::func2()', 'loc_names' : [ 'c::d::func2()'] },
+ ]
+
+ for bp_dict in bp_dicts:
+ self.verify_breakpoint_locations(target, bp_dict)
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/main.cpp b/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/main.cpp
new file mode 100644
index 000000000000..ef582aa36ebb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp/main.cpp
@@ -0,0 +1,77 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+#include <stdint.h>
+
+namespace a {
+ class c {
+ public:
+ c () {}
+ ~c() {}
+ void func1()
+ {
+ puts (__PRETTY_FUNCTION__);
+ }
+ void func2()
+ {
+ puts (__PRETTY_FUNCTION__);
+ }
+ void func3()
+ {
+ puts (__PRETTY_FUNCTION__);
+ }
+ };
+}
+
+namespace b {
+ class c {
+ public:
+ c () {}
+ ~c() {}
+ void func1()
+ {
+ puts (__PRETTY_FUNCTION__);
+ }
+ void func3()
+ {
+ puts (__PRETTY_FUNCTION__);
+ }
+ };
+}
+
+namespace c {
+ class d {
+ public:
+ d () {}
+ ~d() {}
+ void func2()
+ {
+ puts (__PRETTY_FUNCTION__);
+ }
+ void func3()
+ {
+ puts (__PRETTY_FUNCTION__);
+ }
+ };
+}
+
+int main (int argc, char const *argv[])
+{
+ a::c ac;
+ b::c bc;
+ c::d cd;
+ ac.func1();
+ ac.func2();
+ ac.func3();
+ bc.func1();
+ bc.func3();
+ cd.func2();
+ cd.func3();
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/Makefile b/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/TestCPPExceptionBreakpoint.py b/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/TestCPPExceptionBreakpoint.py
new file mode 100644
index 000000000000..f7a19098b492
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/TestCPPExceptionBreakpoint.py
@@ -0,0 +1,48 @@
+"""
+Test that you can set breakpoint and hit the C++ language exception breakpoint
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+import sys
+from lldbsuite.test.lldbtest import *
+
+class TestCPPExceptionBreakpoint (TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+ my_var = 10
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureWindows("llvm.org/pr24538") # clang-cl does not support throw or catch
+ def test_cpp_exception_breakpoint(self):
+ """Test setting and hitting the C++ exception breakpoint."""
+ self.build()
+ self.do_cpp_exception_bkpt ()
+
+ def setUp (self):
+ TestBase.setUp(self)
+ self.main_source = "main.c"
+ self.main_source_spec = lldb.SBFileSpec(self.main_source)
+
+
+ def do_cpp_exception_bkpt (self):
+ exe = os.path.join(os.getcwd(), "a.out")
+ error = lldb.SBError()
+
+ self.target = self.dbg.CreateTarget(exe)
+ self.assertTrue(self.target, VALID_TARGET)
+
+ exception_bkpt = self.target.BreakpointCreateForException(lldb.eLanguageTypeC_plus_plus, False, True)
+ self.assertTrue (exception_bkpt.IsValid(), "Created exception breakpoint.")
+
+ process = self.target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, exception_bkpt)
+ self.assertTrue (len(thread_list) == 1, "One thread stopped at the exception breakpoint.")
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/main.cpp b/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/main.cpp
new file mode 100644
index 000000000000..76cb22735a71
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/cpp_exception/main.cpp
@@ -0,0 +1,13 @@
+#include <exception>
+
+void
+throws_int ()
+{
+ throw 5;
+}
+
+int
+main ()
+{
+ throws_int();
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/Makefile b/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/Makefile
new file mode 100644
index 000000000000..7934cd5db427
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+ifneq (,$(findstring icc,$(CC)))
+ CFLAGS += -debug inline-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/TestBreakpointsWithNoTargets.py b/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/TestBreakpointsWithNoTargets.py
new file mode 100644
index 000000000000..f2693e6ed593
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/TestBreakpointsWithNoTargets.py
@@ -0,0 +1,67 @@
+"""
+Test breakpoint commands set before we have a target
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class BreakpointInDummyTarget (TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test(self):
+ """Test breakpoint set before we have a target. """
+ self.build()
+ self.dummy_breakpoint_test()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.c', 'Set a breakpoint on this line.')
+ self.line2 = line_number ('main.c', 'Set another on this line.')
+
+ def dummy_breakpoint_test(self):
+ """Test breakpoint set before we have a target. """
+
+ # This should create a breakpoint with 3 locations.
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=0)
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line2, num_expected_locations=0)
+
+ # This is the function to remove breakpoints from the dummy target
+ # to get a clean slate for the next test case.
+ def cleanup():
+ self.runCmd('breakpoint delete -D -f', check=False)
+ self.runCmd('breakpoint list', check=False)
+
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # The breakpoint list should show 3 locations.
+ self.expect("breakpoint list -f", "Breakpoint locations shown correctly",
+ substrs = ["1: file = 'main.c', line = %d, exact_match = 0, locations = 1" % self.line,
+ "2: file = 'main.c', line = %d, exact_match = 0, locations = 1" % self.line2])
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Stopped once.
+ self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ["stop reason = breakpoint 1."])
+
+ # Continue the program, there should be another stop.
+ self.runCmd("process continue")
+
+ # Stopped again.
+ self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ["stop reason = breakpoint 2."])
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/main.c b/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/main.c
new file mode 100644
index 000000000000..e1f03237cd11
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/dummy_target_breakpoints/main.c
@@ -0,0 +1,11 @@
+#include <stdio.h>
+
+int
+main (int argc, char **argv)
+{
+ printf ("Set a breakpoint on this line.\n");
+
+ return 0; // Set another on this line.
+}
+
+
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/Makefile b/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/Makefile
new file mode 100644
index 000000000000..5b73ae626f34
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := int.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/TestInlinedBreakpoints.py b/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/TestInlinedBreakpoints.py
new file mode 100644
index 000000000000..d04178bda78d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/TestInlinedBreakpoints.py
@@ -0,0 +1,57 @@
+"""
+Test that inlined breakpoints (breakpoint set on a file/line included from
+another source file) works correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class InlinedBreakpointsTestCase(TestBase):
+ """Bug fixed: rdar://problem/8464339"""
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test_with_run_command(self):
+ """Test 'b basic_types.cpp:176' does break (where int.cpp includes basic_type.cpp)."""
+ self.build()
+ self.inlined_breakpoints()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside basic_type.cpp.
+ self.line = line_number('basic_type.cpp', '// Set break point at this line.')
+
+ def inlined_breakpoints(self):
+ """Test 'b basic_types.cpp:176' does break (where int.cpp includes basic_type.cpp)."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # With the inline-breakpoint-strategy, our file+line breakpoint should not resolve to a location.
+ self.runCmd('settings set target.inline-breakpoint-strategy headers')
+
+ # Set a breakpoint and fail because it is in an inlined source implemenation file
+ lldbutil.run_break_set_by_file_and_line (self, "basic_type.cpp", self.line, num_expected_locations=0)
+
+ # Now enable breakpoints in implementation files and see the breakpoint set succeed
+ self.runCmd('settings set target.inline-breakpoint-strategy always')
+ # And add hooks to restore the settings during tearDown().
+ self.addTearDownHook(
+ lambda: self.runCmd("settings set target.inline-breakpoint-strategy always"))
+
+ lldbutil.run_break_set_by_file_and_line (self, "basic_type.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ # And it should break at basic_type.cpp:176.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint',
+ 'basic_type.cpp:%d' % self.line])
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/basic_type.cpp b/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/basic_type.cpp
new file mode 100644
index 000000000000..5881afe1f395
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/basic_type.cpp
@@ -0,0 +1,178 @@
+// This file must have the following defined before it is included:
+// T defined to the type to test (int, float, etc)
+// T_CSTR a C string representation of the type T ("int", "float")
+// T_VALUE_1 defined to a valid initializer value for TEST_TYPE (7 for int, 2.0 for float)
+// T_VALUE_2, T_VALUE_3, T_VALUE_4 defined to a valid initializer value for TEST_TYPE that is different from TEST_VALUE_1
+// T_PRINTF_FORMAT defined if T can be printed with printf
+//
+// An example for integers is below
+#if 0
+
+#define T int
+#define T_CSTR "int"
+#define T_VALUE_1 11001110
+#define T_VALUE_2 22002220
+#define T_VALUE_3 33003330
+#define T_VALUE_4 44044440
+#define T_PRINTF_FORMAT "%i"
+
+#include "basic_type.cpp"
+
+#endif
+
+class a_class
+{
+public:
+ a_class (const T& a, const T& b) :
+ m_a (a),
+ m_b (b)
+ {
+ }
+
+ ~a_class ()
+ {
+ }
+
+ const T&
+ get_a()
+ {
+ return m_a;
+ }
+
+ void
+ set_a (const T& a)
+ {
+ m_a = a;
+ }
+
+ const T&
+ get_b()
+ {
+ return m_b;
+ }
+
+ void
+ set_b (const T& b)
+ {
+ m_b = b;
+ }
+
+protected:
+ T m_a;
+ T m_b;
+};
+
+typedef struct a_struct_tag {
+ T a;
+ T b;
+} a_struct_t;
+
+
+typedef union a_union_zero_tag {
+ T a;
+ double a_double;
+} a_union_zero_t;
+
+typedef struct a_union_nonzero_tag {
+ double a_double;
+ a_union_zero_t u;
+} a_union_nonzero_t;
+
+
+#include <stdint.h>
+#include <stdio.h>
+
+void Puts(char const *msg)
+{
+ puts(msg);
+}
+
+int
+main (int argc, char const *argv[])
+{
+ T a = T_VALUE_1;
+ T* a_ptr = &a;
+ T& a_ref = a;
+ T a_array_bounded[2] = { T_VALUE_1, T_VALUE_2 };
+ T a_array_unbounded[] = { T_VALUE_1, T_VALUE_2 };
+
+ a_class a_class_instance (T_VALUE_1, T_VALUE_2);
+ a_class *a_class_ptr = &a_class_instance;
+ a_class &a_class_ref = a_class_instance;
+
+ a_struct_t a_struct = { T_VALUE_1, T_VALUE_2 };
+ a_struct_t *a_struct_ptr = &a_struct;
+ a_struct_t &a_struct_ref = a_struct;
+
+ // Create a union with type T at offset zero
+ a_union_zero_t a_union_zero;
+ a_union_zero.a = T_VALUE_1;
+ a_union_zero_t *a_union_zero_ptr = &a_union_zero;
+ a_union_zero_t &a_union_zero_ref = a_union_zero;
+
+ // Create a union with type T at a non-zero offset
+ a_union_nonzero_t a_union_nonzero;
+ a_union_nonzero.u.a = T_VALUE_1;
+ a_union_nonzero_t *a_union_nonzero_ptr = &a_union_nonzero;
+ a_union_nonzero_t &a_union_nonzero_ref = a_union_nonzero;
+
+ a_struct_t a_struct_array_bounded[2] = {{ T_VALUE_1, T_VALUE_2 }, { T_VALUE_3, T_VALUE_4 }};
+ a_struct_t a_struct_array_unbounded[] = {{ T_VALUE_1, T_VALUE_2 }, { T_VALUE_3, T_VALUE_4 }};
+ a_union_zero_t a_union_zero_array_bounded[2];
+ a_union_zero_array_bounded[0].a = T_VALUE_1;
+ a_union_zero_array_bounded[1].a = T_VALUE_2;
+ a_union_zero_t a_union_zero_array_unbounded[] = {{ T_VALUE_1 }, { T_VALUE_2 }};
+
+#ifdef T_PRINTF_FORMAT
+ printf ("%s: a = '" T_PRINTF_FORMAT "'\n", T_CSTR, a);
+ printf ("%s*: %p => *a_ptr = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_ptr, *a_ptr);
+ printf ("%s&: @%p => a_ref = '" T_PRINTF_FORMAT "'\n", T_CSTR, &a_ref, a_ref);
+
+ printf ("%s[2]: a_array_bounded[0] = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_array_bounded[0]);
+ printf ("%s[2]: a_array_bounded[1] = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_array_bounded[1]);
+
+ printf ("%s[]: a_array_unbounded[0] = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_array_unbounded[0]);
+ printf ("%s[]: a_array_unbounded[1] = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_array_unbounded[1]);
+
+ printf ("(a_class) a_class_instance.m_a = '" T_PRINTF_FORMAT "'\n", a_class_instance.get_a());
+ printf ("(a_class) a_class_instance.m_b = '" T_PRINTF_FORMAT "'\n", a_class_instance.get_b());
+ printf ("(a_class*) a_class_ptr = %p, a_class_ptr->m_a = '" T_PRINTF_FORMAT "'\n", a_class_ptr, a_class_ptr->get_a());
+ printf ("(a_class*) a_class_ptr = %p, a_class_ptr->m_b = '" T_PRINTF_FORMAT "'\n", a_class_ptr, a_class_ptr->get_b());
+ printf ("(a_class&) a_class_ref = %p, a_class_ref.m_a = '" T_PRINTF_FORMAT "'\n", &a_class_ref, a_class_ref.get_a());
+ printf ("(a_class&) a_class_ref = %p, a_class_ref.m_b = '" T_PRINTF_FORMAT "'\n", &a_class_ref, a_class_ref.get_b());
+
+ printf ("(a_struct_t) a_struct.a = '" T_PRINTF_FORMAT "'\n", a_struct.a);
+ printf ("(a_struct_t) a_struct.b = '" T_PRINTF_FORMAT "'\n", a_struct.b);
+ printf ("(a_struct_t*) a_struct_ptr = %p, a_struct_ptr->a = '" T_PRINTF_FORMAT "'\n", a_struct_ptr, a_struct_ptr->a);
+ printf ("(a_struct_t*) a_struct_ptr = %p, a_struct_ptr->b = '" T_PRINTF_FORMAT "'\n", a_struct_ptr, a_struct_ptr->b);
+ printf ("(a_struct_t&) a_struct_ref = %p, a_struct_ref.a = '" T_PRINTF_FORMAT "'\n", &a_struct_ref, a_struct_ref.a);
+ printf ("(a_struct_t&) a_struct_ref = %p, a_struct_ref.b = '" T_PRINTF_FORMAT "'\n", &a_struct_ref, a_struct_ref.b);
+
+ printf ("(a_union_zero_t) a_union_zero.a = '" T_PRINTF_FORMAT "'\n", a_union_zero.a);
+ printf ("(a_union_zero_t*) a_union_zero_ptr = %p, a_union_zero_ptr->a = '" T_PRINTF_FORMAT "'\n", a_union_zero_ptr, a_union_zero_ptr->a);
+ printf ("(a_union_zero_t&) a_union_zero_ref = %p, a_union_zero_ref.a = '" T_PRINTF_FORMAT "'\n", &a_union_zero_ref, a_union_zero_ref.a);
+
+ printf ("(a_union_nonzero_t) a_union_nonzero.u.a = '" T_PRINTF_FORMAT "'\n", a_union_nonzero.u.a);
+ printf ("(a_union_nonzero_t*) a_union_nonzero_ptr = %p, a_union_nonzero_ptr->u.a = '" T_PRINTF_FORMAT "'\n", a_union_nonzero_ptr, a_union_nonzero_ptr->u.a);
+ printf ("(a_union_nonzero_t&) a_union_nonzero_ref = %p, a_union_nonzero_ref.u.a = '" T_PRINTF_FORMAT "'\n", &a_union_nonzero_ref, a_union_nonzero_ref.u.a);
+
+ printf ("(a_struct_t[2]) a_struct_array_bounded[0].a = '" T_PRINTF_FORMAT "'\n", a_struct_array_bounded[0].a);
+ printf ("(a_struct_t[2]) a_struct_array_bounded[0].b = '" T_PRINTF_FORMAT "'\n", a_struct_array_bounded[0].b);
+ printf ("(a_struct_t[2]) a_struct_array_bounded[1].a = '" T_PRINTF_FORMAT "'\n", a_struct_array_bounded[1].a);
+ printf ("(a_struct_t[2]) a_struct_array_bounded[1].b = '" T_PRINTF_FORMAT "'\n", a_struct_array_bounded[1].b);
+
+ printf ("(a_struct_t[]) a_struct_array_unbounded[0].a = '" T_PRINTF_FORMAT "'\n", a_struct_array_unbounded[0].a);
+ printf ("(a_struct_t[]) a_struct_array_unbounded[0].b = '" T_PRINTF_FORMAT "'\n", a_struct_array_unbounded[0].b);
+ printf ("(a_struct_t[]) a_struct_array_unbounded[1].a = '" T_PRINTF_FORMAT "'\n", a_struct_array_unbounded[1].a);
+ printf ("(a_struct_t[]) a_struct_array_unbounded[1].b = '" T_PRINTF_FORMAT "'\n", a_struct_array_unbounded[1].b);
+
+ printf ("(a_union_zero_t[2]) a_union_zero_array_bounded[0].a = '" T_PRINTF_FORMAT "'\n", a_union_zero_array_bounded[0].a);
+ printf ("(a_union_zero_t[2]) a_union_zero_array_bounded[1].a = '" T_PRINTF_FORMAT "'\n", a_union_zero_array_bounded[1].a);
+
+ printf ("(a_union_zero_t[]) a_union_zero_array_unbounded[0].a = '" T_PRINTF_FORMAT "'\n", a_union_zero_array_unbounded[0].a);
+ printf ("(a_union_zero_t[]) a_union_zero_array_unbounded[1].a = '" T_PRINTF_FORMAT "'\n", a_union_zero_array_unbounded[1].a);
+
+#endif
+ Puts("About to exit, break here to check values..."); // Set break point at this line.
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/int.cpp b/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/int.cpp
new file mode 100644
index 000000000000..922398b1c6e3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/inlined_breakpoints/int.cpp
@@ -0,0 +1,9 @@
+#define T int
+#define T_CSTR "int"
+#define T_VALUE_1 11001110
+#define T_VALUE_2 22002220
+#define T_VALUE_3 33003330
+#define T_VALUE_4 44004440
+#define T_PRINTF_FORMAT "%i"
+
+#include "basic_type.cpp"
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/Makefile b/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/Makefile
new file mode 100644
index 000000000000..ad3cb3fadcde
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/TestObjCBreakpoints.py b/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/TestObjCBreakpoints.py
new file mode 100644
index 000000000000..648a0f5ea07c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/TestObjCBreakpoints.py
@@ -0,0 +1,94 @@
+"""
+Test that objective-c constant strings are generated correctly by the expression
+parser.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+import shutil
+import subprocess
+
+@skipUnlessDarwin
+class TestObjCBreakpoints(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test_break(self):
+ """Test setting Objective C specific breakpoints (DWARF in .o files)."""
+ self.build()
+ self.setTearDownCleanup()
+ self.check_objc_breakpoints(False)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.main_source = "main.m"
+ self.line = line_number(self.main_source, '// Set breakpoint here')
+
+ def check_category_breakpoints(self):
+ name_bp = self.target.BreakpointCreateByName ("myCategoryFunction")
+ selector_bp = self.target.BreakpointCreateByName ("myCategoryFunction", lldb.eFunctionNameTypeSelector, lldb.SBFileSpecList(), lldb.SBFileSpecList())
+ self.assertTrue(name_bp.GetNumLocations() == selector_bp.GetNumLocations(), 'Make sure setting a breakpoint by name "myCategoryFunction" sets a breakpoint even though it is in a category')
+ for bp_loc in selector_bp:
+ function_name = bp_loc.GetAddress().GetSymbol().GetName()
+ self.assertTrue(" myCategoryFunction]" in function_name, 'Make sure all function names have " myCategoryFunction]" in their names')
+
+ category_bp = self.target.BreakpointCreateByName ("-[MyClass(MyCategory) myCategoryFunction]")
+ stripped_bp = self.target.BreakpointCreateByName ("-[MyClass myCategoryFunction]")
+ stripped2_bp = self.target.BreakpointCreateByName ("[MyClass myCategoryFunction]")
+ self.assertTrue(category_bp.GetNumLocations() == 1, "Make sure we can set a breakpoint using a full objective C function name with the category included (-[MyClass(MyCategory) myCategoryFunction])")
+ self.assertTrue(stripped_bp.GetNumLocations() == 1, "Make sure we can set a breakpoint using a full objective C function name without the category included (-[MyClass myCategoryFunction])")
+ self.assertTrue(stripped2_bp.GetNumLocations() == 1, "Make sure we can set a breakpoint using a full objective C function name without the category included ([MyClass myCategoryFunction])")
+
+ def check_objc_breakpoints(self, have_dsym):
+ """Test constant string generation amd comparison by the expression parser."""
+
+ # Set debugger into synchronous mode
+ self.dbg.SetAsync(False)
+
+ # Create a target by the debugger.
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.target = self.dbg.CreateTarget(exe)
+ self.assertTrue(self.target, VALID_TARGET)
+
+ #----------------------------------------------------------------------
+ # Set breakpoints on all selectors whose name is "count". This should
+ # catch breakpoints that are both C functions _and_ anything whose
+ # selector is "count" because just looking at "count" we can't tell
+ # definitively if the name is a selector or a C function
+ #----------------------------------------------------------------------
+ name_bp = self.target.BreakpointCreateByName ("count")
+ selector_bp = self.target.BreakpointCreateByName ("count", lldb.eFunctionNameTypeSelector, lldb.SBFileSpecList(), lldb.SBFileSpecList())
+ self.assertTrue(name_bp.GetNumLocations() >= selector_bp.GetNumLocations(), 'Make sure we get at least the same amount of breakpoints if not more when setting by name "count"')
+ self.assertTrue(selector_bp.GetNumLocations() > 50, 'Make sure we find a lot of "count" selectors') # There are 93 on the latest MacOSX
+ for bp_loc in selector_bp:
+ function_name = bp_loc.GetAddress().GetSymbol().GetName()
+ self.assertTrue(" count]" in function_name, 'Make sure all function names have " count]" in their names')
+
+ #----------------------------------------------------------------------
+ # Set breakpoints on all selectors whose name is "isEqual:". This should
+ # catch breakpoints that are only ObjC selectors because no C function
+ # can end with a :
+ #----------------------------------------------------------------------
+ name_bp = self.target.BreakpointCreateByName ("isEqual:")
+ selector_bp = self.target.BreakpointCreateByName ("isEqual:", lldb.eFunctionNameTypeSelector, lldb.SBFileSpecList(), lldb.SBFileSpecList())
+ self.assertTrue(name_bp.GetNumLocations() == selector_bp.GetNumLocations(), 'Make sure setting a breakpoint by name "isEqual:" only sets selector breakpoints')
+ for bp_loc in selector_bp:
+ function_name = bp_loc.GetAddress().GetSymbol().GetName()
+ self.assertTrue(" isEqual:]" in function_name, 'Make sure all function names have " isEqual:]" in their names')
+
+ self.check_category_breakpoints()
+
+ if have_dsym:
+ shutil.rmtree(exe + ".dSYM")
+ self.assertTrue(subprocess.call(['/usr/bin/strip', '-Sx', exe]) == 0, 'stripping dylib succeeded')
+
+ # Check breakpoints again, this time using the symbol table only
+ self.check_category_breakpoints()
diff --git a/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/main.m b/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/main.m
new file mode 100644
index 000000000000..53567491219b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/breakpoint/objc/main.m
@@ -0,0 +1,98 @@
+#import <Foundation/Foundation.h>
+#include <unistd.h>
+
+@interface MyClass : NSObject
+@end
+
+@implementation MyClass : NSObject
+@end
+
+@implementation MyClass (MyCategory)
+
+
+- (void) myCategoryFunction {
+ NSLog (@"myCategoryFunction");
+}
+
+@end
+
+
+
+int
+Test_Selector ()
+{
+ SEL sel = @selector(length);
+ printf("sel = %p\n", sel);
+ // Expressions to test here for selector:
+ // expression (char *)sel_getName(sel)
+ // The expression above should return "sel" as it should be just
+ // a uniqued C string pointer. We were seeing the result pointer being
+ // truncated with recent LLDBs.
+ return 0; // Break here for selector: tests
+}
+
+int
+Test_NSString (const char *program)
+{
+ NSString *str = [NSString stringWithFormat:@"Hello from '%s'", program];
+ NSLog(@"NSString instance: %@", str);
+ printf("str = '%s'\n", [str cStringUsingEncoding: [NSString defaultCStringEncoding]]);
+ printf("[str length] = %zu\n", (size_t)[str length]);
+ printf("[str description] = %s\n", [[str description] UTF8String]);
+ id str_id = str;
+ // Expressions to test here for NSString:
+ // expression (char *)sel_getName(sel)
+ // expression [str length]
+ // expression [str_id length]
+ // expression [str description]
+ // expression [str_id description]
+ // expression str.length
+ // expression str.description
+ // expression str = @"new"
+ // expression str = [NSString stringWithFormat: @"%cew", 'N']
+ return 0; // Break here for NSString tests
+}
+
+NSString *my_global_str = NULL;
+
+int
+Test_NSArray ()
+{
+ NSMutableArray *nil_mutable_array = nil;
+ NSArray *array1 = [NSArray arrayWithObjects: @"array1 object1", @"array1 object2", @"array1 object3", nil];
+ NSArray *array2 = [NSArray arrayWithObjects: array1, @"array2 object2", @"array2 object3", nil];
+ // Expressions to test here for NSArray:
+ // expression [nil_mutable_array count]
+ // expression [array1 count]
+ // expression array1.count
+ // expression [array2 count]
+ // expression array2.count
+ id obj;
+ // After each object at index call, use expression and validate object
+ obj = [array1 objectAtIndex: 0]; // Break here for NSArray tests
+ obj = [array1 objectAtIndex: 1];
+ obj = [array1 objectAtIndex: 2];
+
+ obj = [array2 objectAtIndex: 0];
+ obj = [array2 objectAtIndex: 1];
+ obj = [array2 objectAtIndex: 2];
+ NSUInteger count = [nil_mutable_array count];
+ return 0;
+}
+
+
+int main (int argc, char const *argv[])
+{
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+ Test_Selector(); // Set breakpoint here
+ Test_NSArray ();
+ Test_NSString (argv[0]);
+ MyClass *my_class = [[MyClass alloc] init];
+ [my_class myCategoryFunction];
+ printf("sizeof(id) = %zu\n", sizeof(id));
+ printf("sizeof(Class) = %zu\n", sizeof(Class));
+ printf("sizeof(SEL) = %zu\n", sizeof(SEL));
+
+ [pool release];
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/command_history/.categories b/packages/Python/lldbsuite/test/functionalities/command_history/.categories
new file mode 100644
index 000000000000..3a3f4df6416b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_history/.categories
@@ -0,0 +1 @@
+cmdline
diff --git a/packages/Python/lldbsuite/test/functionalities/command_history/TestCommandHistory.py b/packages/Python/lldbsuite/test/functionalities/command_history/TestCommandHistory.py
new file mode 100644
index 000000000000..312c91517f98
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_history/TestCommandHistory.py
@@ -0,0 +1,68 @@
+"""
+Test the command history mechanism
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class CommandHistoryTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @no_debug_info_test
+ def test_history(self):
+ self.runCmd('command history --clear', inHistory=False)
+ self.runCmd('breakpoint list', check=False, inHistory=True) #0
+ self.runCmd('register read', check=False, inHistory=True) #1
+ self.runCmd('apropos hello', check=False, inHistory=True) #2
+ self.runCmd('memory write', check=False, inHistory=True) #3
+ self.runCmd('log list', check=False, inHistory=True) #4
+ self.runCmd('disassemble', check=False, inHistory=True) #5
+ self.runCmd('expression 1', check=False, inHistory=True) #6
+ self.runCmd('type summary list -w default', check=False, inHistory=True) #7
+ self.runCmd('version', check=False, inHistory=True) #8
+ self.runCmd('frame select 1', check=False, inHistory=True) #9
+
+ self.expect ("command history -s 3 -c 3", inHistory=True,
+ substrs = ['3: memory write','4: log list','5: disassemble'])
+
+ self.expect ("command history -s 3 -e 3", inHistory=True,
+ substrs = ['3: memory write'])
+
+ self.expect ("command history -s 6 -e 7", inHistory=True,
+ substrs = ['6: expression 1','7: type summary list -w default'])
+
+ self.expect ("command history -c 2", inHistory=True,
+ substrs = ['0: breakpoint list','1: register read'])
+
+ self.expect ("command history -e 3 -c 1", inHistory=True,
+ substrs = ['3: memory write'])
+
+ self.expect ("command history -e 2", inHistory=True,
+ substrs = ['0: breakpoint list','1: register read','2: apropos hello'])
+
+ self.expect ("command history -s 12", inHistory=True,
+ substrs = ['12: command history -s 6 -e 7','13: command history -c 2','14: command history -e 3 -c 1','15: command history -e 2','16: command history -s 12'])
+
+ self.expect ("command history -s end -c 3", inHistory=True,
+ substrs = ['15: command history -e 2','16: command history -s 12','17: command history -s end -c 3'])
+
+ self.expect ("command history -s end -e 15", inHistory=True,
+ substrs = ['15: command history -e 2','16: command history -s 12','17: command history -s end -c 3','command history -s end -e 15'])
+
+ self.expect ("command history -s 5 -c 1", inHistory=True,
+ substrs = ['5: disassemble'])
+
+ self.expect ("command history -c 1 -s 5", inHistory=True,
+ substrs = ['5: disassemble'])
+
+ self.expect ("command history -c 1 -e 3", inHistory=True,
+ substrs = ['3: memory write'])
+
+ self.expect ("command history -c 1 -e 3 -s 5",error=True, inHistory=True,
+ substrs = ['error: --count, --start-index and --end-index cannot be all specified in the same invocation'])
diff --git a/packages/Python/lldbsuite/test/functionalities/command_regex/.categories b/packages/Python/lldbsuite/test/functionalities/command_regex/.categories
new file mode 100644
index 000000000000..3a3f4df6416b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_regex/.categories
@@ -0,0 +1 @@
+cmdline
diff --git a/packages/Python/lldbsuite/test/functionalities/command_regex/TestCommandRegex.py b/packages/Python/lldbsuite/test/functionalities/command_regex/TestCommandRegex.py
new file mode 100644
index 000000000000..2c48efa863b4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_regex/TestCommandRegex.py
@@ -0,0 +1,56 @@
+"""
+Test lldb 'commands regex' command which allows the user to create a regular expression command.
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class CommandRegexTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureHostWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ @no_debug_info_test
+ def test_command_regex(self):
+ """Test a simple scenario of 'command regex' invocation and subsequent use."""
+ import pexpect
+ prompt = "(lldb) "
+ regex_prompt = "Enter one of more sed substitution commands in the form: 's/<regex>/<subst>/'.\r\nTerminate the substitution list with an empty line.\r\n"
+ regex_prompt1 = "\r\n"
+
+ child = pexpect.spawn('%s %s' % (lldbtest_config.lldbExec, self.lldbOption))
+ # Turn on logging for what the child sends back.
+ if self.TraceOn():
+ child.logfile_read = sys.stdout
+ # So that the spawned lldb session gets shutdown durng teardown.
+ self.child = child
+
+ # Substitute 'Help!' for 'help' using the 'commands regex' mechanism.
+ child.expect_exact(prompt)
+ child.sendline("command regex 'Help__'")
+ child.expect_exact(regex_prompt)
+ child.sendline('s/^$/help/')
+ child.expect_exact(regex_prompt1)
+ child.sendline('')
+ child.expect_exact(prompt)
+ # Help!
+ child.sendline('Help__')
+ # If we see the familiar 'help' output, the test is done.
+ child.expect('Debugger commands:')
+ # Try and incorrectly remove "Help__" using "command unalias" and verify we fail
+ child.sendline('command unalias Help__')
+ child.expect_exact("error: 'Help__' is not an alias, it is a debugger command which can be removed using the 'command delete' command")
+ child.expect_exact(prompt)
+
+ # Delete the regex command using "command delete"
+ child.sendline('command delete Help__')
+ child.expect_exact(prompt)
+ # Verify the command was removed
+ child.sendline('Help__')
+ child.expect_exact("error: 'Help__' is not a valid command")
+ child.expect_exact(prompt)
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/.categories b/packages/Python/lldbsuite/test/functionalities/command_script/.categories
new file mode 100644
index 000000000000..3a3f4df6416b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/.categories
@@ -0,0 +1 @@
+cmdline
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/Makefile b/packages/Python/lldbsuite/test/functionalities/command_script/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/TestCommandScript.py b/packages/Python/lldbsuite/test/functionalities/command_script/TestCommandScript.py
new file mode 100644
index 000000000000..542ee7a1e5f3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/TestCommandScript.py
@@ -0,0 +1,142 @@
+"""
+Test lldb Python commands.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class CmdPythonTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test (self):
+ self.build ()
+ self.pycmd_tests ()
+
+ def pycmd_tests (self):
+ self.runCmd("command source py_import")
+
+ # Verify command that specifies eCommandRequiresTarget returns failure
+ # without a target.
+ self.expect('targetname',
+ substrs = ['a.out'], matching=False, error=True)
+
+ exe = os.path.join (os.getcwd(), "a.out")
+ self.expect("file " + exe,
+ patterns = [ "Current executable set to .*a.out" ])
+
+ self.expect('targetname',
+ substrs = ['a.out'], matching=True, error=False)
+
+ # This is the function to remove the custom commands in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('command script delete welcome', check=False)
+ self.runCmd('command script delete targetname', check=False)
+ self.runCmd('command script delete longwait', check=False)
+ self.runCmd('command script delete mysto', check=False)
+ self.runCmd('command script delete tell_sync', check=False)
+ self.runCmd('command script delete tell_async', check=False)
+ self.runCmd('command script delete tell_curr', check=False)
+ self.runCmd('command script delete bug11569', check=False)
+ self.runCmd('command script delete takes_exe_ctx', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ # Interact with debugger in synchronous mode
+ self.setAsync(False)
+
+ # We don't want to display the stdout if not in TraceOn() mode.
+ if not self.TraceOn():
+ self.HideStdout()
+
+ self.expect('welcome Enrico',
+ substrs = ['Hello Enrico, welcome to LLDB']);
+
+ self.expect("help welcome",
+ substrs = ['Just a docstring for welcome_impl',
+ 'A command that says hello to LLDB users'])
+
+ self.expect("help",
+ substrs = ['For more information run',
+ 'welcome'])
+
+ self.expect("help -a",
+ substrs = ['For more information run',
+ 'welcome'])
+
+ self.expect("help -u", matching=False,
+ substrs = ['For more information run'])
+
+ self.runCmd("command script delete welcome");
+
+ self.expect('welcome Enrico', matching=False, error=True,
+ substrs = ['Hello Enrico, welcome to LLDB']);
+
+ self.expect('targetname fail', error=True,
+ substrs = ['a test for error in command'])
+
+ self.expect('command script list',
+ substrs = ['targetname',
+ 'For more information run'])
+
+ self.expect("help targetname",
+ substrs = ['This', 'command', 'takes', '\'raw\'', 'input',
+ 'quote', 'stuff'])
+
+ self.expect("longwait",
+ substrs = ['Done; if you saw the delays I am doing OK'])
+
+ self.runCmd("b main")
+ self.runCmd("run")
+ self.runCmd("mysto 3")
+ self.expect("frame variable array",
+ substrs = ['[0] = 79630','[1] = 388785018','[2] = 0'])
+ self.runCmd("mysto 3")
+ self.expect("frame variable array",
+ substrs = ['[0] = 79630','[4] = 388785018','[5] = 0'])
+
+# we cannot use the stepover command to check for async execution mode since LLDB
+# seems to get confused when events start to queue up
+ self.expect("tell_sync",
+ substrs = ['running sync'])
+ self.expect("tell_async",
+ substrs = ['running async'])
+ self.expect("tell_curr",
+ substrs = ['I am running sync'])
+
+# check that the execution context is passed in to commands that ask for it
+ self.expect("takes_exe_ctx", substrs = ["a.out"])
+
+ # Test that a python command can redefine itself
+ self.expect('command script add -f foobar welcome -h "just some help"')
+
+ self.runCmd("command script clear")
+
+ # Test that re-defining an existing command works
+ self.runCmd('command script add my_command --class welcome.WelcomeCommand')
+ self.expect('my_command Blah', substrs = ['Hello Blah, welcome to LLDB'])
+
+ self.runCmd('command script add my_command --class welcome.TargetnameCommand')
+ self.expect('my_command', substrs = ['a.out'])
+
+ self.runCmd("command script clear")
+
+ self.expect('command script list', matching=False,
+ substrs = ['targetname',
+ 'longwait'])
+
+ self.expect('command script add -f foobar frame', error=True,
+ substrs = ['cannot add command'])
+
+ # http://llvm.org/bugs/show_bug.cgi?id=11569
+ # LLDBSwigPythonCallCommand crashes when a command script returns an object
+ self.runCmd('command script add -f bug11569 bug11569')
+ # This should not crash.
+ self.runCmd('bug11569', check=False)
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/bug11569.py b/packages/Python/lldbsuite/test/functionalities/command_script/bug11569.py
new file mode 100644
index 000000000000..93897d88098f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/bug11569.py
@@ -0,0 +1,7 @@
+def bug11569(debugger, args, result, dict):
+ """
+ http://llvm.org/bugs/show_bug.cgi?id=11569
+ LLDBSwigPythonCallCommand crashes when a command script returns an object.
+ """
+ return ["return", "a", "non-string", "should", "not", "crash", "LLDB"];
+
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/import/Makefile b/packages/Python/lldbsuite/test/functionalities/command_script/import/Makefile
new file mode 100644
index 000000000000..9374aef487fe
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/import/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+EXE := hello_world
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/import/TestImport.py b/packages/Python/lldbsuite/test/functionalities/command_script/import/TestImport.py
new file mode 100644
index 000000000000..691045ae82ed
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/import/TestImport.py
@@ -0,0 +1,73 @@
+"""Test custom import command to import files by path."""
+
+from __future__ import print_function
+
+
+
+import os, sys, time
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class ImportTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_import_command(self):
+ """Import some Python scripts by path and test them"""
+ self.run_test()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+
+ def run_test(self):
+ """Import some Python scripts by path and test them."""
+
+ # This is the function to remove the custom commands in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('command script delete foo2cmd', check=False)
+ self.runCmd('command script delete foocmd', check=False)
+ self.runCmd('command script delete foobarcmd', check=False)
+ self.runCmd('command script delete barcmd', check=False)
+ self.runCmd('command script delete barothercmd', check=False)
+ self.runCmd('command script delete TPcommandA', check=False)
+ self.runCmd('command script delete TPcommandB', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.runCmd("command script import ./foo/foo.py --allow-reload")
+ self.runCmd("command script import ./foo/foo2.py --allow-reload")
+ self.runCmd("command script import ./foo/bar/foobar.py --allow-reload")
+ self.runCmd("command script import ./bar/bar.py --allow-reload")
+
+ self.expect("command script import ./nosuchfile.py",
+ error=True, startstr='error: module importing failed')
+ self.expect("command script import ./nosuchfolder/",
+ error=True, startstr='error: module importing failed')
+ self.expect("command script import ./foo/foo.py", error=False)
+
+ self.runCmd("command script import --allow-reload ./thepackage")
+ self.expect("TPcommandA",substrs=["hello world A"])
+ self.expect("TPcommandB",substrs=["hello world B"])
+
+ self.runCmd("script import dummymodule")
+ self.expect("command script import ./dummymodule.py", error=False)
+ self.expect("command script import --allow-reload ./dummymodule.py", error=False)
+
+ self.runCmd("command script add -f foo.foo_function foocmd")
+ self.runCmd("command script add -f foobar.foo_function foobarcmd")
+ self.runCmd("command script add -f bar.bar_function barcmd")
+ self.expect("foocmd hello",
+ substrs = ['foo says', 'hello'])
+ self.expect("foo2cmd hello",
+ substrs = ['foo2 says', 'hello'])
+ self.expect("barcmd hello",
+ substrs = ['barutil says', 'bar told me', 'hello'])
+ self.expect("barothercmd hello",
+ substrs = ['barutil says', 'bar told me', 'hello'])
+ self.expect("foobarcmd hello",
+ substrs = ['foobar says', 'hello'])
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/import/bar/bar.py b/packages/Python/lldbsuite/test/functionalities/command_script/import/bar/bar.py
new file mode 100644
index 000000000000..bbc41f3b217d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/import/bar/bar.py
@@ -0,0 +1,12 @@
+from __future__ import print_function
+
+def bar_function(debugger, args, result, dict):
+ global UtilityModule
+ print(UtilityModule.barutil_function("bar told me " + args), file=result)
+ return None
+
+def __lldb_init_module(debugger, session_dict):
+ global UtilityModule
+ UtilityModule = __import__("barutil")
+ debugger.HandleCommand("command script add -f bar.bar_function barothercmd")
+ return None \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/import/bar/barutil.py b/packages/Python/lldbsuite/test/functionalities/command_script/import/bar/barutil.py
new file mode 100644
index 000000000000..0d3d2eb1b2d7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/import/bar/barutil.py
@@ -0,0 +1,2 @@
+def barutil_function(x):
+ return "barutil says: " + x
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/import/dummymodule.py b/packages/Python/lldbsuite/test/functionalities/command_script/import/dummymodule.py
new file mode 100644
index 000000000000..dcc724ec9c23
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/import/dummymodule.py
@@ -0,0 +1,2 @@
+def no_useful_code(foo):
+ return foo
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/bar/foobar.py b/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/bar/foobar.py
new file mode 100644
index 000000000000..659ded22c901
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/bar/foobar.py
@@ -0,0 +1,5 @@
+from __future__ import print_function
+
+def foo_function(debugger, args, result, dict):
+ print("foobar says " + args, file=result)
+ return None
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/foo.py b/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/foo.py
new file mode 100644
index 000000000000..51cc0c3bab19
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/foo.py
@@ -0,0 +1,5 @@
+from __future__ import print_function
+
+def foo_function(debugger, args, result, dict):
+ print("foo says " + args, file=result)
+ return None
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/foo2.py b/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/foo2.py
new file mode 100644
index 000000000000..6863454ca6ef
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/import/foo/foo2.py
@@ -0,0 +1,9 @@
+from __future__ import print_function
+
+def foo2_function(debugger, args, result, dict):
+ print("foo2 says " + args, file=result)
+ return None
+
+def __lldb_init_module(debugger, session_dict):
+ debugger.HandleCommand("command script add -f foo2.foo2_function foo2cmd")
+ return None \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/import/main.c b/packages/Python/lldbsuite/test/functionalities/command_script/import/main.c
new file mode 100644
index 000000000000..dffc8c77b04c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/import/main.c
@@ -0,0 +1,15 @@
+#include <stdio.h>
+
+int main(int argc, char const *argv[]) {
+ printf("Hello world.\n"); // Set break point at this line.
+ if (argc == 1)
+ return 0;
+
+ // Waiting to be attached by the debugger, otherwise.
+ char line[100];
+ while (fgets(line, sizeof(line), stdin)) { // Waiting to be attached...
+ printf("input line=>%s\n", line);
+ }
+
+ printf("Exiting now\n");
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/Makefile b/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/Makefile
new file mode 100644
index 000000000000..7913aaa4b746
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/Makefile
@@ -0,0 +1,3 @@
+LEVEL = ../../../../make
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/TestRdar12586188.py b/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/TestRdar12586188.py
new file mode 100644
index 000000000000..9800a08c06de
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/TestRdar12586188.py
@@ -0,0 +1,31 @@
+"""Check that we handle an ImportError in a special way when command script importing files."""
+
+from __future__ import print_function
+
+
+
+import os, sys, time
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class Rdar12586188TestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_rdar12586188_command(self):
+ """Check that we handle an ImportError in a special way when command script importing files."""
+ self.run_test()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+
+ def run_test(self):
+ """Check that we handle an ImportError in a special way when command script importing files."""
+
+ self.expect("command script import ./fail12586188.py --allow-reload",
+ error=True, substrs = ['raise ImportError("I do not want to be imported")'])
+ self.expect("command script import ./fail212586188.py --allow-reload",
+ error=True, substrs = ['raise ValueError("I do not want to be imported")'])
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/fail12586188.py b/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/fail12586188.py
new file mode 100644
index 000000000000..add85a73f853
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/fail12586188.py
@@ -0,0 +1,4 @@
+def f(x):
+ return x + 1
+
+raise ImportError("I do not want to be imported")
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/fail212586188.py b/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/fail212586188.py
new file mode 100644
index 000000000000..1549a036590f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/import/rdar-12586188/fail212586188.py
@@ -0,0 +1,4 @@
+def f(x):
+ return x + 1
+
+raise ValueError("I do not want to be imported")
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/TPunitA.py b/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/TPunitA.py
new file mode 100644
index 000000000000..fb65305d205c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/TPunitA.py
@@ -0,0 +1,6 @@
+
+import six
+
+def command(debugger, command, result, internal_dict):
+ result.PutCString(six.u("hello world A"))
+ return None
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/TPunitB.py b/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/TPunitB.py
new file mode 100644
index 000000000000..60b31b89f6da
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/TPunitB.py
@@ -0,0 +1,6 @@
+
+import six
+
+def command(debugger, command, result, internal_dict):
+ result.PutCString(six.u("hello world B"))
+ return None
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/__init__.py b/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/__init__.py
new file mode 100644
index 000000000000..faa4e3b0cbff
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/import/thepackage/__init__.py
@@ -0,0 +1,6 @@
+import TPunitA
+import TPunitB
+
+def __lldb_init_module(debugger,*args):
+ debugger.HandleCommand("command script add -f thepackage.TPunitA.command TPcommandA")
+ debugger.HandleCommand("command script add -f thepackage.TPunitB.command TPcommandB")
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/main.cpp b/packages/Python/lldbsuite/test/functionalities/command_script/main.cpp
new file mode 100644
index 000000000000..0b24cb73a619
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/main.cpp
@@ -0,0 +1,70 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <cstdlib>
+#include <cstring>
+#include <string>
+#include <fstream>
+#include <iostream>
+
+int
+product (int x, int y)
+{
+ int result = x * y;
+ return result;
+}
+
+int
+sum (int a, int b)
+{
+ int result = a + b;
+ return result;
+}
+
+int
+strange_max (int m, int n)
+{
+ if (m > n)
+ return m;
+ else if (n > m)
+ return n;
+ else
+ return 0;
+}
+
+int
+foo (int i, int j)
+{
+ if (strange_max (i, j) == i)
+ return product (i, j);
+ else if (strange_max (i, j) == j)
+ return sum (i, j);
+ else
+ return product (sum (i, i), sum (j, j));
+}
+
+int
+main(int argc, char const *argv[])
+{
+
+ int array[9];
+ memset(array,0,9*sizeof(int));
+
+ array[0] = foo (1238, 78392);
+ array[1] = foo (379265, 23674);
+ array[2] = foo (872934, 234);
+ array[3] = foo (1238, 78392);
+ array[4] = foo (379265, 23674);
+ array[5] = foo (872934, 234);
+ array[6] = foo (1238, 78392);
+ array[7] = foo (379265, 23674);
+ array[8] = foo (872934, 234);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/mysto.py b/packages/Python/lldbsuite/test/functionalities/command_script/mysto.py
new file mode 100644
index 000000000000..656cd1502930
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/mysto.py
@@ -0,0 +1,23 @@
+from __future__ import print_function
+
+import lldb
+import sys
+import os
+import time
+
+def StepOver(debugger, args, result, dict):
+ """
+ Step over a given number of times instead of only just once
+ """
+ arg_split = args.split(" ")
+ print(type(arg_split))
+ count = int(arg_split[0])
+ for i in range(0,count):
+ debugger.GetSelectedTarget().GetProcess().GetSelectedThread().StepOver(lldb.eOnlyThisThread)
+ print("step<%d>"%i)
+
+def __lldb_init_module(debugger, session_dict):
+ # by default, --synchronicity is set to synchronous
+ debugger.HandleCommand("command script add -f mysto.StepOver mysto")
+ return None
+
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/py_import b/packages/Python/lldbsuite/test/functionalities/command_script/py_import
new file mode 100644
index 000000000000..169daacc1a83
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/py_import
@@ -0,0 +1,12 @@
+script import sys, os
+script sys.path.append(os.path.join(os.getcwd(), os.pardir))
+script import welcome
+script import bug11569
+command script add welcome --class welcome.WelcomeCommand
+command script add targetname --class welcome.TargetnameCommand
+command script add longwait --function welcome.print_wait_impl
+command script import mysto.py --allow-reload
+command script add tell_sync --function welcome.check_for_synchro --synchronicity sync
+command script add tell_async --function welcome.check_for_synchro --synchronicity async
+command script add tell_curr --function welcome.check_for_synchro --synchronicity curr
+command script add takes_exe_ctx --function welcome.takes_exe_ctx
diff --git a/packages/Python/lldbsuite/test/functionalities/command_script/welcome.py b/packages/Python/lldbsuite/test/functionalities/command_script/welcome.py
new file mode 100644
index 000000000000..5dbf09fbbec2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_script/welcome.py
@@ -0,0 +1,46 @@
+from __future__ import print_function
+import lldb, sys
+
+class WelcomeCommand(object):
+ def __init__(self, debugger, session_dict):
+ pass
+
+ def get_short_help(self):
+ return "Just a docstring for welcome_impl\nA command that says hello to LLDB users"
+
+ def __call__(self, debugger, args, exe_ctx, result):
+ print('Hello ' + args + ', welcome to LLDB', file=result);
+ return None;
+
+class TargetnameCommand(object):
+ def __init__(self, debugger, session_dict):
+ pass
+
+ def __call__(self, debugger, args, exe_ctx, result):
+ target = debugger.GetSelectedTarget()
+ file = target.GetExecutable()
+ print('Current target ' + file.GetFilename(), file=result)
+ if args == 'fail':
+ result.SetError('a test for error in command')
+
+ def get_flags(self):
+ return lldb.eCommandRequiresTarget
+
+def print_wait_impl(debugger, args, result, dict):
+ result.SetImmediateOutputFile(sys.stdout)
+ print('Trying to do long task..', file=result)
+ import time
+ time.sleep(1)
+ print('Still doing long task..', file=result)
+ time.sleep(1)
+ print('Done; if you saw the delays I am doing OK', file=result)
+
+def check_for_synchro(debugger, args, result, dict):
+ if debugger.GetAsync() == True:
+ print('I am running async', file=result)
+ if debugger.GetAsync() == False:
+ print('I am running sync', file=result)
+
+def takes_exe_ctx(debugger, args, exe_ctx, result, dict):
+ print(str(exe_ctx.GetTarget()), file=result)
+
diff --git a/packages/Python/lldbsuite/test/functionalities/command_source/.categories b/packages/Python/lldbsuite/test/functionalities/command_source/.categories
new file mode 100644
index 000000000000..3a3f4df6416b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_source/.categories
@@ -0,0 +1 @@
+cmdline
diff --git a/packages/Python/lldbsuite/test/functionalities/command_source/.lldb b/packages/Python/lldbsuite/test/functionalities/command_source/.lldb
new file mode 100644
index 000000000000..c544523832e7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_source/.lldb
@@ -0,0 +1 @@
+script import my
diff --git a/packages/Python/lldbsuite/test/functionalities/command_source/TestCommandSource.py b/packages/Python/lldbsuite/test/functionalities/command_source/TestCommandSource.py
new file mode 100644
index 000000000000..013803e698af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_source/TestCommandSource.py
@@ -0,0 +1,36 @@
+"""
+Test that lldb command "command source" works correctly.
+
+See also http://llvm.org/viewvc/llvm-project?view=rev&revision=109673.
+"""
+
+from __future__ import print_function
+
+
+
+import os, sys
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class CommandSourceTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @no_debug_info_test
+ def test_command_source(self):
+ """Test that lldb command "command source" works correctly."""
+
+ # Sourcing .lldb in the current working directory, which in turn imports
+ # the "my" package that defines the date() function.
+ self.runCmd("command source .lldb")
+
+ # Python should evaluate "my.date()" successfully.
+ command_interpreter = self.dbg.GetCommandInterpreter()
+ self.assertTrue(command_interpreter, VALID_COMMAND_INTERPRETER)
+ result = lldb.SBCommandReturnObject()
+ command_interpreter.HandleCommand("script my.date()", result)
+
+ import datetime
+ self.expect(result.GetOutput(), "script my.date() runs successfully",
+ exe=False,
+ substrs = [str(datetime.date.today())])
diff --git a/packages/Python/lldbsuite/test/functionalities/command_source/my.py b/packages/Python/lldbsuite/test/functionalities/command_source/my.py
new file mode 100644
index 000000000000..cb2fd012e4bd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/command_source/my.py
@@ -0,0 +1,6 @@
+from __future__ import print_function
+
+def date():
+ import datetime
+ today = datetime.date.today()
+ print(today)
diff --git a/packages/Python/lldbsuite/test/functionalities/completion/.categories b/packages/Python/lldbsuite/test/functionalities/completion/.categories
new file mode 100644
index 000000000000..3a3f4df6416b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/completion/.categories
@@ -0,0 +1 @@
+cmdline
diff --git a/packages/Python/lldbsuite/test/functionalities/completion/Makefile b/packages/Python/lldbsuite/test/functionalities/completion/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/completion/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/completion/TestCompletion.py b/packages/Python/lldbsuite/test/functionalities/completion/TestCompletion.py
new file mode 100644
index 000000000000..d7aab03c0830
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/completion/TestCompletion.py
@@ -0,0 +1,324 @@
+"""
+Test the lldb command line completion mechanism.
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class CommandLineCompletionTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @classmethod
+ def classCleanup(cls):
+ """Cleanup the test byproducts."""
+ try:
+ os.remove("child_send.txt")
+ os.remove("child_read.txt")
+ except:
+ pass
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_at(self):
+ """Test that 'at' completes to 'attach '."""
+ self.complete_from_to('at', 'attach ')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_de(self):
+ """Test that 'de' completes to 'detach '."""
+ self.complete_from_to('de', 'detach ')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_process_attach_dash_dash_con(self):
+ """Test that 'process attach --con' completes to 'process attach --continue '."""
+ self.complete_from_to('process attach --con', 'process attach --continue ')
+
+ # <rdar://problem/11052829>
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_infinite_loop_while_completing(self):
+ """Test that 'process print hello\' completes to itself and does not infinite loop."""
+ self.complete_from_to('process print hello\\', 'process print hello\\',
+ turn_off_re_match=True)
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_watchpoint_co(self):
+ """Test that 'watchpoint co' completes to 'watchpoint command '."""
+ self.complete_from_to('watchpoint co', 'watchpoint command ')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_watchpoint_command_space(self):
+ """Test that 'watchpoint command ' completes to ['Available completions:', 'add', 'delete', 'list']."""
+ self.complete_from_to('watchpoint command ', ['Available completions:', 'add', 'delete', 'list'])
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_watchpoint_command_a(self):
+ """Test that 'watchpoint command a' completes to 'watchpoint command add '."""
+ self.complete_from_to('watchpoint command a', 'watchpoint command add ')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_watchpoint_set_variable_dash_w(self):
+ """Test that 'watchpoint set variable -w' completes to 'watchpoint set variable -w '."""
+ self.complete_from_to('watchpoint set variable -w', 'watchpoint set variable -w ')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_watchpoint_set_variable_dash_w_space(self):
+ """Test that 'watchpoint set variable -w ' completes to ['Available completions:', 'read', 'write', 'read_write']."""
+ self.complete_from_to('watchpoint set variable -w ', ['Available completions:', 'read', 'write', 'read_write'])
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_watchpoint_set_ex(self):
+ """Test that 'watchpoint set ex' completes to 'watchpoint set expression '."""
+ self.complete_from_to('watchpoint set ex', 'watchpoint set expression ')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_watchpoint_set_var(self):
+ """Test that 'watchpoint set var' completes to 'watchpoint set variable '."""
+ self.complete_from_to('watchpoint set var', 'watchpoint set variable ')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_watchpoint_set_variable_dash_w_read_underbar(self):
+ """Test that 'watchpoint set variable -w read_' completes to 'watchpoint set variable -w read_write'."""
+ self.complete_from_to('watchpoint set variable -w read_', 'watchpoint set variable -w read_write')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_help_fi(self):
+ """Test that 'help fi' completes to ['Available completions:', 'file', 'finish']."""
+ self.complete_from_to('help fi', ['Available completions:', 'file', 'finish'])
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_help_watchpoint_s(self):
+ """Test that 'help watchpoint s' completes to 'help watchpoint set '."""
+ self.complete_from_to('help watchpoint s', 'help watchpoint set ')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_settings_append_target_er(self):
+ """Test that 'settings append target.er' completes to 'settings append target.error-path'."""
+ self.complete_from_to('settings append target.er', 'settings append target.error-path')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_settings_insert_after_target_en(self):
+ """Test that 'settings insert-after target.env' completes to 'settings insert-after target.env-vars'."""
+ self.complete_from_to('settings insert-after target.env', 'settings insert-after target.env-vars')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_settings_insert_before_target_en(self):
+ """Test that 'settings insert-before target.env' completes to 'settings insert-before target.env-vars'."""
+ self.complete_from_to('settings insert-before target.env', 'settings insert-before target.env-vars')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_settings_replace_target_ru(self):
+ """Test that 'settings replace target.ru' completes to 'settings replace target.run-args'."""
+ self.complete_from_to('settings replace target.ru', 'settings replace target.run-args')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_settings_s(self):
+ """Test that 'settings s' completes to ['Available completions:', 'set', 'show']."""
+ self.complete_from_to('settings s', ['Available completions:', 'set', 'show'])
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_settings_set_th(self):
+ """Test that 'settings set th' completes to 'settings set thread-format'."""
+ self.complete_from_to('settings set th', 'settings set thread-format')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_settings_s_dash(self):
+ """Test that 'settings set -' completes to 'settings set -g'."""
+ self.complete_from_to('settings set -', 'settings set -g')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_settings_clear_th(self):
+ """Test that 'settings clear th' completes to 'settings clear thread-format'."""
+ self.complete_from_to('settings clear th', 'settings clear thread-format')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_settings_set_ta(self):
+ """Test that 'settings set ta' completes to 'settings set target.'."""
+ self.complete_from_to('settings set target.ma', 'settings set target.max-')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_settings_set_target_exec(self):
+ """Test that 'settings set target.exec' completes to 'settings set target.exec-search-paths '."""
+ self.complete_from_to('settings set target.exec', 'settings set target.exec-search-paths')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_settings_set_target_pr(self):
+ """Test that 'settings set target.pr' completes to ['Available completions:',
+ 'target.prefer-dynamic-value', 'target.process.']."""
+ self.complete_from_to('settings set target.pr',
+ ['Available completions:',
+ 'target.prefer-dynamic-value',
+ 'target.process.'])
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_settings_set_target_process(self):
+ """Test that 'settings set target.process' completes to 'settings set target.process.'."""
+ self.complete_from_to('settings set target.process', 'settings set target.process.')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_settings_set_target_process_dot(self):
+ """Test that 'settings set target.process.t' completes to 'settings set target.process.thread.'."""
+ self.complete_from_to('settings set target.process.t', 'settings set target.process.thread.')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_settings_set_target_process_thread_dot(self):
+ """Test that 'settings set target.process.thread.' completes to ['Available completions:',
+ 'target.process.thread.step-avoid-regexp', 'target.process.thread.trace-thread']."""
+ self.complete_from_to('settings set target.process.thread.',
+ ['Available completions:',
+ 'target.process.thread.step-avoid-regexp',
+ 'target.process.thread.trace-thread'])
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_target_space(self):
+ """Test that 'target ' completes to ['Available completions:', 'create', 'delete', 'list',
+ 'modules', 'select', 'stop-hook', 'variable']."""
+ self.complete_from_to('target ',
+ ['Available completions:', 'create', 'delete', 'list',
+ 'modules', 'select', 'stop-hook', 'variable'])
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_target_create_dash_co(self):
+ """Test that 'target create --co' completes to 'target variable --core '."""
+ self.complete_from_to('target create --co', 'target create --core ')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @skipIfFreeBSD # timing out on the FreeBSD buildbot
+ @no_debug_info_test
+ def test_target_va(self):
+ """Test that 'target va' completes to 'target variable '."""
+ self.complete_from_to('target va', 'target variable ')
+
+ @expectedFailureHostWindows("llvm.org/pr24679")
+ @expectedFailureDarwin("llvm.org/pr25485")
+ def test_symbol_name(self):
+ self.build()
+ self.complete_from_to('''file a.out
+ breakpoint set -n Fo''',
+ 'breakpoint set -n Foo::Bar(int,\\ int)',
+ turn_off_re_match=True)
+
+ def complete_from_to(self, str_input, patterns, turn_off_re_match=False):
+ """Test that the completion mechanism completes str_input to patterns,
+ where patterns could be a pattern-string or a list of pattern-strings"""
+ import pexpect
+ # Patterns should not be None in order to proceed.
+ self.assertFalse(patterns is None)
+ # And should be either a string or list of strings. Check for list type
+ # below, if not, make a list out of the singleton string. If patterns
+ # is not a string or not a list of strings, there'll be runtime errors
+ # later on.
+ if not isinstance(patterns, list):
+ patterns = [patterns]
+
+ # The default lldb prompt.
+ prompt = "(lldb) "
+
+ # So that the child gets torn down after the test.
+ self.child = pexpect.spawn(lldbtest_config.lldbExec,
+ [self.lldbOption] + ['--no-use-colors'])
+ child = self.child
+ # Turn on logging for input/output to/from the child.
+ with open('child_send.txt', 'w') as f_send:
+ with open('child_read.txt', 'w') as f_read:
+ child.logfile_send = f_send
+ child.logfile_read = f_read
+
+ child.expect_exact(prompt)
+ child.setecho(True)
+ # Sends str_input and a Tab to invoke the completion machinery.
+ child.send("%s\t" % str_input)
+ child.sendline('')
+ child.expect_exact(prompt)
+ child.sendline('')
+ child.expect_exact(prompt)
+
+ # Now that the necessary logging is done, restore logfile to None to
+ # stop further logging.
+ child.logfile_send = None
+ child.logfile_read = None
+
+ with open('child_send.txt', 'r') as fs:
+ if self.TraceOn():
+ print("\n\nContents of child_send.txt:")
+ print(fs.read())
+ with open('child_read.txt', 'r') as fr:
+ from_child = fr.read()
+ if self.TraceOn():
+ print("\n\nContents of child_read.txt:")
+ print(from_child)
+
+ # The matching could be verbatim or using generic re pattern.
+ for p in patterns:
+ # Test that str_input completes to our patterns or substrings.
+ # If each pattern/substring matches from_child, the completion mechanism works!
+ if turn_off_re_match:
+ self.expect(from_child, msg=COMPLETION_MSG(str_input, p), exe=False,
+ substrs = [p])
+ else:
+ self.expect(from_child, msg=COMPLETION_MSG(str_input, p), exe=False,
+ patterns = [p])
diff --git a/packages/Python/lldbsuite/test/functionalities/completion/main.cpp b/packages/Python/lldbsuite/test/functionalities/completion/main.cpp
new file mode 100644
index 000000000000..b408720d2cdc
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/completion/main.cpp
@@ -0,0 +1,14 @@
+class Foo
+{
+public:
+ int Bar(int x, int y)
+ {
+ return x + y;
+ }
+};
+
+int main()
+{
+ Foo f;
+ f.Bar(1, 2);
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/conditional_break/.lldb b/packages/Python/lldbsuite/test/functionalities/conditional_break/.lldb
new file mode 100644
index 000000000000..4be90efee23b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/conditional_break/.lldb
@@ -0,0 +1,3 @@
+breakpoint set -n c
+command script import -r conditional_break.py
+breakpoint command add 1 -F "conditional_break.stop_if_called_from_a"
diff --git a/packages/Python/lldbsuite/test/functionalities/conditional_break/Makefile b/packages/Python/lldbsuite/test/functionalities/conditional_break/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/conditional_break/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/conditional_break/TestConditionalBreak.py b/packages/Python/lldbsuite/test/functionalities/conditional_break/TestConditionalBreak.py
new file mode 100644
index 000000000000..3ae7a20b4c7d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/conditional_break/TestConditionalBreak.py
@@ -0,0 +1,133 @@
+"""
+Test conditionally break on a function and inspect its variables.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+# rdar://problem/8532131
+# lldb not able to digest the clang-generated debug info correctly with respect to function name
+#
+# This class currently fails for clang as well as llvm-gcc.
+
+class ConditionalBreakTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @add_test_categories(['pyapi'])
+ def test_with_python(self):
+ """Exercise some thread and frame APIs to break if c() is called by a()."""
+ self.build()
+ self.do_conditional_break()
+
+ def test_with_command(self):
+ """Simulate a user using lldb commands to break on c() if called from a()."""
+ self.build()
+ self.simulate_conditional_break_by_user()
+
+ def do_conditional_break(self):
+ """Exercise some thread and frame APIs to break if c() is called by a()."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByName("c", exe)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ STOPPED_DUE_TO_BREAKPOINT)
+
+ # Find the line number where a's parent frame function is c.
+ line = line_number('main.c',
+ "// Find the line number where c's parent frame is a here.")
+
+ # Suppose we are only interested in the call scenario where c()'s
+ # immediate caller is a() and we want to find out the value passed from
+ # a().
+ #
+ # The 10 in range(10) is just an arbitrary number, which means we would
+ # like to try for at most 10 times.
+ for j in range(10):
+ if self.TraceOn():
+ print("j is: ", j)
+ thread = process.GetThreadAtIndex(0)
+
+ if thread.GetNumFrames() >= 2:
+ frame0 = thread.GetFrameAtIndex(0)
+ name0 = frame0.GetFunction().GetName()
+ frame1 = thread.GetFrameAtIndex(1)
+ name1 = frame1.GetFunction().GetName()
+ #lldbutil.print_stacktrace(thread)
+ self.assertTrue(name0 == "c", "Break on function c()")
+ if (name1 == "a"):
+ # By design, we know that a() calls c() only from main.c:27.
+ # In reality, similar logic can be used to find out the call
+ # site.
+ self.assertTrue(frame1.GetLineEntry().GetLine() == line,
+ "Immediate caller a() at main.c:%d" % line)
+
+ # And the local variable 'val' should have a value of (int) 3.
+ val = frame1.FindVariable("val")
+ self.assertTrue(val.GetTypeName() == "int", "'val' has int type")
+ self.assertTrue(val.GetValue() == "3", "'val' has a value of 3")
+ break
+
+ process.Continue()
+
+ def simulate_conditional_break_by_user(self):
+ """Simulate a user using lldb commands to break on c() if called from a()."""
+
+ # Sourcing .lldb in the current working directory, which sets the main
+ # executable, sets the breakpoint on c(), and adds the callback for the
+ # breakpoint such that lldb only stops when the caller of c() is a().
+ # the "my" package that defines the date() function.
+ if self.TraceOn():
+ print("About to source .lldb")
+
+ if not self.TraceOn():
+ self.HideStdout()
+
+ # Separate out the "file a.out" command from .lldb file, for the sake of
+ # remote testsuite.
+ self.runCmd("file a.out")
+ self.runCmd("command source .lldb")
+
+ self.runCmd ("break list")
+
+ if self.TraceOn():
+ print("About to run.")
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.runCmd ("break list")
+
+ if self.TraceOn():
+ print("Done running")
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped', 'stop reason = breakpoint'])
+
+ # The frame info for frame #0 points to a.out`c and its immediate caller
+ # (frame #1) points to a.out`a.
+
+ self.expect("frame info", "We should stop at c()",
+ substrs = ["a.out`c"])
+
+ # Select our parent frame as the current frame.
+ self.runCmd("frame select 1")
+ self.expect("frame info", "The immediate caller should be a()",
+ substrs = ["a.out`a"])
diff --git a/packages/Python/lldbsuite/test/functionalities/conditional_break/conditional_break.py b/packages/Python/lldbsuite/test/functionalities/conditional_break/conditional_break.py
new file mode 100644
index 000000000000..b30a34e56b14
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/conditional_break/conditional_break.py
@@ -0,0 +1,30 @@
+import sys
+import lldb
+
+def stop_if_called_from_a(frame, bp_loc, dict):
+
+ thread = frame.GetThread()
+ process = thread.GetProcess()
+ target = process.GetTarget()
+ dbg = target.GetDebugger()
+
+ # Perform synchronous interaction with the debugger.
+ old_async = dbg.GetAsync()
+ dbg.SetAsync(True)
+
+ # We check the call frames in order to stop only when the immediate caller
+ # of the leaf function c() is a(). If it's not the right caller, we ask the
+ # command interpreter to continue execution.
+
+ should_stop = True
+ if thread.GetNumFrames() >= 2:
+
+ if (thread.frames[0].function.name == 'c' and thread.frames[1].function.name == 'a'):
+ should_stop = True
+ else:
+ should_stop = False
+
+ dbg.SetAsync(old_async)
+ return should_stop
+
+
diff --git a/packages/Python/lldbsuite/test/functionalities/conditional_break/main.c b/packages/Python/lldbsuite/test/functionalities/conditional_break/main.c
new file mode 100644
index 000000000000..1329fd69a2e1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/conditional_break/main.c
@@ -0,0 +1,54 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+// This simple program is to demonstrate the capability of the lldb command
+// "breakpoint command add" to add a set of commands to a breakpoint to be
+// executed when the breakpoint is hit.
+//
+// In particular, we want to break within c(), but only if the immediate caller
+// is a().
+
+int a(int);
+int b(int);
+int c(int);
+
+int a(int val)
+{
+ if (val <= 1)
+ return b(val);
+ else if (val >= 3)
+ return c(val); // Find the line number where c's parent frame is a here.
+
+ return val;
+}
+
+int b(int val)
+{
+ return c(val);
+}
+
+int c(int val)
+{
+ return val + 3;
+}
+
+int main (int argc, char const *argv[])
+{
+ int A1 = a(1); // a(1) -> b(1) -> c(1)
+ printf("a(1) returns %d\n", A1);
+
+ int B2 = b(2); // b(2) -> c(2)
+ printf("b(2) returns %d\n", B2);
+
+ int A3 = a(3); // a(3) -> c(3)
+ printf("a(3) returns %d\n", A3);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/.categories b/packages/Python/lldbsuite/test/functionalities/data-formatter/.categories
new file mode 100644
index 000000000000..fe1da0247c62
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/.categories
@@ -0,0 +1 @@
+dataformatters
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/Makefile
new file mode 100644
index 000000000000..261658b10ae8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../../make
+
+OBJCXX_SOURCES := main.mm
+
+CFLAGS_EXTRAS += -w
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/TestFormattersBoolRefPtr.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/TestFormattersBoolRefPtr.py
new file mode 100644
index 000000000000..94cdfdfeb343
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/TestFormattersBoolRefPtr.py
@@ -0,0 +1,72 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import datetime
+import lldbsuite.test.lldbutil as lldbutil
+
+class DataFormatterBoolRefPtr(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipUnlessDarwin
+ def test_boolrefptr_with_run_command(self):
+ """Test the formatters we use for BOOL& and BOOL* in Objective-C."""
+ self.build()
+ self.boolrefptr_data_formatter_commands()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.mm', '// Set break point at this line.')
+
+ def boolrefptr_data_formatter_commands(self):
+ """Test the formatters we use for BOOL& and BOOL* in Objective-C."""
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.mm", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type synth clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ # Now check that we use the right summary for BOOL&
+ self.expect('frame variable yes_ref',
+ substrs = ['YES'])
+ self.expect('frame variable no_ref',
+ substrs = ['NO'])
+
+
+ # Now check that we use the right summary for BOOL*
+ self.expect('frame variable yes_ptr',
+ substrs = ['YES'])
+ self.expect('frame variable no_ptr',
+ substrs = ['NO'])
+
+
+ # Now check that we use the right summary for BOOL
+ self.expect('frame variable yes',
+ substrs = ['YES'])
+ self.expect('frame variable no',
+ substrs = ['NO'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/main.mm b/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/main.mm
new file mode 100644
index 000000000000..a2461fd9da91
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/boolreference/main.mm
@@ -0,0 +1,29 @@
+//===-- main.m ------------------------------------------------*- ObjC -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#import <Foundation/Foundation.h>
+
+int main (int argc, const char * argv[])
+{
+
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+
+ BOOL yes = YES;
+ BOOL no = NO;
+
+ BOOL &yes_ref = yes;
+ BOOL &no_ref = no;
+
+ BOOL* yes_ptr = &yes;
+ BOOL* no_ptr = &no;
+
+ [pool drain];// Set break point at this line.
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/Makefile
new file mode 100644
index 000000000000..9b06ad7d705a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Accelerate \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/TestCompactVectors.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/TestCompactVectors.py
new file mode 100644
index 000000000000..7cd2a49b4717
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/TestCompactVectors.py
@@ -0,0 +1,58 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class CompactVectorsFormattingTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ @skipUnlessDarwin
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type summary clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.expect('frame variable',
+ substrs = ['(vFloat) valueFL = (1.25, 0, 0.25, 0)',
+ '(int16_t [8]) valueI16 = (1, 0, 4, 0, 0, 1, 0, 4)',
+ '(int32_t [4]) valueI32 = (1, 0, 4, 0)',
+ '(vDouble) valueDL = (1.25, 2.25)',
+ '(vUInt8) valueU8 = (0x01, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)',
+ '(vUInt16) valueU16 = (1, 0, 4, 0, 0, 1, 0, 4)',
+ '(vUInt32) valueU32 = (1, 2, 3, 4)',
+ "(vSInt8) valueS8 = (1, 0, 4, 0, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0)",
+ '(vSInt16) valueS16 = (1, 0, 4, 0, 0, 1, 0, 4)',
+ '(vSInt32) valueS32 = (4, 3, 2, 1)',
+ '(vBool32) valueBool32 = (0, 1, 0, 1)'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/main.cpp
new file mode 100644
index 000000000000..bbbd823ec313
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/compactvectors/main.cpp
@@ -0,0 +1,26 @@
+ //===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <Accelerate/Accelerate.h>
+
+int main()
+{
+ vFloat valueFL = {1.25,0,0.25,0};
+ vDouble valueDL = {1.25,2.25};
+ int16_t valueI16[8] = {1,0,4,0,0,1,0,4};
+ int32_t valueI32[4] = {1,0,4,0};
+ vUInt8 valueU8 = {1,0,4,0,0,1,0,4};
+ vUInt16 valueU16 = {1,0,4,0,0,1,0,4};
+ vUInt32 valueU32 = {1,2,3,4};
+ vSInt8 valueS8 = {1,0,4,0,0,1,0,4};
+ vSInt16 valueS16 = {1,0,4,0,0,1,0,4};
+ vSInt32 valueS32 = {4,3,2,1};
+ vBool32 valueBool32 = {false,true,false,true};
+ return 0; // Set break point at this line.
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/TestDataFormatterAdv.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/TestDataFormatterAdv.py
new file mode 100644
index 000000000000..8166d1540ca3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/TestDataFormatterAdv.py
@@ -0,0 +1,285 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class AdvDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.runCmd("type summary add --summary-string \"pippo\" \"i_am_cool\"")
+
+ self.runCmd("type summary add --summary-string \"pluto\" -x \"i_am_cool[a-z]*\"")
+
+ self.expect("frame variable cool_boy",
+ substrs = ['pippo'])
+
+ self.expect("frame variable cooler_boy",
+ substrs = ['pluto'])
+
+ self.runCmd("type summary delete i_am_cool")
+
+ self.expect("frame variable cool_boy",
+ substrs = ['pluto'])
+
+ self.runCmd("type summary clear")
+
+ self.runCmd("type summary add --summary-string \"${var[]}\" -x \"int \\[[0-9]\\]")
+
+ self.expect("frame variable int_array",
+ substrs = ['1,2,3,4,5'])
+
+ # this will fail if we don't do [] as regex correctly
+ self.runCmd('type summary add --summary-string "${var[].integer}" "i_am_cool[]')
+
+ self.expect("frame variable cool_array",
+ substrs = ['1,1,1,1,6'])
+
+ self.runCmd("type summary clear")
+
+ self.runCmd("type summary add --summary-string \"${var[1-0]%x}\" \"int\"")
+
+ self.expect("frame variable iAmInt",
+ substrs = ['01'])
+
+ self.runCmd("type summary add --summary-string \"${var[0-1]%x}\" \"int\"")
+
+ self.expect("frame variable iAmInt",
+ substrs = ['01'])
+
+ self.runCmd("type summary clear")
+
+ self.runCmd("type summary add --summary-string \"${var[0-1]%x}\" int")
+ self.runCmd("type summary add --summary-string \"${var[0-31]%x}\" float")
+
+ self.expect("frame variable *pointer",
+ substrs = ['0x',
+ '2'])
+
+ # check fix for <rdar://problem/11338654> LLDB crashes when using a "type summary" that uses bitfields with no format
+ self.runCmd("type summary add --summary-string \"${var[0-1]}\" int")
+ self.expect("frame variable iAmInt",
+ substrs = ['9 1'])
+
+ self.expect("frame variable cool_array[3].floating",
+ substrs = ['0x'])
+
+ self.runCmd("type summary add --summary-string \"low bits are ${*var[0-1]} tgt is ${*var}\" \"int *\"")
+
+ self.expect("frame variable pointer",
+ substrs = ['low bits are',
+ 'tgt is 6'])
+
+ self.expect("frame variable int_array --summary-string \"${*var[0-1]}\"",
+ substrs = ['3'])
+
+ self.runCmd("type summary clear")
+
+ self.runCmd('type summary add --summary-string \"${var[0-1]}\" -x \"int \[[0-9]\]\"')
+
+ self.expect("frame variable int_array",
+ substrs = ['1,2'])
+
+ self.runCmd('type summary add --summary-string \"${var[0-1]}\" "int []"')
+
+ self.expect("frame variable int_array",
+ substrs = ['1,2'])
+
+ self.runCmd("type summary clear")
+
+ self.runCmd("type summary add -c -x \"i_am_cool \[[0-9]\]\"")
+ self.runCmd("type summary add -c i_am_cool")
+
+ self.expect("frame variable cool_array",
+ substrs = ['[0]',
+ '[1]',
+ '[2]',
+ '[3]',
+ '[4]',
+ 'integer',
+ 'character',
+ 'floating'])
+
+ self.runCmd("type summary add --summary-string \"int = ${*var.int_pointer}, float = ${*var.float_pointer}\" IWrapPointers")
+
+ self.expect("frame variable wrapper",
+ substrs = ['int = 4',
+ 'float = 1.1'])
+
+ self.runCmd("type summary add --summary-string \"low bits = ${*var.int_pointer[2]}\" IWrapPointers -p")
+
+ self.expect("frame variable wrapper",
+ substrs = ['low bits = 1'])
+
+ self.expect("frame variable *wrap_pointer",
+ substrs = ['low bits = 1'])
+
+ self.runCmd("type summary clear")
+
+ self.expect("frame variable int_array --summary-string \"${var[0][0-2]%hex}\"",
+ substrs = ['0x',
+ '7'])
+
+ self.runCmd("type summary clear")
+
+ self.runCmd("type summary add --summary-string \"${*var[].x[0-3]%hex} is a bitfield on a set of integers\" -x \"SimpleWithPointers \[[0-9]\]\"")
+
+ self.expect("frame variable couple --summary-string \"${*var.sp.x[0-2]} are low bits of integer ${*var.sp.x}. If I pretend it is an array I get ${var.sp.x[0-5]}\"",
+ substrs = ['1 are low bits of integer 9.',
+ 'If I pretend it is an array I get [9,'])
+
+ # if the summary has an error, we still display the value
+ self.expect("frame variable couple --summary-string \"${*var.sp.foo[0-2]\"",
+ substrs = ['(Couple) couple = {','x = 0x','y = 0x','z = 0x','s = 0x'])
+
+
+ self.runCmd("type summary add --summary-string \"${*var.sp.x[0-2]} are low bits of integer ${*var.sp.x}. If I pretend it is an array I get ${var.sp.x[0-5]}\" Couple")
+
+ self.expect("frame variable sparray",
+ substrs = ['[0x0000000f,0x0000000c,0x00000009]'])
+
+ # check that we can format a variable in a summary even if a format is defined for its datatype
+ self.runCmd("type format add -f hex int")
+ self.runCmd("type summary add --summary-string \"x=${var.x%d}\" Simple")
+
+ self.expect("frame variable a_simple_object",
+ substrs = ['x=3'])
+
+ self.expect("frame variable a_simple_object", matching=False,
+ substrs = ['0x0'])
+
+ # now check that the default is applied if we do not hand out a format
+ self.runCmd("type summary add --summary-string \"x=${var.x}\" Simple")
+
+ self.expect("frame variable a_simple_object", matching=False,
+ substrs = ['x=3'])
+
+ self.expect("frame variable a_simple_object", matching=True,
+ substrs = ['x=0x00000003'])
+
+ # check that we can correctly cap the number of children shown
+ self.runCmd("settings set target.max-children-count 5")
+
+ self.expect('frame variable a_long_guy', matching=True,
+ substrs = ['a_1',
+ 'b_1',
+ 'c_1',
+ 'd_1',
+ 'e_1',
+ '...'])
+
+ # check that no further stuff is printed (not ALL values are checked!)
+ self.expect('frame variable a_long_guy', matching=False,
+ substrs = ['f_1',
+ 'g_1',
+ 'h_1',
+ 'i_1',
+ 'j_1',
+ 'q_1',
+ 'a_2',
+ 'f_2',
+ 't_2',
+ 'w_2'])
+
+ self.runCmd("settings set target.max-children-count 1")
+ self.expect('frame variable a_long_guy', matching=True,
+ substrs = ['a_1',
+ '...'])
+ self.expect('frame variable a_long_guy', matching=False,
+ substrs = ['b_1',
+ 'c_1',
+ 'd_1',
+ 'e_1'])
+ self.expect('frame variable a_long_guy', matching=False,
+ substrs = ['f_1',
+ 'g_1',
+ 'h_1',
+ 'i_1',
+ 'j_1',
+ 'q_1',
+ 'a_2',
+ 'f_2',
+ 't_2',
+ 'w_2'])
+
+ self.runCmd("settings set target.max-children-count 30")
+ self.expect('frame variable a_long_guy', matching=True,
+ substrs = ['a_1',
+ 'b_1',
+ 'c_1',
+ 'd_1',
+ 'e_1',
+ 'z_1',
+ 'a_2',
+ 'b_2',
+ 'c_2',
+ 'd_2',
+ '...'])
+ self.expect('frame variable a_long_guy', matching=False,
+ substrs = ['e_2',
+ 'n_2',
+ 'r_2',
+ 'i_2',
+ 'k_2',
+ 'o_2'])
+
+ # override the cap
+ self.expect('frame variable a_long_guy --show-all-children', matching=True,
+ substrs = ['a_1',
+ 'b_1',
+ 'c_1',
+ 'd_1',
+ 'e_1',
+ 'z_1',
+ 'a_2',
+ 'b_2',
+ 'c_2',
+ 'd_2'])
+ self.expect('frame variable a_long_guy --show-all-children', matching=True,
+ substrs = ['e_2',
+ 'n_2',
+ 'r_2',
+ 'i_2',
+ 'k_2',
+ 'o_2'])
+ self.expect('frame variable a_long_guy --show-all-children', matching=False,
+ substrs = ['...'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/main.cpp
new file mode 100644
index 000000000000..2462e28db127
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-advanced/main.cpp
@@ -0,0 +1,174 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+
+struct i_am_cool
+{
+ int integer;
+ float floating;
+ char character;
+ i_am_cool(int I, float F, char C) :
+ integer(I), floating(F), character(C) {}
+ i_am_cool() : integer(1), floating(2), character('3') {}
+
+};
+
+struct i_am_cooler
+{
+ i_am_cool first_cool;
+ i_am_cool second_cool;
+ float floating;
+
+ i_am_cooler(int I1, int I2, float F1, float F2, char C1, char C2) :
+ first_cool(I1,F1,C1),
+ second_cool(I2,F2,C2),
+ floating((F1 + F2)/2) {}
+};
+
+struct IWrapPointers
+{
+ int* int_pointer;
+ float* float_pointer;
+ IWrapPointers() : int_pointer(new int(4)), float_pointer(new float(1.111)) {}
+};
+
+struct Simple
+{
+ int x;
+ float y;
+ char z;
+ Simple(int X, float Y, char Z) :
+ x(X),
+ y(Y),
+ z(Z)
+ {}
+};
+
+struct SimpleWithPointers
+{
+ int *x;
+ float *y;
+ char *z;
+ SimpleWithPointers(int X, float Y, char Z) :
+ x(new int (X)),
+ y(new float (Y)),
+ z(new char[2])
+ {
+ z[0] = Z;
+ z[1] = '\0';
+ }
+};
+
+struct Couple
+{
+ SimpleWithPointers sp;
+ Simple* s;
+ Couple(int X, float Y, char Z) : sp(X,Y,Z),
+ s(new Simple(X,Y,Z)) {}
+};
+
+struct VeryLong
+{
+ int a_1;
+ int b_1;
+ int c_1;
+ int d_1;
+ int e_1;
+ int f_1;
+ int g_1;
+ int h_1;
+ int i_1;
+ int j_1;
+ int k_1;
+ int l_1;
+ int m_1;
+ int n_1;
+ int o_1;
+ int p_1;
+ int q_1;
+ int r_1;
+ int s_1;
+ int t_1;
+ int u_1;
+ int v_1;
+ int w_1;
+ int x_1;
+ int y_1;
+ int z_1;
+
+ int a_2;
+ int b_2;
+ int c_2;
+ int d_2;
+ int e_2;
+ int f_2;
+ int g_2;
+ int h_2;
+ int i_2;
+ int j_2;
+ int k_2;
+ int l_2;
+ int m_2;
+ int n_2;
+ int o_2;
+ int p_2;
+ int q_2;
+ int r_2;
+ int s_2;
+ int t_2;
+ int u_2;
+ int v_2;
+ int w_2;
+ int x_2;
+ int y_2;
+ int z_2;
+};
+
+int main (int argc, const char * argv[])
+{
+
+ int iAmInt = 9;
+
+ i_am_cool cool_boy(1,0.5,3);
+ i_am_cooler cooler_boy(1,2,0.1,0.2,'A','B');
+
+ i_am_cool *cool_pointer = new i_am_cool(3,-3.141592,'E');
+
+ i_am_cool cool_array[5];
+
+ cool_array[3].floating = 5.25;
+ cool_array[4].integer = 6;
+ cool_array[2].character = 'Q';
+
+ int int_array[] = {1,2,3,4,5};
+
+ IWrapPointers wrapper;
+
+ *int_array = -1;
+
+ int* pointer = &cool_array[4].integer;
+
+ IWrapPointers *wrap_pointer = &wrapper;
+
+ Couple couple(9,9.99,'X');
+
+ SimpleWithPointers sparray[] =
+ {SimpleWithPointers(-1,-2,'3'),
+ SimpleWithPointers(-4,-5,'6'),
+ SimpleWithPointers(-7,-8,'9')};
+
+ Simple a_simple_object(3,0.14,'E');
+
+ VeryLong a_long_guy;
+
+ return 0; // Set break point at this line.
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/TestDataFormatterCategories.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/TestDataFormatterCategories.py
new file mode 100644
index 000000000000..db426cac6e59
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/TestDataFormatterCategories.py
@@ -0,0 +1,329 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class CategoriesDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case (most of these categories do not
+ # exist anymore, but we just make sure we delete all of them)
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type category delete Category1', check=False)
+ self.runCmd('type category delete Category2', check=False)
+ self.runCmd('type category delete NewCategory', check=False)
+ self.runCmd("type category delete CircleCategory", check=False)
+ self.runCmd("type category delete RectangleStarCategory", check=False)
+ self.runCmd("type category delete BaseCategory", check=False)
+
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ # Add a summary to a new category and check that it works
+ self.runCmd("type summary add Rectangle --summary-string \"ARectangle\" -w NewCategory")
+
+ self.expect("frame variable r1 r2 r3", matching=False,
+ substrs = ['r1 = ARectangle',
+ 'r2 = ARectangle',
+ 'r3 = ARectangle'])
+
+ self.runCmd("type category enable NewCategory")
+
+ self.expect("frame variable r1 r2 r3", matching=True,
+ substrs = ['r1 = ARectangle',
+ 'r2 = ARectangle',
+ 'r3 = ARectangle'])
+
+ # Disable the category and check that the old stuff is there
+ self.runCmd("type category disable NewCategory")
+
+ self.expect("frame variable r1 r2 r3",
+ substrs = ['r1 = {',
+ 'r2 = {',
+ 'r3 = {'])
+
+ # Re-enable the category and check that it works
+ self.runCmd("type category enable NewCategory")
+
+ self.expect("frame variable r1 r2 r3",
+ substrs = ['r1 = ARectangle',
+ 'r2 = ARectangle',
+ 'r3 = ARectangle'])
+
+ # Delete the category and the old stuff should be there
+ self.runCmd("type category delete NewCategory")
+
+ self.expect("frame variable r1 r2 r3",
+ substrs = ['r1 = {',
+ 'r2 = {',
+ 'r3 = {'])
+
+ # Add summaries to two different categories and check that we can switch
+ self.runCmd("type summary add --summary-string \"Width = ${var.w}, Height = ${var.h}\" Rectangle -w Category1")
+ self.runCmd("type summary add --python-script \"return 'Area = ' + str( int(valobj.GetChildMemberWithName('w').GetValue()) * int(valobj.GetChildMemberWithName('h').GetValue()) );\" Rectangle -w Category2")
+
+ # check that enable A B is the same as enable B enable A
+ self.runCmd("type category enable Category1 Category2")
+
+ self.expect("frame variable r1 r2 r3",
+ substrs = ['r1 = Width = ',
+ 'r2 = Width = ',
+ 'r3 = Width = '])
+
+ self.runCmd("type category disable Category1")
+
+ self.expect("frame variable r1 r2 r3",
+ substrs = ['r1 = Area = ',
+ 'r2 = Area = ',
+ 'r3 = Area = '])
+
+ # switch again
+
+ self.runCmd("type category enable Category1")
+
+ self.expect("frame variable r1 r2 r3",
+ substrs = ['r1 = Width = ',
+ 'r2 = Width = ',
+ 'r3 = Width = '])
+
+ # Re-enable the category and show that the preference is persisted
+ self.runCmd("type category disable Category2")
+ self.runCmd("type category enable Category2")
+
+ self.expect("frame variable r1 r2 r3",
+ substrs = ['r1 = Area = ',
+ 'r2 = Area = ',
+ 'r3 = Area = '])
+
+ # Now delete the favorite summary
+ self.runCmd("type summary delete Rectangle -w Category2")
+
+ self.expect("frame variable r1 r2 r3",
+ substrs = ['r1 = Width = ',
+ 'r2 = Width = ',
+ 'r3 = Width = '])
+
+ # Delete the summary from the default category (that does not have it)
+ self.runCmd("type summary delete Rectangle", check=False)
+
+ self.expect("frame variable r1 r2 r3",
+ substrs = ['r1 = Width = ',
+ 'r2 = Width = ',
+ 'r3 = Width = '])
+
+ # Now add another summary to another category and switch back and forth
+ self.runCmd("type category delete Category1 Category2")
+
+ self.runCmd("type summary add Rectangle -w Category1 --summary-string \"Category1\"")
+ self.runCmd("type summary add Rectangle -w Category2 --summary-string \"Category2\"")
+
+ self.runCmd("type category enable Category2")
+ self.runCmd("type category enable Category1")
+
+ self.runCmd("type summary list -w Category1")
+
+ self.expect("frame variable r1 r2 r3",
+ substrs = ['r1 = Category1',
+ 'r2 = Category1',
+ 'r3 = Category1'])
+
+ self.runCmd("type category disable Category1")
+
+ self.expect("frame variable r1 r2 r3",
+ substrs = ['r1 = Category2',
+ 'r2 = Category2',
+ 'r3 = Category2'])
+
+ # Check that re-enabling an enabled category works
+ self.runCmd("type category enable Category1")
+
+ self.expect("frame variable r1 r2 r3",
+ substrs = ['r1 = Category1',
+ 'r2 = Category1',
+ 'r3 = Category1'])
+
+ self.runCmd("type category delete Category1")
+ self.runCmd("type category delete Category2")
+
+ self.expect("frame variable r1 r2 r3",
+ substrs = ['r1 = {',
+ 'r2 = {',
+ 'r3 = {'])
+
+ # Check that multiple summaries can go into one category
+ self.runCmd("type summary add -w Category1 --summary-string \"Width = ${var.w}, Height = ${var.h}\" Rectangle")
+ self.runCmd("type summary add -w Category1 --summary-string \"Radius = ${var.r}\" Circle")
+
+ self.runCmd("type category enable Category1")
+
+ self.expect("frame variable r1 r2 r3",
+ substrs = ['r1 = Width = ',
+ 'r2 = Width = ',
+ 'r3 = Width = '])
+
+ self.expect("frame variable c1 c2 c3",
+ substrs = ['c1 = Radius = ',
+ 'c2 = Radius = ',
+ 'c3 = Radius = '])
+
+ self.runCmd("type summary delete Circle -w Category1")
+
+ self.expect("frame variable c1 c2 c3",
+ substrs = ['c1 = {',
+ 'c2 = {',
+ 'c3 = {'])
+
+ # Add a regex based summary to a category
+ self.runCmd("type summary add -w Category1 --summary-string \"Radius = ${var.r}\" -x Circle")
+
+ self.expect("frame variable r1 r2 r3",
+ substrs = ['r1 = Width = ',
+ 'r2 = Width = ',
+ 'r3 = Width = '])
+
+ self.expect("frame variable c1 c2 c3",
+ substrs = ['c1 = Radius = ',
+ 'c2 = Radius = ',
+ 'c3 = Radius = '])
+
+ # Delete it
+ self.runCmd("type summary delete Circle -w Category1")
+
+ self.expect("frame variable c1 c2 c3",
+ substrs = ['c1 = {',
+ 'c2 = {',
+ 'c3 = {'])
+
+ # Change a summary inside a category and check that the change is reflected
+ self.runCmd("type summary add Circle -w Category1 --summary-string \"summary1\"")
+
+ self.expect("frame variable c1 c2 c3",
+ substrs = ['c1 = summary1',
+ 'c2 = summary1',
+ 'c3 = summary1'])
+
+ self.runCmd("type summary add Circle -w Category1 --summary-string \"summary2\"")
+
+ self.expect("frame variable c1 c2 c3",
+ substrs = ['c1 = summary2',
+ 'c2 = summary2',
+ 'c3 = summary2'])
+
+ # Check that our order of priority works. Start by clearing categories
+ self.runCmd("type category delete Category1")
+
+ self.runCmd("type summary add Shape -w BaseCategory --summary-string \"AShape\"")
+ self.runCmd("type category enable BaseCategory")
+
+ self.expect("print (Shape*)&c1",
+ substrs = ['AShape'])
+ self.expect("print (Shape*)&r1",
+ substrs = ['AShape'])
+ self.expect("print (Shape*)c_ptr",
+ substrs = ['AShape'])
+ self.expect("print (Shape*)r_ptr",
+ substrs = ['AShape'])
+
+ self.runCmd("type summary add Circle -w CircleCategory --summary-string \"ACircle\"")
+ self.runCmd("type summary add Rectangle -w RectangleCategory --summary-string \"ARectangle\"")
+ self.runCmd("type category enable CircleCategory")
+
+ self.expect("frame variable c1",
+ substrs = ['ACircle'])
+ self.expect("frame variable c_ptr",
+ substrs = ['ACircle'])
+
+ self.runCmd("type summary add \"Rectangle *\" -w RectangleStarCategory --summary-string \"ARectangleStar\"")
+ self.runCmd("type category enable RectangleStarCategory")
+
+ self.expect("frame variable c1 r1 c_ptr r_ptr",
+ substrs = ['ACircle',
+ 'ARectangleStar'])
+
+ self.runCmd("type category enable RectangleCategory")
+
+ self.expect("frame variable c1 r1 c_ptr r_ptr",
+ substrs = ['ACircle',
+ 'ACircle',
+ 'ARectangle'])
+
+ # Check that abruptly deleting an enabled category does not crash us
+ self.runCmd("type category delete RectangleCategory")
+
+ self.expect("frame variable c1 r1 c_ptr r_ptr",
+ substrs = ['ACircle',
+ '(Rectangle) r1 = ', 'w = 5', 'h = 6',
+ 'ACircle',
+ 'ARectangleStar'])
+
+ # check that list commands work
+ self.expect("type category list",
+ substrs = ['RectangleStarCategory (enabled)'])
+
+ self.expect("type summary list",
+ substrs = ['ARectangleStar'])
+
+ # Disable a category and check that it fallsback
+ self.runCmd("type category disable CircleCategory")
+
+ # check that list commands work
+ self.expect("type category list",
+ substrs = ['CircleCategory (disabled'])
+
+ self.expect("frame variable c1 r_ptr",
+ substrs = ['AShape',
+ 'ARectangleStar'])
+
+ # check that filters work into categories
+ self.runCmd("type filter add Rectangle --child w --category RectangleCategory")
+ self.runCmd("type category enable RectangleCategory")
+ self.runCmd("type summary add Rectangle --category RectangleCategory --summary-string \" \" -e")
+ self.expect('frame variable r2',
+ substrs = ['w = 9'])
+ self.runCmd("type summary add Rectangle --summary-string \" \" -e")
+ self.expect('frame variable r2', matching=False,
+ substrs = ['h = 16'])
+
+ # Now delete all categories
+ self.runCmd("type category delete CircleCategory RectangleStarCategory BaseCategory RectangleCategory")
+
+ # check that a deleted category with filter does not blow us up
+ self.expect('frame variable r2',
+ substrs = ['w = 9',
+ 'h = 16'])
+
+ # and also validate that one can print formatters for a language
+ self.expect('type summary list -l c++', substrs=['vector', 'map', 'list', 'string'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/main.cpp
new file mode 100644
index 000000000000..b51dd45a7f60
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-categories/main.cpp
@@ -0,0 +1,46 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+
+struct Shape
+{
+ bool dummy;
+ Shape() : dummy(true) {}
+};
+
+struct Rectangle : public Shape {
+ int w;
+ int h;
+ Rectangle(int W = 3, int H = 5) : w(W), h(H) {}
+};
+
+struct Circle : public Shape {
+ int r;
+ Circle(int R = 6) : r(R) {}
+};
+
+int main (int argc, const char * argv[])
+{
+ Rectangle r1(5,6);
+ Rectangle r2(9,16);
+ Rectangle r3(4,4);
+
+ Circle c1(5);
+ Circle c2(6);
+ Circle c3(7);
+
+ Circle *c_ptr = new Circle(8);
+ Rectangle *r_ptr = new Rectangle(9,7);
+
+ return 0; // Set break point at this line.
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
new file mode 100644
index 000000000000..2ca737156a1a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/TestDataFormatterCpp.py
@@ -0,0 +1,265 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class CppDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ @expectedFailureWindows("llvm.org/pr24462") # Data formatters have problems on Windows
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ self.expect("frame variable",
+ substrs = ['(Speed) SPILookHex = 5.55' # Speed by default is 5.55.
+ ]);
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.runCmd("type format add -C yes -f x Speed BitField")
+ self.runCmd("type format add -C no -f c RealNumber")
+ self.runCmd("type format add -C no -f x Type2")
+ self.runCmd("type format add -C yes -f c Type1")
+
+ # The type format list should show our custom formats.
+ self.expect("type format list",
+ substrs = ['RealNumber',
+ 'Speed',
+ 'BitField',
+ 'Type1',
+ 'Type2'])
+
+ self.expect("frame variable",
+ patterns = ['\(Speed\) SPILookHex = 0x[0-9a-f]+' # Speed should look hex-ish now.
+ ]);
+
+ # gcc4.2 on Mac OS X skips typedef chains in the DWARF output
+ if self.getCompiler() in ['clang', 'llvm-gcc']:
+ self.expect("frame variable",
+ patterns = ['\(SignalMask\) SMILookHex = 0x[0-9a-f]+' # SignalMask should look hex-ish now.
+ ]);
+ self.expect("frame variable", matching=False,
+ patterns = ['\(Type4\) T4ILookChar = 0x[0-9a-f]+' # Type4 should NOT look hex-ish now.
+ ]);
+
+ # Now let's delete the 'Speed' custom format.
+ self.runCmd("type format delete Speed")
+
+ # The type format list should not show 'Speed' at this point.
+ self.expect("type format list", matching=False,
+ substrs = ['Speed'])
+
+ # Delete type format for 'Speed', we should expect an error message.
+ self.expect("type format delete Speed", error=True,
+ substrs = ['no custom formatter for Speed'])
+
+ self.runCmd("type summary add --summary-string \"arr = ${var%s}\" -x \"char \\[[0-9]+\\]\" -v")
+
+ self.expect("frame variable strarr",
+ substrs = ['arr = "Hello world!"'])
+
+ self.runCmd("type summary clear")
+
+ self.runCmd("type summary add --summary-string \"ptr = ${var%s}\" \"char *\" -v")
+
+ self.expect("frame variable strptr",
+ substrs = ['ptr = "Hello world!"'])
+
+ self.runCmd("type summary add --summary-string \"arr = ${var%s}\" -x \"char \\[[0-9]+\\]\" -v")
+
+ self.expect("frame variable strarr",
+ substrs = ['arr = "Hello world!'])
+
+ # check that rdar://problem/10011145 (Standard summary format for char[] doesn't work as the result of "expr".) is solved
+ self.expect("p strarr",
+ substrs = ['arr = "Hello world!'])
+
+ self.expect("frame variable strptr",
+ substrs = ['ptr = "Hello world!"'])
+
+ self.expect("p strptr",
+ substrs = ['ptr = "Hello world!"'])
+
+ self.expect("p (char*)\"1234567890123456789012345678901234567890123456789012345678901234ABC\"",
+ substrs = ['(char *) $', ' = ptr = ', ' "1234567890123456789012345678901234567890123456789012345678901234ABC"'])
+
+ self.runCmd("type summary add -c Point")
+
+ self.expect("frame variable iAmSomewhere",
+ substrs = ['x = 4',
+ 'y = 6'])
+
+ self.expect("type summary list",
+ substrs = ['Point',
+ 'one-line'])
+
+ self.runCmd("type summary add --summary-string \"y=${var.y%x}\" Point")
+
+ self.expect("frame variable iAmSomewhere",
+ substrs = ['y=0x'])
+
+ self.runCmd("type summary add --summary-string \"y=${var.y},x=${var.x}\" Point")
+
+ self.expect("frame variable iAmSomewhere",
+ substrs = ['y=6',
+ 'x=4'])
+
+ self.runCmd("type summary add --summary-string \"hello\" Point -e")
+
+ self.expect("type summary list",
+ substrs = ['Point',
+ 'show children'])
+
+ self.expect("frame variable iAmSomewhere",
+ substrs = ['hello',
+ 'x = 4',
+ '}'])
+
+ self.runCmd("type summary add --summary-string \"Sign: ${var[31]%B} Exponent: ${var[23-30]%x} Mantissa: ${var[0-22]%u}\" ShowMyGuts")
+
+ self.expect("frame variable cool_pointer->floating",
+ substrs = ['Sign: true',
+ 'Exponent: 0x',
+ '80'])
+
+ self.runCmd("type summary add --summary-string \"a test\" i_am_cool")
+
+ self.expect("frame variable cool_pointer",
+ substrs = ['a test'])
+
+ self.runCmd("type summary add --summary-string \"a test\" i_am_cool --skip-pointers")
+
+ self.expect("frame variable cool_pointer",
+ substrs = ['a test'],
+ matching = False)
+
+ self.runCmd("type summary add --summary-string \"${var[1-3]}\" \"int [5]\"")
+
+ self.expect("frame variable int_array",
+ substrs = ['2',
+ '3',
+ '4'])
+
+ self.runCmd("type summary clear")
+
+ self.runCmd("type summary add --summary-string \"${var[0-2].integer}\" \"i_am_cool *\"")
+ self.runCmd("type summary add --summary-string \"${var[2-4].integer}\" \"i_am_cool [5]\"")
+
+ self.expect("frame variable cool_array",
+ substrs = ['1,1,6'])
+
+ self.expect("frame variable cool_pointer",
+ substrs = ['3,0,0'])
+
+ # test special symbols for formatting variables into summaries
+ self.runCmd("type summary add --summary-string \"cool object @ ${var%L}\" i_am_cool")
+ self.runCmd("type summary delete \"i_am_cool [5]\"")
+
+ # this test might fail if the compiler tries to store
+ # these values into registers.. hopefully this is not
+ # going to be the case
+ self.expect("frame variable cool_array",
+ substrs = ['[0] = cool object @ 0x',
+ '[1] = cool object @ 0x',
+ '[2] = cool object @ 0x',
+ '[3] = cool object @ 0x',
+ '[4] = cool object @ 0x'])
+
+ # test getting similar output by exploiting ${var} = 'type @ location' for aggregates
+ self.runCmd("type summary add --summary-string \"${var}\" i_am_cool")
+
+ # this test might fail if the compiler tries to store
+ # these values into registers.. hopefully this is not
+ # going to be the case
+ self.expect("frame variable cool_array",
+ substrs = ['[0] = i_am_cool @ 0x',
+ '[1] = i_am_cool @ 0x',
+ '[2] = i_am_cool @ 0x',
+ '[3] = i_am_cool @ 0x',
+ '[4] = i_am_cool @ 0x'])
+
+
+ # test getting same output by exploiting %T and %L together for aggregates
+ self.runCmd("type summary add --summary-string \"${var%T} @ ${var%L}\" i_am_cool")
+
+ # this test might fail if the compiler tries to store
+ # these values into registers.. hopefully this is not
+ # going to be the case
+ self.expect("frame variable cool_array",
+ substrs = ['[0] = i_am_cool @ 0x',
+ '[1] = i_am_cool @ 0x',
+ '[2] = i_am_cool @ 0x',
+ '[3] = i_am_cool @ 0x',
+ '[4] = i_am_cool @ 0x'])
+
+ self.runCmd("type summary add --summary-string \"goofy\" i_am_cool")
+ self.runCmd("type summary add --summary-string \"${var.second_cool%S}\" i_am_cooler")
+
+ self.expect("frame variable the_coolest_guy",
+ substrs = ['(i_am_cooler) the_coolest_guy = goofy'])
+
+ # check that unwanted type specifiers are removed
+ self.runCmd("type summary delete i_am_cool")
+ self.runCmd("type summary add --summary-string \"goofy\" \"class i_am_cool\"")
+ self.expect("frame variable the_coolest_guy",
+ substrs = ['(i_am_cooler) the_coolest_guy = goofy'])
+
+ self.runCmd("type summary delete i_am_cool")
+ self.runCmd("type summary add --summary-string \"goofy\" \"enum i_am_cool\"")
+ self.expect("frame variable the_coolest_guy",
+ substrs = ['(i_am_cooler) the_coolest_guy = goofy'])
+
+ self.runCmd("type summary delete i_am_cool")
+ self.runCmd("type summary add --summary-string \"goofy\" \"struct i_am_cool\"")
+ self.expect("frame variable the_coolest_guy",
+ substrs = ['(i_am_cooler) the_coolest_guy = goofy'])
+
+ # many spaces, but we still do the right thing
+ self.runCmd("type summary delete i_am_cool")
+ self.runCmd("type summary add --summary-string \"goofy\" \"union i_am_cool\"")
+ self.expect("frame variable the_coolest_guy",
+ substrs = ['(i_am_cooler) the_coolest_guy = goofy'])
+
+ # but that not *every* specifier is removed
+ self.runCmd("type summary delete i_am_cool")
+ self.runCmd("type summary add --summary-string \"goofy\" \"wrong i_am_cool\"")
+ self.expect("frame variable the_coolest_guy", matching=False,
+ substrs = ['(i_am_cooler) the_coolest_guy = goofy'])
+
+ # check that formats are not sticking since that is the behavior we want
+ self.expect("frame variable iAmInt --format hex", substrs = ['(int) iAmInt = 0x00000001'])
+ self.expect("frame variable iAmInt", matching=False, substrs = ['(int) iAmInt = 0x00000001'])
+ self.expect("frame variable iAmInt", substrs = ['(int) iAmInt = 1'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/main.cpp
new file mode 100644
index 000000000000..5bcfbfd4d46e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-cpp/main.cpp
@@ -0,0 +1,121 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+
+typedef float RealNumber; // should show as char
+typedef RealNumber Temperature; // should show as float
+typedef RealNumber Speed; // should show as hex
+
+typedef int Counter; // should show as int
+typedef int BitField; // should show as hex
+
+typedef BitField SignalMask; // should show as hex
+typedef BitField Modifiers; // should show as hex
+
+typedef Counter Accumulator; // should show as int
+
+typedef int Type1; // should show as char
+typedef Type1 Type2; // should show as hex
+typedef Type2 Type3; // should show as char
+typedef Type3 Type4; // should show as char
+
+typedef int ChildType; // should show as int
+typedef int AnotherChildType; // should show as int
+
+struct Point {
+ int x;
+ int y;
+ Point(int X = 3, int Y = 2) : x(X), y(Y) {}
+};
+
+typedef float ShowMyGuts;
+
+struct i_am_cool
+{
+ int integer;
+ ShowMyGuts floating;
+ char character;
+ i_am_cool(int I, ShowMyGuts F, char C) :
+ integer(I), floating(F), character(C) {}
+ i_am_cool() : integer(1), floating(2), character('3') {}
+
+};
+
+struct i_am_cooler
+{
+ i_am_cool first_cool;
+ i_am_cool second_cool;
+ ShowMyGuts floating;
+
+ i_am_cooler(int I1, int I2, float F1, float F2, char C1, char C2) :
+ first_cool(I1,F1,C1),
+ second_cool(I2,F2,C2),
+ floating((F1 + F2)/2) {}
+};
+
+struct IUseCharStar
+{
+ const char* pointer;
+ IUseCharStar() : pointer("Hello world") {}
+};
+
+int main (int argc, const char * argv[])
+{
+
+ int iAmInt = 1;
+ const float& IAmFloat = float(2.45);
+
+ RealNumber RNILookChar = 3.14;
+ Temperature TMILookFloat = 4.97;
+ Speed SPILookHex = 5.55;
+
+ Counter CTILookInt = 6;
+ BitField BFILookHex = 7;
+ SignalMask SMILookHex = 8;
+ Modifiers MFILookHex = 9;
+
+ Accumulator* ACILookInt = new Accumulator(10);
+
+ const Type1& T1ILookChar = 11;
+ Type2 T2ILookHex = 12;
+ Type3 T3ILookChar = 13;
+ Type4 T4ILookChar = 14;
+
+ AnotherChildType AHILookInt = 15;
+
+ Speed* SPPtrILookHex = new Speed(16);
+
+ Point iAmSomewhere(4,6);
+
+ i_am_cool *cool_pointer = (i_am_cool*)malloc(sizeof(i_am_cool)*3);
+ cool_pointer[0] = i_am_cool(3,-3.141592,'E');
+ cool_pointer[1] = i_am_cool(0,-3.141592,'E');
+ cool_pointer[2] = i_am_cool(0,-3.141592,'E');
+
+ i_am_cool cool_array[5];
+
+ cool_array[3].floating = 5.25;
+ cool_array[4].integer = 6;
+ cool_array[2].character = 'Q';
+
+ int int_array[] = {1,2,3,4,5};
+
+ IUseCharStar iEncapsulateCharStar;
+
+ char strarr[32] = "Hello world!";
+ char* strptr = "Hello world!";
+
+ i_am_cooler the_coolest_guy(1,2,3.14,6.28,'E','G');
+
+ return 0; // Set break point at this line.
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/TestDataFormatterDisabling.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/TestDataFormatterDisabling.py
new file mode 100644
index 000000000000..0f254a67d5a6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/TestDataFormatterDisabling.py
@@ -0,0 +1,80 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class DataFormatterDisablingTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ @expectedFailureWindows("llvm.org/pr24462") # Data formatters have problems on Windows
+ def test_with_run_command(self):
+ """Check that we can properly disable all data formatter categories."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type category enable *', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ #self.runCmd('type category enable system VectorTypes libcxx gnu-libstdc++ CoreGraphics CoreServices AppKit CoreFoundation objc default', check=False)
+
+ self.expect('type category list', substrs = ['system','enabled',])
+
+ self.expect("frame variable numbers",
+ substrs = ['[0] = 1', '[3] = 1234'])
+
+ self.expect('frame variable string1', substrs = ['hello world'])
+
+ # now disable them all and check that nothing is formatted
+ self.runCmd('type category disable *')
+
+ self.expect("frame variable numbers", matching=False,
+ substrs = ['[0] = 1', '[3] = 1234'])
+
+ self.expect('frame variable string1', matching=False, substrs = ['hello world'])
+
+ self.expect('type category list', substrs = ['system','disabled',])
+
+ # now enable and check that we are back to normal
+ self.runCmd("type category enable *")
+
+ self.expect('type category list', substrs = ['system','enabled'])
+
+ self.expect("frame variable numbers",
+ substrs = ['[0] = 1', '[3] = 1234'])
+
+ self.expect('frame variable string1', substrs = ['hello world'])
+
+ self.expect('type category list', substrs = ['system','enabled'])
+
+ # last check - our cleanup will re-enable everything
+ self.runCmd('type category disable *')
+ self.expect('type category list', substrs = ['system','disabled'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/main.cpp
new file mode 100644
index 000000000000..9374642fb0d2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-disabling/main.cpp
@@ -0,0 +1,18 @@
+#include <vector>
+
+int main()
+{
+
+ const char* string1 = "hello world";
+
+ std::vector<int> numbers;
+ numbers.push_back(1);
+ numbers.push_back(12);
+ numbers.push_back(123);
+ numbers.push_back(1234);
+ numbers.push_back(12345);
+ numbers.push_back(123456);
+ numbers.push_back(1234567); // Set break point at this line.
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/TestDataFormatterEnumFormat.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/TestDataFormatterEnumFormat.py
new file mode 100644
index 000000000000..1659ade74a06
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/TestDataFormatterEnumFormat.py
@@ -0,0 +1,65 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class EnumFormatTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ self.expect("frame variable",
+ substrs = ['(Foo) f = Case45',
+ '(int) x = 1',
+ '(int) y = 45',
+ '(int) z = 43'
+ ]);
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.runCmd("type format add --type Foo int")
+
+ # The type format list should show our custom formats.
+ self.expect("type format list -w default",
+ substrs = ['int: as type Foo'])
+
+ self.expect("frame variable",
+ substrs = ['(Foo) f = Case45',
+ '(int) x = Case1',
+ '(int) y = Case45',
+ '(int) z = 43'
+ ]);
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/main.cpp
new file mode 100644
index 000000000000..6a8074ff9fbe
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-enum-format/main.cpp
@@ -0,0 +1,13 @@
+enum Foo {
+ Case1 = 1,
+ Case2 = 2,
+ Case45 = 45
+};
+
+int main() {
+ Foo f = Case45;
+ int x = 1;
+ int y = 45;
+ int z = 43;
+ return 1; // Set break point at this line.
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/TestDataFormatterGlobals.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/TestDataFormatterGlobals.py
new file mode 100644
index 000000000000..df3bef091c89
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/TestDataFormatterGlobals.py
@@ -0,0 +1,67 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class GlobalsDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.runCmd("type summary add --summary-string \"JustATest\" Point")
+
+ # Simply check we can get at global variables
+ self.expect("target variable g_point",
+ substrs = ['JustATest'])
+
+ self.expect("target variable g_point_pointer",
+ substrs = ['(Point *) g_point_pointer ='])
+
+ # Print some information about the variables
+ # (we ignore the actual values)
+ self.runCmd("type summary add --summary-string \"(x=${var.x},y=${var.y})\" Point")
+
+ self.expect("target variable g_point",
+ substrs = ['x=',
+ 'y='])
+
+ self.expect("target variable g_point_pointer",
+ substrs = ['(Point *) g_point_pointer ='])
+
+ # Test Python code on resulting SBValue
+ self.runCmd("type summary add --python-script \"return 'x=' + str(valobj.GetChildMemberWithName('x').GetValue());\" Point")
+
+ self.expect("target variable g_point",
+ substrs = ['x='])
+
+ self.expect("target variable g_point_pointer",
+ substrs = ['(Point *) g_point_pointer ='])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/main.cpp
new file mode 100644
index 000000000000..521f7a6931e9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-globals/main.cpp
@@ -0,0 +1,27 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+
+struct Point {
+ int x;
+ int y;
+ Point(int X = 3, int Y = 2) : x(X), y(Y) {}
+};
+
+Point g_point(3,4);
+Point* g_point_pointer = new Point(7,5);
+
+int main (int argc, const char * argv[])
+{
+ return 0; // Set break point at this line.
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/TestDataFormatterNamedSummaries.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/TestDataFormatterNamedSummaries.py
new file mode 100644
index 000000000000..94df520d29b3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/TestDataFormatterNamedSummaries.py
@@ -0,0 +1,122 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class NamedSummariesDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.runCmd("type summary add --summary-string \"AllUseIt: x=${var.x} {y=${var.y}} {z=${var.z}}\" --name AllUseIt")
+ self.runCmd("type summary add --summary-string \"First: x=${var.x} y=${var.y} dummy=${var.dummy}\" First")
+ self.runCmd("type summary add --summary-string \"Second: x=${var.x} y=${var.y%hex}\" Second")
+ self.runCmd("type summary add --summary-string \"Third: x=${var.x} z=${var.z}\" Third")
+
+ self.expect("frame variable first",
+ substrs = ['First: x=12'])
+
+ self.expect("frame variable first --summary AllUseIt",
+ substrs = ['AllUseIt: x=12'])
+
+ # We *DO NOT* remember the summary choice anymore
+ self.expect("frame variable first", matching=False,
+ substrs = ['AllUseIt: x=12'])
+ self.expect("frame variable first",
+ substrs = ['First: x=12'])
+
+ self.runCmd("thread step-over") # 2
+
+ self.expect("frame variable first",
+ substrs = ['First: x=12'])
+
+ self.expect("frame variable first --summary AllUseIt",
+ substrs = ['AllUseIt: x=12',
+ 'y=34'])
+
+ self.expect("frame variable second --summary AllUseIt",
+ substrs = ['AllUseIt: x=65',
+ 'y=43.25'])
+
+ self.expect("frame variable third --summary AllUseIt",
+ substrs = ['AllUseIt: x=96',
+ 'z=',
+ 'E'])
+
+ self.runCmd("thread step-over") # 3
+
+ self.expect("frame variable second",
+ substrs = ['Second: x=65',
+ 'y=0x'])
+
+ # <rdar://problem/11576143> decided that invalid summaries will raise an error
+ # instead of just defaulting to the base summary
+ self.expect("frame variable second --summary NoSuchSummary",error=True,
+ substrs = ['must specify a valid named summary'])
+
+ self.runCmd("thread step-over")
+
+ self.runCmd("type summary add --summary-string \"FirstAndFriends: x=${var.x} {y=${var.y}} {z=${var.z}}\" First --name FirstAndFriends")
+
+ self.expect("frame variable first",
+ substrs = ['FirstAndFriends: x=12',
+ 'y=34'])
+
+ self.runCmd("type summary delete First")
+
+ self.expect("frame variable first --summary FirstAndFriends",
+ substrs = ['FirstAndFriends: x=12',
+ 'y=34'])
+
+ self.expect("frame variable first", matching=True,
+ substrs = ['x = 12',
+ 'y = 34'])
+
+ self.runCmd("type summary delete FirstAndFriends")
+ self.expect("type summary delete NoSuchSummary", error=True)
+ self.runCmd("type summary delete AllUseIt")
+
+ self.expect("frame variable first", matching=False,
+ substrs = ['FirstAndFriends'])
+
+ self.runCmd("thread step-over") # 4
+
+ self.expect("frame variable first",matching=False,
+ substrs = ['FirstAndFriends: x=12',
+ 'y=34'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/main.cpp
new file mode 100644
index 000000000000..fdec5fecd3a2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-named-summaries/main.cpp
@@ -0,0 +1,59 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+
+struct First
+{
+ int x;
+ int y;
+ float dummy;
+ First(int X, int Y) :
+ x(X),
+ y(Y),
+ dummy(3.14)
+ {}
+};
+
+struct Second
+{
+ int x;
+ float y;
+ Second(int X, float Y) :
+ x(X),
+ y(Y)
+ {}
+};
+
+struct Third
+{
+ int x;
+ char z;
+ Third(int X, char Z) :
+ x(X),
+ z(Z)
+ {}
+};
+
+int main (int argc, const char * argv[])
+{
+ First first(12,34);
+ Second second(65,43.25);
+ Third *third = new Third(96,'E');
+
+ first.dummy = 1; // Set break point at this line.
+ first.dummy = 2;
+ first.dummy = 3;
+ first.dummy = 4;
+ first.dummy = 5;
+
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/.categories b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/.categories
new file mode 100644
index 000000000000..6326dbcec91b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/.categories
@@ -0,0 +1 @@
+dataformatters,objc
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/Makefile
new file mode 100644
index 000000000000..9f7fb1ca6231
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+
+CFLAGS_EXTRAS += -w
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjC.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjC.py
new file mode 100644
index 000000000000..e12ddca2eea7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/TestDataFormatterObjC.py
@@ -0,0 +1,464 @@
+# encoding: utf-8
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import datetime
+import lldbsuite.test.lldbutil as lldbutil
+
+class ObjCDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipUnlessDarwin
+ def test_plain_objc_with_run_command(self):
+ """Test basic ObjC formatting behavior."""
+ self.build()
+ self.plain_data_formatter_commands()
+
+ def appkit_tester_impl(self,commands):
+ self.build()
+ self.appkit_common_data_formatters_command()
+ commands()
+
+ @skipUnlessDarwin
+ def test_nsnumber_with_run_command(self):
+ """Test formatters for NSNumber."""
+ self.appkit_tester_impl(self.nsnumber_data_formatter_commands)
+
+ @skipUnlessDarwin
+ def test_nscontainers_with_run_command(self):
+ """Test formatters for NS container classes."""
+ self.appkit_tester_impl(self.nscontainers_data_formatter_commands)
+
+ @skipUnlessDarwin
+ def test_nsdata_with_run_command(self):
+ """Test formatters for NSData."""
+ self.appkit_tester_impl(self.nsdata_data_formatter_commands)
+
+ @skipUnlessDarwin
+ def test_nsurl_with_run_command(self):
+ """Test formatters for NSURL."""
+ self.appkit_tester_impl(self.nsurl_data_formatter_commands)
+
+
+ @skipUnlessDarwin
+ def test_nserror_with_run_command(self):
+ """Test formatters for NSError."""
+ self.appkit_tester_impl(self.nserror_data_formatter_commands)
+
+
+ @skipUnlessDarwin
+ def test_nsbundle_with_run_command(self):
+ """Test formatters for NSBundle."""
+ self.appkit_tester_impl(self.nsbundle_data_formatter_commands)
+
+
+ @skipUnlessDarwin
+ def test_nsexception_with_run_command(self):
+ """Test formatters for NSException."""
+ self.appkit_tester_impl(self.nsexception_data_formatter_commands)
+
+ @skipUnlessDarwin
+ def test_nsmisc_with_run_command(self):
+ """Test formatters for misc NS classes."""
+ self.appkit_tester_impl(self.nsmisc_data_formatter_commands)
+
+
+ @skipUnlessDarwin
+ def test_nsdate_with_run_command(self):
+ """Test formatters for NSDate."""
+ self.appkit_tester_impl(self.nsdate_data_formatter_commands)
+
+ @skipUnlessDarwin
+ def test_coreframeworks_and_run_command(self):
+ """Test formatters for Core OSX frameworks."""
+ self.build()
+ self.cf_data_formatter_commands()
+
+ @skipUnlessDarwin
+ def test_kvo_with_run_command(self):
+ """Test the behavior of formatters when KVO is in use."""
+ self.build()
+ self.kvo_data_formatter_commands()
+
+ @skipUnlessDarwin
+ def test_expr_with_run_command(self):
+ """Test common cases of expression parser <--> formatters interaction."""
+ self.build()
+ self.expr_objc_data_formatter_commands()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.m', '// Set break point at this line.')
+
+ def plain_data_formatter_commands(self):
+ """Test basic ObjC formatting behavior."""
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type synth clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.runCmd("type summary add --summary-string \"${var%@}\" MyClass")
+
+ self.expect("frame variable object2",
+ substrs = ['MyOtherClass']);
+
+ self.expect("frame variable *object2",
+ substrs = ['MyOtherClass']);
+
+ # Now let's delete the 'MyClass' custom summary.
+ self.runCmd("type summary delete MyClass")
+
+ # The type format list should not show 'MyClass' at this point.
+ self.expect("type summary list", matching=False,
+ substrs = ['MyClass'])
+
+ self.runCmd("type summary add --summary-string \"a test\" MyClass")
+
+ self.expect("frame variable *object2",
+ substrs = ['*object2 =',
+ 'MyClass = a test',
+ 'backup = ']);
+
+ self.expect("frame variable object2", matching=False,
+ substrs = ['a test']);
+
+ self.expect("frame variable object",
+ substrs = ['a test']);
+
+ self.expect("frame variable *object",
+ substrs = ['a test']);
+
+ self.expect('frame variable myclass',
+ substrs = ['(Class) myclass = NSValue'])
+ self.expect('frame variable myclass2',
+ substrs = ['(Class) myclass2 = ','NS','String'])
+ self.expect('frame variable myclass3',
+ substrs = ['(Class) myclass3 = Molecule'])
+ self.expect('frame variable myclass4',
+ substrs = ['(Class) myclass4 = NSMutableArray'])
+ self.expect('frame variable myclass5',
+ substrs = ['(Class) myclass5 = nil'])
+
+ def appkit_common_data_formatters_command(self):
+ """Test formatters for AppKit classes."""
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type synth clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ def nsnumber_data_formatter_commands(self):
+ # Now enable AppKit and check we are displaying Cocoa classes correctly
+ self.expect('frame variable num1 num2 num3 num4 num5 num6 num7 num8_Y num8_N num9',
+ substrs = ['(NSNumber *) num1 = ',' (int)5',
+ '(NSNumber *) num2 = ',' (float)3.1',
+ '(NSNumber *) num3 = ',' (double)3.14',
+ '(NSNumber *) num4 = ',' (long)-2',
+ '(NSNumber *) num5 = ',' (char)65',
+ '(NSNumber *) num6 = ',' (long)255',
+ '(NSNumber *) num7 = ','2000000',
+ '(NSNumber *) num8_Y = ',' @"1"',
+ '(NSNumber *) num8_N = ',' @"0"',
+ '(NSNumber *) num9 = ',' (short)-31616'])
+
+ self.expect('frame variable decimal_one',
+ substrs = ['(NSDecimalNumber *) decimal_one = 0x','1'])
+
+ self.expect('frame variable num_at1 num_at2 num_at3 num_at4',
+ substrs = ['(NSNumber *) num_at1 = ',' (int)12',
+ '(NSNumber *) num_at2 = ',' (int)-12',
+ '(NSNumber *) num_at3 = ',' (double)12.5',
+ '(NSNumber *) num_at4 = ',' (double)-12.5'])
+
+ def nscontainers_data_formatter_commands(self):
+ self.expect('frame variable newArray newDictionary newMutableDictionary cfdict_ref mutable_dict_ref cfarray_ref mutable_array_ref',
+ substrs = ['(NSArray *) newArray = ','@"50 elements"',
+ '(NSDictionary *) newDictionary = ',' 12 key/value pairs',
+ '(NSDictionary *) newMutableDictionary = ',' 21 key/value pairs',
+ '(CFDictionaryRef) cfdict_ref = ','3 key/value pairs',
+ '(CFMutableDictionaryRef) mutable_dict_ref = ','12 key/value pairs',
+ '(CFArrayRef) cfarray_ref = ','@"3 elements"',
+ '(CFMutableArrayRef) mutable_array_ref = ','@"11 elements"'])
+
+ self.expect('frame variable nscounted_set',
+ substrs = ['(NSCountedSet *) nscounted_set = ','5 elements'])
+
+ self.expect('frame variable iset1 iset2 imset',
+ substrs = ['4 indexes','512 indexes','10 indexes'])
+
+ self.expect('frame variable mutable_bag_ref cfbag_ref binheap_ref',
+ substrs = ['(CFMutableBagRef) mutable_bag_ref = ','@"17 values"',
+ '(CFBagRef) cfbag_ref = ','@"15 values"',
+ '(CFBinaryHeapRef) binheap_ref = ','@"21 items"'])
+
+ self.expect('expression -d run -- [NSArray new]', substrs=['@"0 elements"'])
+
+ def nsdata_data_formatter_commands(self):
+ self.expect('frame variable immutableData mutableData data_ref mutable_data_ref mutable_string_ref',
+ substrs = ['(NSData *) immutableData = ',' 4 bytes',
+ '(NSData *) mutableData = ',' 14 bytes',
+ '(CFDataRef) data_ref = ','@"5 bytes"',
+ '(CFMutableDataRef) mutable_data_ref = ','@"5 bytes"',
+ '(CFMutableStringRef) mutable_string_ref = ',' @"Wish ya knew"'])
+
+ def nsurl_data_formatter_commands(self):
+ self.expect('frame variable cfurl_ref cfchildurl_ref cfgchildurl_ref',
+ substrs = ['(CFURLRef) cfurl_ref = ','@"http://www.foo.bar',
+ 'cfchildurl_ref = ','@"page.html -- http://www.foo.bar',
+ '(CFURLRef) cfgchildurl_ref = ','@"?whatever -- http://www.foo.bar/page.html"'])
+
+ self.expect('frame variable nsurl nsurl2 nsurl3',
+ substrs = ['(NSURL *) nsurl = ','@"http://www.foo.bar',
+ '(NSURL *) nsurl2 =','@"page.html -- http://www.foo.bar',
+ '(NSURL *) nsurl3 = ','@"?whatever -- http://www.foo.bar/page.html"'])
+
+ def nserror_data_formatter_commands(self):
+ self.expect('frame variable nserror',
+ substrs = ['domain: @"Foobar" - code: 12'])
+
+ self.expect('frame variable nserror->_userInfo',
+ substrs = ['2 key/value pairs'])
+
+ self.expect('frame variable nserror->_userInfo --ptr-depth 1 -d run-target',
+ substrs = ['@"a"','@"b"',"1","2"])
+
+ def nsbundle_data_formatter_commands(self):
+ self.expect('frame variable bundle_string bundle_url main_bundle',
+ substrs = ['(NSBundle *) bundle_string = ',' @"/System/Library/Frameworks/Accelerate.framework"',
+ '(NSBundle *) bundle_url = ',' @"/System/Library/Frameworks/Cocoa.framework"',
+ '(NSBundle *) main_bundle = ','data-formatter-objc'])
+
+ def nsexception_data_formatter_commands(self):
+ self.expect('frame variable except0 except1 except2 except3',
+ substrs = ['(NSException *) except0 = ','name:@"TheGuyWhoHasNoName" reason:@"cuz it\'s funny"',
+ '(NSException *) except1 = ','name:@"TheGuyWhoHasNoName~1" reason:@"cuz it\'s funny"',
+ '(NSException *) except2 = ','name:@"TheGuyWhoHasNoName`2" reason:@"cuz it\'s funny"',
+ '(NSException *) except3 = ','name:@"TheGuyWhoHasNoName/3" reason:@"cuz it\'s funny"'])
+
+ def nsmisc_data_formatter_commands(self):
+ self.expect('frame variable localhost',
+ substrs = ['<NSHost ','> localhost ((','"127.0.0.1"'])
+
+ if self.getArchitecture() in ['i386', 'x86_64']:
+ self.expect('frame variable my_task',
+ substrs = ['<NS','Task: 0x'])
+
+ self.expect('frame variable range_value',
+ substrs = ['NSRange: {4, 4}'])
+
+ self.expect('frame variable port',
+ substrs = ['(NSMachPort *) port = ',' mach port: '])
+
+ def nsdate_data_formatter_commands(self):
+ self.expect('frame variable date1 date2',
+ patterns = ['(1985-04-10|1985-04-11)','(2011-01-01|2010-12-31)'])
+
+ # this test might fail if we hit the breakpoint late on December 31st of some given year
+ # and midnight comes between hitting the breakpoint and running this line of code
+ # hopefully the output will be revealing enough in that case :-)
+ now_year = str(datetime.datetime.now().year)
+
+ self.expect('frame variable date3 date4',
+ substrs = [now_year,'1970'])
+
+ self.expect('frame variable date1_abs date2_abs',
+ substrs = ['1985-04','2011-01'])
+
+ self.expect('frame variable date3_abs date4_abs',
+ substrs = [now_year,'1970'])
+
+ self.expect('frame variable cupertino home europe',
+ substrs = ['@"America/Los_Angeles"',
+ '@"Europe/Rome"',
+ '@"Europe/Paris"'])
+
+ self.expect('frame variable cupertino_ns home_ns europe_ns',
+ substrs = ['@"America/Los_Angeles"',
+ '@"Europe/Rome"',
+ '@"Europe/Paris"'])
+
+ self.expect('frame variable mut_bv',
+ substrs = ['(CFMutableBitVectorRef) mut_bv = ', '1110 0110 1011 0000 1101 1010 1000 1111 0011 0101 1101 0001 00'])
+
+
+ def expr_objc_data_formatter_commands(self):
+ """Test common cases of expression parser <--> formatters interaction."""
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type synth clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ # check that the formatters are able to deal safely and correctly
+ # with ValueObjects that the expression parser returns
+ self.expect('expression ((id)@"Hello for long enough to avoid short string types")', matching=False,
+ substrs = ['Hello for long enough to avoid short string types'])
+
+ self.expect('expression -d run -- ((id)@"Hello for long enough to avoid short string types")',
+ substrs = ['Hello for long enough to avoid short string types'])
+
+ self.expect('expr -d run -- label1',
+ substrs = ['Process Name'])
+
+ self.expect('expr -d run -- @"Hello for long enough to avoid short string types"',
+ substrs = ['Hello for long enough to avoid short string types'])
+
+ self.expect('expr -d run --object-description -- @"Hello for long enough to avoid short string types"',
+ substrs = ['Hello for long enough to avoid short string types'])
+ self.expect('expr -d run --object-description -- @"Hello"', matching=False,
+ substrs = ['@"Hello" Hello'])
+
+
+ def cf_data_formatter_commands(self):
+ """Test formatters for Core OSX frameworks."""
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd('log timers disable', check=False)
+
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ # check formatters for common Objective-C types
+ expect_strings = ['(CFGregorianUnits) cf_greg_units = 1 years, 3 months, 5 days, 12 hours, 5 minutes 7 seconds',
+ '(CFRange) cf_range = location=4 length=4',
+ '(NSPoint) ns_point = (x = 4, y = 4)',
+ '(NSRange) ns_range = location=4, length=4',
+ '(NSRect) ns_rect = (origin = (x = 1, y = 1), size = (width = 5, height = 5))',
+ '(NSRectArray) ns_rect_arr = ((x = 1, y = 1), (width = 5, height = 5)), ...',
+ '(NSSize) ns_size = (width = 5, height = 7)',
+ '(CGSize) cg_size = (width = 1, height = 6)',
+ '(CGPoint) cg_point = (x = 2, y = 7)',
+ '(CGRect) cg_rect = (origin = (x = 1, y = 2), size = (width = 7, height = 7))',
+ '(Rect) rect = (t=4, l=8, b=4, r=7)',
+ '(Rect *) rect_ptr = (t=4, l=8, b=4, r=7)',
+ '(Point) point = (v=7, h=12)',
+ '(Point *) point_ptr = (v=7, h=12)',
+ 'name:@"TheGuyWhoHasNoName" reason:@"cuz it\'s funny"',
+ '1985',
+ 'foo_selector_impl'];
+
+ if self.getArchitecture() in ['i386', 'x86_64']:
+ expect_strings.append('(HIPoint) hi_point = (x=7, y=12)')
+ expect_strings.append('(HIRect) hi_rect = origin=(x = 3, y = 5) size=(width = 4, height = 6)')
+ expect_strings.append('(RGBColor) rgb_color = red=3 green=56 blue=35')
+ expect_strings.append('(RGBColor *) rgb_color_ptr = red=3 green=56 blue=35')
+
+ self.expect("frame variable",
+ substrs = expect_strings)
+
+
+ def kvo_data_formatter_commands(self):
+ """Test the behavior of formatters when KVO is in use."""
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type synth clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ # as long as KVO is implemented by subclassing, this test should succeed
+ # we should be able to dynamically figure out that the KVO implementor class
+ # is a subclass of Molecule, and use the appropriate summary for it
+ self.runCmd("type summary add -s JustAMoleculeHere Molecule")
+ self.expect('frame variable molecule', substrs = ['JustAMoleculeHere'])
+ self.runCmd("next")
+ self.expect("thread list",
+ substrs = ['stopped',
+ 'step over'])
+ self.expect('frame variable molecule', substrs = ['JustAMoleculeHere'])
+
+ self.runCmd("next")
+ # check that NSMutableDictionary's formatter is not confused when dealing with a KVO'd dictionary
+ self.expect('frame variable newMutableDictionary', substrs = ['(NSDictionary *) newMutableDictionary = ',' 21 key/value pairs'])
+
+ lldbutil.run_break_set_by_regexp (self, 'setAtoms')
+
+ self.runCmd("continue")
+ self.expect("frame variable _cmd",substrs = ['setAtoms:'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/main.m b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/main.m
new file mode 100644
index 000000000000..6eb7e021f70b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/main.m
@@ -0,0 +1,694 @@
+//===-- main.m ------------------------------------------------*- ObjC -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#import <Foundation/Foundation.h>
+
+#if defined(__APPLE__)
+#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
+#define IOS
+#endif
+#endif
+
+#if defined(IOS)
+#import <Foundation/NSGeometry.h>
+#else
+#import <Carbon/Carbon.h>
+#endif
+
+@interface MyClass : NSObject
+{
+ int i;
+ char c;
+ float f;
+}
+
+- (id)initWithInt: (int)x andFloat:(float)y andChar:(char)z;
+- (int)doIncrementByInt: (int)x;
+
+@end
+
+@interface MyOtherClass : MyClass
+{
+ int i2;
+ MyClass *backup;
+}
+- (id)initWithInt: (int)x andFloat:(float)y andChar:(char)z andOtherInt:(int)q;
+
+@end
+
+@implementation MyClass
+
+- (id)initWithInt: (int)x andFloat:(float)y andChar:(char)z
+{
+ self = [super init];
+ if (self) {
+ self->i = x;
+ self->f = y;
+ self->c = z;
+ }
+ return self;
+}
+
+- (int)doIncrementByInt: (int)x
+{
+ self->i += x;
+ return self->i;
+}
+
+@end
+
+@implementation MyOtherClass
+
+- (id)initWithInt: (int)x andFloat:(float)y andChar:(char)z andOtherInt:(int)q
+{
+ self = [super initWithInt:x andFloat:y andChar:z];
+ if (self) {
+ self->i2 = q;
+ self->backup = [[MyClass alloc] initWithInt:x andFloat:y andChar:z];
+ }
+ return self;
+}
+
+@end
+
+@interface Atom : NSObject {
+ float mass;
+}
+-(void)setMass:(float)newMass;
+-(float)mass;
+@end
+
+@interface Molecule : NSObject {
+ NSArray *atoms;
+}
+-(void)setAtoms:(NSArray *)newAtoms;
+-(NSArray *)atoms;
+@end
+
+@implementation Atom
+
+-(void)setMass:(float)newMass
+{
+ mass = newMass;
+}
+-(float)mass
+{
+ return mass;
+}
+
+@end
+
+@implementation Molecule
+
+-(void)setAtoms:(NSArray *)newAtoms
+{
+ atoms = newAtoms;
+}
+-(NSArray *)atoms
+{
+ return atoms;
+}
+@end
+
+@interface My_KVO_Observer : NSObject
+-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change
+ context:(void *)context;
+- (id) init;
+- (void) dealloc;
+@end
+
+@implementation My_KVO_Observer
+-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change
+ context:(void *)context {
+ // we do not really care about KVO'ing - do nothing
+ return;
+}
+- (id) init
+{
+ self = [super init];
+ return self;
+}
+
+- (void) dealloc
+{
+ [super dealloc];
+}
+@end
+
+int main (int argc, const char * argv[])
+{
+
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+
+ MyClass *object = [[MyClass alloc] initWithInt:1 andFloat:3.14 andChar: 'E'];
+
+ [object doIncrementByInt:3];
+
+ MyOtherClass *object2 = [[MyOtherClass alloc] initWithInt:2 andFloat:6.28 andChar: 'G' andOtherInt:-1];
+
+ [object2 doIncrementByInt:3];
+
+ NSNumber* num1 = [NSNumber numberWithInt:5];
+ NSNumber* num2 = [NSNumber numberWithFloat:3.14];
+ NSNumber* num3 = [NSNumber numberWithDouble:3.14];
+ NSNumber* num4 = [NSNumber numberWithUnsignedLongLong:0xFFFFFFFFFFFFFFFE];
+ NSNumber* num5 = [NSNumber numberWithChar:'A'];
+ NSNumber* num6 = [NSNumber numberWithUnsignedLongLong:0xFF];
+ NSNumber* num7 = [NSNumber numberWithLong:0x1E8480];
+ NSNumber* num8_Y = [NSNumber numberWithBool:YES];
+ NSNumber* num8_N = [NSNumber numberWithBool:NO];
+ NSNumber* num9 = [NSNumber numberWithShort:0x1E8480];
+ NSNumber* num_at1 = @12;
+ NSNumber* num_at2 = @-12;
+ NSNumber* num_at3 = @12.5;
+ NSNumber* num_at4 = @-12.5;
+
+ NSDecimalNumber* decimal_one = [NSDecimalNumber one];
+
+ NSString *str0 = [num6 stringValue];
+
+ NSString *str1 = [NSString stringWithCString:"A rather short ASCII NSString object is here" encoding:NSASCIIStringEncoding];
+
+ NSString *str2 = [NSString stringWithUTF8String:"A rather short UTF8 NSString object is here"];
+
+ NSString *str3 = @"A string made with the at sign is here";
+
+ NSString *str4 = [NSString stringWithFormat:@"This is string number %ld right here", (long)4];
+
+ NSRect ns_rect_4str = {{1,1},{5,5}};
+
+ NSString* str5 = NSStringFromRect(ns_rect_4str);
+
+ NSString* str6 = [@"/usr/doc/README.1ST" pathExtension];
+
+ const unichar myCharacters[] = {0x03C3,'x','x'};
+ NSString *str7 = [NSString stringWithCharacters: myCharacters
+ length: sizeof myCharacters / sizeof *myCharacters];
+
+ NSString* str8 = [@"/usr/doc/file.hasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTime" pathExtension];
+
+ const unichar myOtherCharacters[] = {'a',' ', 'v','e','r','y',' ',
+ 'm','u','c','h',' ','b','o','r','i','n','g',' ','t','a','s','k',
+ ' ','t','o',' ','w','r','i','t','e', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g', ' ',
+ 't','h','i','s',' ','w','a','y','!','!',0x03C3, 0};
+ NSString *str9 = [NSString stringWithCharacters: myOtherCharacters
+ length: sizeof myOtherCharacters / sizeof *myOtherCharacters];
+
+ const unichar myNextCharacters[] = {0x03C3, 0x0000};
+
+ NSString *str10 = [NSString stringWithFormat:@"This is a Unicode string %S number %ld right here", myNextCharacters, (long)4];
+
+ NSString *str11 = NSStringFromClass([str10 class]);
+
+ NSString *label1 = @"Process Name: ";
+ NSString *label2 = @"Process Id: ";
+ NSString *processName = [[NSProcessInfo processInfo] processName];
+ NSString *processID = [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]];
+ NSString *str12 = [NSString stringWithFormat:@"%@ %@ %@ %@", label1, processName, label2, processID];
+
+ NSString *strA1 = [NSString stringWithCString:"A rather short ASCII NSString object is here" encoding:NSASCIIStringEncoding];
+
+ NSString *strA2 = [NSString stringWithUTF8String:"A rather short UTF8 NSString object is here"];
+
+ NSString *strA3 = @"A string made with the at sign is here";
+
+ NSString *strA4 = [NSString stringWithFormat:@"This is string number %ld right here", (long)4];
+
+ NSString* strA5 = NSStringFromRect(ns_rect_4str);
+
+ NSString* strA6 = [@"/usr/doc/README.1ST" pathExtension];
+
+ NSString *strA7 = [NSString stringWithCharacters: myCharacters
+ length: sizeof myCharacters / sizeof *myCharacters];
+
+ NSString* strA8 = [@"/usr/doc/file.hasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTime" pathExtension];
+
+ NSString *strA9 = [NSString stringWithCharacters: myOtherCharacters
+ length: sizeof myOtherCharacters / sizeof *myOtherCharacters];
+
+ NSString *strA10 = [NSString stringWithFormat:@"This is a Unicode string %S number %ld right here", myNextCharacters, (long)4];
+
+ NSString *strA11 = NSStringFromClass([str10 class]);
+
+ NSString *strA12 = [NSString stringWithFormat:@"%@ %@ %@ %@", label1, processName, label2, processID];
+
+ NSString *strB1 = [NSString stringWithCString:"A rather short ASCII NSString object is here" encoding:NSASCIIStringEncoding];
+
+ NSString *strB2 = [NSString stringWithUTF8String:"A rather short UTF8 NSString object is here"];
+
+ NSString *strB3 = @"A string made with the at sign is here";
+
+ NSString *strB4 = [NSString stringWithFormat:@"This is string number %ld right here", (long)4];
+
+ NSString* strB5 = NSStringFromRect(ns_rect_4str);
+
+ NSString* strB6 = [@"/usr/doc/README.1ST" pathExtension];
+
+ NSString *strB7 = [NSString stringWithCharacters: myCharacters
+ length: sizeof myCharacters / sizeof *myCharacters];
+
+ NSString* strB8 = [@"/usr/doc/file.hasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTime" pathExtension];
+
+ NSString *strB9 = [NSString stringWithCharacters: myOtherCharacters
+ length: sizeof myOtherCharacters / sizeof *myOtherCharacters];
+
+ NSString *strB10 = [NSString stringWithFormat:@"This is a Unicode string %S number %ld right here", myNextCharacters, (long)4];
+
+ NSString *strB11 = NSStringFromClass([str10 class]);
+
+ NSString *strB12 = [NSString stringWithFormat:@"%@ %@ %@ %@", label1, processName, label2, processID];
+
+ NSString *strC11 = NSStringFromClass([str10 class]);
+
+ NSString *strC12 = [NSString stringWithFormat:@"%@ %@ %@ %@", label1, processName, label2, processID];
+
+ NSString *strC1 = [NSString stringWithCString:"A rather short ASCII NSString object is here" encoding:NSASCIIStringEncoding];
+
+ NSString *strC2 = [NSString stringWithUTF8String:"A rather short UTF8 NSString object is here"];
+
+ NSString *strC3 = @"A string made with the at sign is here";
+
+ NSString *strC4 = [NSString stringWithFormat:@"This is string number %ld right here", (long)4];
+
+ NSString* strC5 = NSStringFromRect(ns_rect_4str);
+
+ NSString* strC6 = [@"/usr/doc/README.1ST" pathExtension];
+
+ NSString *strC7 = [NSString stringWithCharacters: myCharacters
+ length: sizeof myCharacters / sizeof *myCharacters];
+
+ NSString* strC8 = [@"/usr/doc/file.hasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTime" pathExtension];
+
+ NSString *strC9 = [NSString stringWithCharacters: myOtherCharacters
+ length: sizeof myOtherCharacters / sizeof *myOtherCharacters];
+
+ NSString *strC10 = [NSString stringWithFormat:@"This is a Unicode string %S number %ld right here", myNextCharacters, (long)4];
+
+ NSString *strD11 = NSStringFromClass([str10 class]);
+
+ NSString *strD12 = [NSString stringWithFormat:@"%@ %@ %@ %@", label1, processName, label2, processID];
+
+ NSString *eAcute = [NSString stringWithFormat: @"%C", 0x00E9];
+ NSString *randomHaziChar = [NSString stringWithFormat: @"%C", 0x9DC5];
+ NSString *japanese = @"色は匂へど散りぬるを";
+ NSString *italian = @"L'Italia è una Repubblica democratica, fondata sul lavoro. La sovranità appartiene al popolo, che la esercita nelle forme e nei limiti della Costituzione.";
+ NSString* french = @"Que veut cette horde d'esclaves, De traîtres, de rois conjurés?";
+ NSString* german = @"Über-Ich und aus den Ansprüchen der sozialen Umwelt";
+
+ void* data_set[3] = {str1,str2,str3};
+
+ NSString *hebrew = [NSString stringWithString:@"לילה טוב"];
+
+ NSArray* newArray = [[NSMutableArray alloc] init];
+ [newArray addObject:str1];
+ [newArray addObject:str2];
+ [newArray addObject:str3];
+ [newArray addObject:str4];
+ [newArray addObject:str5];
+ [newArray addObject:str6];
+ [newArray addObject:str7];
+ [newArray addObject:str8];
+ [newArray addObject:str9];
+ [newArray addObject:str10];
+ [newArray addObject:str11];
+ [newArray addObject:str12];
+ [newArray addObject:strA1];
+ [newArray addObject:strA2];
+ [newArray addObject:strA3];
+ [newArray addObject:strA4];
+ [newArray addObject:strA5];
+ [newArray addObject:strA6];
+ [newArray addObject:strA7];
+ [newArray addObject:strA8];
+ [newArray addObject:strA9];
+ [newArray addObject:strA10];
+ [newArray addObject:strA11];
+ [newArray addObject:strA12];
+ [newArray addObject:strB1];
+ [newArray addObject:strB2];
+ [newArray addObject:strB3];
+ [newArray addObject:strB4];
+ [newArray addObject:strB5];
+ [newArray addObject:strB6];
+ [newArray addObject:strB7];
+ [newArray addObject:strB8];
+ [newArray addObject:strB9];
+ [newArray addObject:strB10];
+ [newArray addObject:strB11];
+ [newArray addObject:strB12];
+ [newArray addObject:strC1];
+ [newArray addObject:strC2];
+ [newArray addObject:strC3];
+ [newArray addObject:strC4];
+ [newArray addObject:strC5];
+ [newArray addObject:strC6];
+ [newArray addObject:strC7];
+ [newArray addObject:strC8];
+ [newArray addObject:strC9];
+ [newArray addObject:strC10];
+ [newArray addObject:strC11];
+ [newArray addObject:strC12];
+ [newArray addObject:strD11];
+ [newArray addObject:strD12];
+
+ NSDictionary* newDictionary = [[NSDictionary alloc] initWithObjects:newArray forKeys:newArray];
+ NSDictionary *newMutableDictionary = [[NSMutableDictionary alloc] init];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar0"];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar1"];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar2"];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar3"];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar4"];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar5"];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar6"];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar7"];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar8"];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar9"];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar10"];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar11"];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar12"];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar13"];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar14"];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar15"];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar16"];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar17"];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar18"];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar19"];
+ [newMutableDictionary setObject:@"foo" forKey:@"bar20"];
+
+ NSAttributedString* attrString = [[NSAttributedString alloc] initWithString:@"hello world from foo" attributes:newDictionary];
+ [attrString isEqual:nil];
+ NSAttributedString* mutableAttrString = [[NSMutableAttributedString alloc] initWithString:@"hello world from foo" attributes:newDictionary];
+ [mutableAttrString isEqual:nil];
+
+ NSString* mutableString = [[NSMutableString alloc] initWithString:@"foo"];
+ [mutableString insertString:@"foo said this string needs to be very long so much longer than whatever other string has been seen ever before by anyone of the mankind that of course this is still not long enough given what foo our friend foo our lovely dearly friend foo desired of us so i am adding more stuff here for the sake of it and for the joy of our friend who is named guess what just foo. hence, dear friend foo, stay safe, your string is now long enough to accommodate your testing need and I will make sure that if not we extend it with even more fuzzy random meaningless words pasted one after the other from a long tiresome friday evening spent working in my office. my office mate went home but I am still randomly typing just for the fun of seeing what happens of the length of a Mutable String in Cocoa if it goes beyond one byte.. so be it, dear " atIndex:0];
+
+ NSString* mutableGetConst = [NSString stringWithCString:[mutableString cString]];
+
+ [mutableGetConst length];
+
+ NSData *immutableData = [[NSData alloc] initWithBytes:"HELLO" length:4];
+ NSData *mutableData = [[NSMutableData alloc] initWithBytes:"NODATA" length:6];
+
+ [mutableData appendBytes:"MOREDATA" length:8];
+
+ [immutableData length];
+ [mutableData length];
+
+ NSSet* nsset = [[NSSet alloc] initWithObjects:str1,str2,str3,nil];
+ NSSet *nsmutableset = [[NSMutableSet alloc] initWithObjects:str1,str2,str3,nil];
+ [nsmutableset addObject:str4];
+
+ CFDataRef data_ref = CFDataCreate(kCFAllocatorDefault, [immutableData bytes], 5);
+
+ CFMutableDataRef mutable_data_ref = CFDataCreateMutable(kCFAllocatorDefault, 8);
+ CFDataAppendBytes(mutable_data_ref, [mutableData bytes], 5);
+
+ CFMutableStringRef mutable_string_ref = CFStringCreateMutable(NULL,100);
+ CFStringAppend(mutable_string_ref, CFSTR("Wish ya knew"));
+
+ CFStringRef cfstring_ref = CFSTR("HELLO WORLD");
+
+
+ CFSetRef set_ref = CFSetCreate(NULL, data_set, 3, NULL);
+
+ CFMutableSetRef mutable_set_ref = CFSetCreateMutable(NULL, 5, NULL);
+
+ CFSetAddValue(mutable_set_ref, str1);
+ CFSetAddValue(mutable_set_ref, str2);
+ CFSetAddValue(mutable_set_ref, str3);
+ CFSetAddValue(mutable_set_ref, str4);
+ CFSetAddValue(mutable_set_ref, str5);
+ CFSetAddValue(mutable_set_ref, str6);
+ CFSetAddValue(mutable_set_ref, str7);
+ CFSetAddValue(mutable_set_ref, str8);
+ CFSetAddValue(mutable_set_ref, str9);
+ CFSetAddValue(mutable_set_ref, str10);
+ CFSetAddValue(mutable_set_ref, str11);
+ CFSetAddValue(mutable_set_ref, str12);
+
+
+ CFDictionaryRef cfdict_ref = CFDictionaryCreate(NULL, data_set, data_set, 3, NULL, NULL);
+ CFMutableDictionaryRef mutable_dict_ref = CFDictionaryCreateMutable(NULL, 16, NULL, NULL);
+
+ CFDictionarySetValue(mutable_dict_ref, str1, str1);
+ CFDictionarySetValue(mutable_dict_ref, str2, str2);
+ CFDictionarySetValue(mutable_dict_ref, str3, str3);
+ CFDictionarySetValue(mutable_dict_ref, str4, str1);
+ CFDictionarySetValue(mutable_dict_ref, str5, str2);
+ CFDictionarySetValue(mutable_dict_ref, str6, str3);
+ CFDictionarySetValue(mutable_dict_ref, str7, str1);
+ CFDictionarySetValue(mutable_dict_ref, str8, str2);
+ CFDictionarySetValue(mutable_dict_ref, str9, str3);
+ CFDictionarySetValue(mutable_dict_ref, str10, str1);
+ CFDictionarySetValue(mutable_dict_ref, str11, str2);
+ CFDictionarySetValue(mutable_dict_ref, str12, str3);
+
+ CFArrayRef cfarray_ref = CFArrayCreate(NULL, data_set, 3, NULL);
+ CFMutableArrayRef mutable_array_ref = CFArrayCreateMutable(NULL, 16, NULL);
+
+ CFArraySetValueAtIndex(mutable_array_ref, 0, str1);
+ CFArraySetValueAtIndex(mutable_array_ref, 1, str2);
+ CFArraySetValueAtIndex(mutable_array_ref, 2, str3);
+ CFArraySetValueAtIndex(mutable_array_ref, 3, str4);
+ CFArraySetValueAtIndex(mutable_array_ref, 0, str5); // replacing value at 0!!
+ CFArraySetValueAtIndex(mutable_array_ref, 4, str6);
+ CFArraySetValueAtIndex(mutable_array_ref, 5, str7);
+ CFArraySetValueAtIndex(mutable_array_ref, 6, str8);
+ CFArraySetValueAtIndex(mutable_array_ref, 7, str9);
+ CFArraySetValueAtIndex(mutable_array_ref, 8, str10);
+ CFArraySetValueAtIndex(mutable_array_ref, 9, str11);
+ CFArraySetValueAtIndex(mutable_array_ref, 10, str12);
+
+ CFMutableBagRef mutable_bag_ref = CFBagCreateMutable(NULL, 15, NULL);
+
+ CFBagSetValue(mutable_bag_ref, strB10);
+ CFBagSetValue(mutable_bag_ref, str1);
+ CFBagSetValue(mutable_bag_ref, str2);
+ CFBagSetValue(mutable_bag_ref, str3);
+ CFBagSetValue(mutable_bag_ref, str4);
+ CFBagSetValue(mutable_bag_ref, str5);
+ CFBagSetValue(mutable_bag_ref, str6);
+ CFBagSetValue(mutable_bag_ref, str7);
+ CFBagSetValue(mutable_bag_ref, str8);
+ CFBagSetValue(mutable_bag_ref, str9);
+ CFBagSetValue(mutable_bag_ref, str10);
+ CFBagSetValue(mutable_bag_ref, str11);
+ CFBagSetValue(mutable_bag_ref, str12);
+ CFBagSetValue(mutable_bag_ref, strA1);
+ CFBagSetValue(mutable_bag_ref, strA2);
+ CFBagSetValue(mutable_bag_ref, strA3);
+
+ CFBagRef cfbag_ref = CFBagCreateCopy(NULL, mutable_bag_ref);
+
+ CFBagSetValue(mutable_bag_ref, strB8);
+ CFBagSetValue(mutable_bag_ref, strC4);
+
+
+ CFBinaryHeapRef binheap_ref = CFBinaryHeapCreate(NULL, 15, &kCFStringBinaryHeapCallBacks, NULL);
+ CFBinaryHeapAddValue(binheap_ref, str1);
+ CFBinaryHeapAddValue(binheap_ref, str2);
+ CFBinaryHeapAddValue(binheap_ref, str3);
+ CFBinaryHeapAddValue(binheap_ref, str4);
+ CFBinaryHeapAddValue(binheap_ref, str5);
+ CFBinaryHeapAddValue(binheap_ref, str6);
+ CFBinaryHeapAddValue(binheap_ref, str7);
+ CFBinaryHeapAddValue(binheap_ref, str8);
+ CFBinaryHeapAddValue(binheap_ref, str9);
+ CFBinaryHeapAddValue(binheap_ref, str10);
+ CFBinaryHeapAddValue(binheap_ref, str11);
+ CFBinaryHeapAddValue(binheap_ref, str12);
+ CFBinaryHeapAddValue(binheap_ref, strA1);
+ CFBinaryHeapAddValue(binheap_ref, strB1);
+ CFBinaryHeapAddValue(binheap_ref, strC1);
+ CFBinaryHeapAddValue(binheap_ref, strA11);
+ CFBinaryHeapAddValue(binheap_ref, strB11);
+ CFBinaryHeapAddValue(binheap_ref, strC11);
+ CFBinaryHeapAddValue(binheap_ref, strB12);
+ CFBinaryHeapAddValue(binheap_ref, strC12);
+ CFBinaryHeapAddValue(binheap_ref, strA12);
+
+ CFURLRef cfurl_ref = CFURLCreateWithString(NULL, CFSTR("http://www.foo.bar/"), NULL);
+ CFURLRef cfchildurl_ref = CFURLCreateWithString(NULL, CFSTR("page.html"), cfurl_ref);
+ CFURLRef cfgchildurl_ref = CFURLCreateWithString(NULL, CFSTR("?whatever"), cfchildurl_ref);
+
+ NSDictionary *error_userInfo = @{@"a": @1, @"b" : @2};
+ NSError *nserror = [[NSError alloc] initWithDomain:@"Foobar" code:12 userInfo:error_userInfo];
+
+ NSBundle* bundle_string = [[NSBundle alloc] initWithPath:@"/System/Library/Frameworks/Accelerate.framework"];
+ NSBundle* bundle_url = [[NSBundle alloc] initWithURL:[[NSURL alloc] initWithString:@"file://localhost/System/Library/Frameworks/Cocoa.framework"]];
+
+ NSBundle* main_bundle = [NSBundle mainBundle];
+
+ NSArray* bundles = [NSBundle allBundles];
+
+ NSURL *nsurl0;
+
+ for (NSBundle* bundle in bundles)
+ {
+ nsurl0 = [bundle bundleURL];
+ }
+
+ NSException* except0 = [[NSException alloc] initWithName:@"TheGuyWhoHasNoName" reason:@"cuz it's funny" userInfo:nil];
+ NSException* except1 = [[NSException alloc] initWithName:@"TheGuyWhoHasNoName~1" reason:@"cuz it's funny" userInfo:nil];
+ NSException* except2 = [[NSException alloc] initWithName:@"TheGuyWhoHasNoName`2" reason:@"cuz it's funny" userInfo:nil];
+ NSException* except3 = [[NSException alloc] initWithName:@"TheGuyWhoHasNoName/3" reason:@"cuz it's funny" userInfo:nil];
+
+ NSMachPort *port = [NSMachPort port];
+
+ NSURL *nsurl = [[NSURL alloc] initWithString:@"http://www.foo.bar"];
+ NSURL *nsurl2 = [NSURL URLWithString:@"page.html" relativeToURL:nsurl];
+ NSURL *nsurl3 = [NSURL URLWithString:@"?whatever" relativeToURL:nsurl2];
+
+ NSDate *date1 = [NSDate dateWithNaturalLanguageString:@"6pm April 10, 1985"];
+ NSDate *date2 = [NSDate dateWithNaturalLanguageString:@"12am January 1, 2011"];
+ NSDate *date3 = [NSDate date];
+ NSDate *date4 = [NSDate dateWithTimeIntervalSince1970:24*60*60];
+
+ CFAbsoluteTime date1_abs = CFDateGetAbsoluteTime(date1);
+ CFAbsoluteTime date2_abs = CFDateGetAbsoluteTime(date2);
+ CFAbsoluteTime date3_abs = CFDateGetAbsoluteTime(date3);
+ CFAbsoluteTime date4_abs = CFDateGetAbsoluteTime(date4);
+
+ NSCountedSet *nscounted_set = [[NSCountedSet alloc] initWithCapacity:5];
+
+ [nscounted_set addObject:str0];
+ [nscounted_set addObject:str1];
+ [nscounted_set addObject:str0];
+ [nscounted_set addObject:str0];
+ [nscounted_set addObject:@"foo1"];
+ [nscounted_set addObject:@"foo2"];
+ [nscounted_set addObject:@"foo3"];
+
+ NSIndexSet *iset1 = [[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(1, 4)];
+ NSIndexSet *iset2 = [[NSIndexSet alloc] initWithIndexesInRange:NSMakeRange(1, 512)];
+
+ NSMutableIndexSet *imset = [[NSMutableIndexSet alloc] init];
+ [imset addIndex:1936];
+ [imset addIndex:7];
+ [imset addIndex:9];
+ [imset addIndex:11];
+ [imset addIndex:24];
+ [imset addIndex:41];
+ [imset addIndex:58];
+ [imset addIndex:61];
+ [imset addIndex:62];
+ [imset addIndex:63];
+
+ CFTimeZoneRef cupertino = CFTimeZoneCreateWithName (
+ NULL,
+ CFSTR("PST"),
+ YES);
+ CFTimeZoneRef home = CFTimeZoneCreateWithName (
+ NULL,
+ CFSTR("Europe/Rome"),
+ YES);
+ CFTimeZoneRef europe = CFTimeZoneCreateWithName (
+ NULL,
+ CFSTR("CET"),
+ YES);
+
+ NSTimeZone *cupertino_ns = [NSTimeZone timeZoneWithAbbreviation:@"PST"];
+ NSTimeZone *home_ns = [NSTimeZone timeZoneWithName:@"Europe/Rome"];
+ NSTimeZone *europe_ns = [NSTimeZone timeZoneWithAbbreviation:@"CET"];
+
+ NSHost *localhost = [NSHost hostWithAddress:@"127.0.0.1"];
+
+#ifndef IOS
+ NSTask *my_task = [[NSTask alloc] init];
+#endif
+
+
+ CFGregorianUnits cf_greg_units = {1,3,5,12,5,7};
+ CFGregorianDate cf_greg_date = CFAbsoluteTimeGetGregorianDate(CFDateGetAbsoluteTime(date1), NULL);
+ CFRange cf_range = {4,4};
+ NSPoint ns_point = {4,4};
+ NSRange ns_range = {4,4};
+
+ NSValue *range_value = [NSValue valueWithRange:ns_range];
+
+ NSRect ns_rect = {{1,1},{5,5}};
+ NSRect* ns_rect_ptr = &ns_rect;
+ NSRectArray ns_rect_arr = &ns_rect;
+ NSSize ns_size = {5,7};
+ NSSize* ns_size_ptr = &ns_size;
+
+ CGSize cg_size = {1,6};
+ CGPoint cg_point = {2,7};
+ CGRect cg_rect = {{1,2}, {7,7}};
+
+#ifndef IOS
+ RGBColor rgb_color = {3,56,35};
+ RGBColor* rgb_color_ptr = &rgb_color;
+#endif
+
+ Rect rect = {4,8,4,7};
+ Rect* rect_ptr = &rect;
+
+ Point point = {7,12};
+ Point* point_ptr = &point;
+
+#ifndef IOS
+ HIPoint hi_point = {7,12};
+ HIRect hi_rect = {{3,5},{4,6}};
+#endif
+
+ SEL foo_selector = @selector(foo_selector_impl);
+
+ CFMutableBitVectorRef mut_bv = CFBitVectorCreateMutable(NULL, 64);
+ CFBitVectorSetCount(mut_bv, 50);
+ CFBitVectorSetBitAtIndex(mut_bv, 0, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 1, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 2, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 5, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 6, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 8, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 10, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 11, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 16, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 17, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 19, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 20, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 22, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 24, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 28, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 29, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 30, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 30, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 31, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 34, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 35, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 37, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 39, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 40, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 41, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 43, 1);
+ CFBitVectorSetBitAtIndex(mut_bv, 47, 1);
+
+ Molecule *molecule = [Molecule new];
+
+ Class myclass = NSClassFromString(@"NSValue");
+ Class myclass2 = [str0 class];
+ Class myclass3 = [molecule class];
+ Class myclass4 = NSClassFromString(@"NSMutableArray");
+ Class myclass5 = [nil class];
+
+ NSArray *components = @[@"usr", @"blah", @"stuff"];
+ NSString *path = [NSString pathWithComponents: components];
+
+ [molecule addObserver:[My_KVO_Observer new] forKeyPath:@"atoms" options:0 context:NULL]; // Set break point at this line.
+ [newMutableDictionary addObserver:[My_KVO_Observer new] forKeyPath:@"weirdKeyToKVO" options:NSKeyValueObservingOptionNew context:NULL];
+
+ [molecule setAtoms:nil];
+ [molecule setAtoms:[NSMutableArray new]];
+
+ [pool drain];
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/Makefile
new file mode 100644
index 000000000000..0d94c2247f14
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../../../make
+
+OBJC_SOURCES := main.m
+
+CFLAGS_EXTRAS += -w
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/TestDataFormatterNSString.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/TestDataFormatterNSString.py
new file mode 100644
index 000000000000..e11c45e9038e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/TestDataFormatterNSString.py
@@ -0,0 +1,107 @@
+# encoding: utf-8
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import datetime
+import lldbsuite.test.lldbutil as lldbutil
+
+class NSStringDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def appkit_tester_impl(self,commands):
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type synth clear', check=False)
+
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+ commands()
+
+ @skipUnlessDarwin
+ def test_nsstring_with_run_command(self):
+ """Test formatters for NSString."""
+ self.appkit_tester_impl(self.nsstring_data_formatter_commands)
+
+ @skipUnlessDarwin
+ def test_rdar11106605_with_run_command(self):
+ """Check that Unicode characters come out of CFString summary correctly."""
+ self.appkit_tester_impl(self.rdar11106605_commands)
+
+ @skipUnlessDarwin
+ def test_nsstring_withNULS_with_run_command(self):
+ """Test formatters for NSString."""
+ self.appkit_tester_impl(self.nsstring_withNULs_commands)
+
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.m', '// break here')
+
+ def rdar11106605_commands(self):
+ """Check that Unicode characters come out of CFString summary correctly."""
+ self.expect('frame variable italian', substrs = ['L\'Italia è una Repubblica democratica, fondata sul lavoro. La sovranità appartiene al popolo, che la esercita nelle forme e nei limiti della Costituzione.'])
+ self.expect('frame variable french', substrs = ['Que veut cette horde d\'esclaves, De traîtres, de rois conjurés?'])
+ self.expect('frame variable german', substrs = ['Über-Ich und aus den Ansprüchen der sozialen Umwelt'])
+ self.expect('frame variable japanese', substrs = ['色は匂へど散りぬるを'])
+ self.expect('frame variable hebrew', substrs = ['לילה טוב'])
+
+ def nsstring_data_formatter_commands(self):
+ self.expect('frame variable str0 str1 str2 str3 str4 str5 str6 str8 str9 str10 str11 label1 label2 processName str12',
+ substrs = ['(NSString *) str1 = ',' @"A rather short ASCII NSString object is here"',
+ # '(NSString *) str0 = ',' @"255"',
+ '(NSString *) str1 = ',' @"A rather short ASCII NSString object is here"',
+ '(NSString *) str2 = ',' @"A rather short UTF8 NSString object is here"',
+ '(NSString *) str3 = ',' @"A string made with the at sign is here"',
+ '(NSString *) str4 = ',' @"This is string number 4 right here"',
+ '(NSString *) str5 = ',' @"{{1, 1}, {5, 5}}"',
+ '(NSString *) str6 = ',' @"1ST"',
+ '(NSString *) str8 = ',' @"hasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTime',
+ '(NSString *) str9 = ',' @"a very much boring task to write a string this way!!',
+ '(NSString *) str10 = ',' @"This is a Unicode string σ number 4 right here"',
+ '(NSString *) str11 = ',' @"__NSCFString"',
+ '(NSString *) label1 = ',' @"Process Name: "',
+ '(NSString *) label2 = ',' @"Process Id: "',
+ '(NSString *) str12 = ',' @"Process Name: a.out Process Id:'])
+ self.expect('frame variable attrString mutableAttrString mutableGetConst',
+ substrs = ['(NSAttributedString *) attrString = ',' @"hello world from foo"',
+ '(NSAttributedString *) mutableAttrString = ',' @"hello world from foo"',
+ '(NSString *) mutableGetConst = ',' @"foo said this string needs to be very long so much longer than whatever other string has been seen ever before by anyone of the mankind that of course this is still not long enough given what foo our friend foo our lovely dearly friend foo desired of us so i am adding more stuff here for the sake of it and for the joy of our friend who is named guess what just foo. hence, dear friend foo, stay safe, your string is now long enough to accommodate your testing need and I will make sure that if not we extend it with even more fuzzy random meaningless words pasted one after the other from a long tiresome friday evening spent working in my office. my office mate went home but I am still randomly typing just for the fun of seeing what happens of the length of a Mutable String in Cocoa if it goes beyond one byte.. so be it, dear foo"'])
+
+ self.expect('expr -d run-target -- path',substrs = ['usr/blah/stuff'])
+ self.expect('frame variable path',substrs = ['usr/blah/stuff'])
+
+ def nsstring_withNULs_commands(self):
+ """Check that the NSString formatter supports embedded NULs in the text"""
+ self.expect('po strwithNULs', substrs=['a very much boring task to write'])
+ self.expect('expr [strwithNULs length]', substrs=['54'])
+ self.expect('frame variable strwithNULs', substrs=['@"a very much boring task to write\\0a string this way!!'])
+ self.expect('po strwithNULs2', substrs=['a very much boring task to write'])
+ self.expect('expr [strwithNULs2 length]', substrs=['52'])
+ self.expect('frame variable strwithNULs2', substrs=['@"a very much boring task to write\\0a string this way!!'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/main.m b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/main.m
new file mode 100644
index 000000000000..7b8c3785a18c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-objc/nsstring/main.m
@@ -0,0 +1,99 @@
+//===-- main.m ------------------------------------------------*- ObjC -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#import <Foundation/Foundation.h>
+
+#if defined(__APPLE__)
+#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
+#define IOS
+#endif
+#endif
+
+#if defined(IOS)
+#import <Foundation/NSGeometry.h>
+#else
+#import <Carbon/Carbon.h>
+#endif
+
+int main (int argc, const char * argv[])
+{
+
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+
+ NSString *str0 = [[NSNumber numberWithUnsignedLongLong:0xFF] stringValue];
+ NSString *str1 = [NSString stringWithCString:"A rather short ASCII NSString object is here" encoding:NSASCIIStringEncoding];
+ NSString *str2 = [NSString stringWithUTF8String:"A rather short UTF8 NSString object is here"];
+ NSString *str3 = @"A string made with the at sign is here";
+ NSString *str4 = [NSString stringWithFormat:@"This is string number %ld right here", (long)4];
+ NSRect ns_rect_4str = {{1,1},{5,5}};
+ NSString* str5 = NSStringFromRect(ns_rect_4str);
+ NSString* str6 = [@"/usr/doc/README.1ST" pathExtension];
+ const unichar myCharacters[] = {0x03C3,'x','x'};
+ NSString *str7 = [NSString stringWithCharacters: myCharacters
+ length: sizeof myCharacters / sizeof *myCharacters];
+ NSString* str8 = [@"/usr/doc/file.hasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTimehasVeryLongExtensionThisTime" pathExtension];
+ const unichar myOtherCharacters[] = {'a',' ', 'v','e','r','y',' ',
+ 'm','u','c','h',' ','b','o','r','i','n','g',' ','t','a','s','k',
+ ' ','t','o',' ','w','r','i','t','e', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g', ' ',
+ 't','h','i','s',' ','w','a','y','!','!',0x03C3, 0};
+ NSString *str9 = [NSString stringWithCharacters: myOtherCharacters
+ length: sizeof myOtherCharacters / sizeof *myOtherCharacters];
+ const unichar myNextCharacters[] = {0x03C3, 0x0000};
+ NSString *str10 = [NSString stringWithFormat:@"This is a Unicode string %S number %ld right here", myNextCharacters, (long)4];
+ NSString *str11 = NSStringFromClass([str10 class]);
+ NSString *label1 = @"Process Name: ";
+ NSString *label2 = @"Process Id: ";
+ NSString *processName = [[NSProcessInfo processInfo] processName];
+ NSString *processID = [NSString stringWithFormat:@"%d", [[NSProcessInfo processInfo] processIdentifier]];
+ NSString *str12 = [NSString stringWithFormat:@"%@ %@ %@ %@", label1, processName, label2, processID];
+ NSString *eAcute = [NSString stringWithFormat: @"%C", 0x00E9];
+ NSString *randomHaziChar = [NSString stringWithFormat: @"%C", 0x9DC5];
+ NSString *japanese = @"色は匂へど散りぬるを";
+ NSString *italian = @"L'Italia è una Repubblica democratica, fondata sul lavoro. La sovranità appartiene al popolo, che la esercita nelle forme e nei limiti della Costituzione.";
+ NSString* french = @"Que veut cette horde d'esclaves, De traîtres, de rois conjurés?";
+ NSString* german = @"Über-Ich und aus den Ansprüchen der sozialen Umwelt";
+ void* data_set[3] = {str1,str2,str3};
+ NSString *hebrew = [NSString stringWithString:@"לילה טוב"];
+
+ NSAttributedString* attrString = [[NSAttributedString alloc] initWithString:@"hello world from foo" attributes:[NSDictionary new]];
+ [attrString isEqual:nil];
+ NSAttributedString* mutableAttrString = [[NSMutableAttributedString alloc] initWithString:@"hello world from foo" attributes:[NSDictionary new]];
+ [mutableAttrString isEqual:nil];
+
+ NSString* mutableString = [[NSMutableString alloc] initWithString:@"foo"];
+ [mutableString insertString:@"foo said this string needs to be very long so much longer than whatever other string has been seen ever before by anyone of the mankind that of course this is still not long enough given what foo our friend foo our lovely dearly friend foo desired of us so i am adding more stuff here for the sake of it and for the joy of our friend who is named guess what just foo. hence, dear friend foo, stay safe, your string is now long enough to accommodate your testing need and I will make sure that if not we extend it with even more fuzzy random meaningless words pasted one after the other from a long tiresome friday evening spent working in my office. my office mate went home but I am still randomly typing just for the fun of seeing what happens of the length of a Mutable String in Cocoa if it goes beyond one byte.. so be it, dear " atIndex:0];
+
+ NSString* mutableGetConst = [NSString stringWithCString:[mutableString cString]];
+
+ [mutableGetConst length];
+ CFMutableStringRef mutable_string_ref = CFStringCreateMutable(NULL,100);
+ CFStringAppend(mutable_string_ref, CFSTR("Wish ya knew"));
+ CFStringRef cfstring_ref = CFSTR("HELLO WORLD");
+
+ NSArray *components = @[@"usr", @"blah", @"stuff"];
+ NSString *path = [NSString pathWithComponents: components];
+
+ const unichar someOfTheseAreNUL[] = {'a',' ', 'v','e','r','y',' ',
+ 'm','u','c','h',' ','b','o','r','i','n','g',' ','t','a','s','k',
+ ' ','t','o',' ','w','r','i','t','e', 0, 'a', ' ', 's', 't', 'r', 'i', 'n', 'g', ' ',
+ 't','h','i','s',' ','w','a','y','!','!', 0x03C3, 0};
+ NSString *strwithNULs = [NSString stringWithCharacters: someOfTheseAreNUL
+ length: sizeof someOfTheseAreNUL / sizeof *someOfTheseAreNUL];
+
+ const unichar someOfTheseAreNUL2[] = {'a',' ', 'v','e','r','y',' ',
+ 'm','u','c','h',' ','b','o','r','i','n','g',' ','t','a','s','k',
+ ' ','t','o',' ','w','r','i','t','e', 0, 'a', ' ', 's', 't', 'r', 'i', 'n', 'g', ' ',
+ 't','h','i','s',' ','w','a','y','!','!'};
+ NSString *strwithNULs2 = [NSString stringWithCharacters: someOfTheseAreNUL2
+ length: sizeof someOfTheseAreNUL2 / sizeof *someOfTheseAreNUL2];
+
+ [pool drain]; // break here
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/Makefile
new file mode 100644
index 000000000000..9f7fb1ca6231
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+
+CFLAGS_EXTRAS += -w
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/TestFormattersOneIsSingular.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/TestFormattersOneIsSingular.py
new file mode 100644
index 000000000000..1281f17ab58a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/TestFormattersOneIsSingular.py
@@ -0,0 +1,90 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import datetime
+import lldbsuite.test.lldbutil as lldbutil
+
+class DataFormatterOneIsSingularTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipUnlessDarwin
+ def test_one_is_singular_with_run_command(self):
+ """Test that 1 item is not as reported as 1 items."""
+ self.build()
+ self.oneness_data_formatter_commands()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.m', '// Set break point at this line.')
+
+ def oneness_data_formatter_commands(self):
+ """Test that 1 item is not as reported as 1 items."""
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type synth clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ # Now check that we are displaying Cocoa classes correctly
+ self.expect('frame variable key',
+ substrs = ['@"1 element"'])
+ self.expect('frame variable key', matching=False,
+ substrs = ['1 elements'])
+ self.expect('frame variable value',
+ substrs = ['@"1 element"'])
+ self.expect('frame variable value', matching=False,
+ substrs = ['1 elements'])
+ self.expect('frame variable dict',
+ substrs = ['1 key/value pair'])
+ self.expect('frame variable dict', matching=False,
+ substrs = ['1 key/value pairs'])
+ self.expect('frame variable mutable_bag_ref',
+ substrs = ['@"1 value"'])
+ self.expect('frame variable mutable_bag_ref', matching=False,
+ substrs = ['1 values'])
+ self.expect('frame variable nscounted_set',
+ substrs = ['1 element'])
+ self.expect('frame variable nscounted_set', matching=False,
+ substrs = ['1 elements'])
+ self.expect('frame variable imset',
+ substrs = ['1 index'])
+ self.expect('frame variable imset', matching=False,
+ substrs = ['1 indexes'])
+ self.expect('frame variable binheap_ref',
+ substrs = ['@"1 item"'])
+ self.expect('frame variable binheap_ref', matching=False,
+ substrs = ['1 items'])
+ self.expect('frame variable nsset',
+ substrs = ['1 element'])
+ self.expect('frame variable nsset', matching=False,
+ substrs = ['1 elements'])
+ self.expect('frame variable immutableData',
+ substrs = ['1 byte'])
+ self.expect('frame variable immutableData', matching=False,
+ substrs = ['1 bytes'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/main.m b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/main.m
new file mode 100644
index 000000000000..7204d3c7b202
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-proper-plurals/main.m
@@ -0,0 +1,42 @@
+//===-- main.m ------------------------------------------------*- ObjC -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#import <Foundation/Foundation.h>
+
+int main (int argc, const char * argv[])
+{
+
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+
+
+ NSArray* key = [NSArray arrayWithObjects:@"foo",nil];
+ NSArray* value = [NSArray arrayWithObjects:@"key",nil];
+ NSDictionary *dict = [NSDictionary dictionaryWithObjects:value forKeys:key];
+
+ CFMutableBagRef mutable_bag_ref = CFBagCreateMutable(NULL, 15, NULL);
+ CFBagSetValue(mutable_bag_ref, CFSTR("Hello world"));
+
+ NSCountedSet *nscounted_set = [[NSCountedSet alloc] initWithCapacity:5];
+ [nscounted_set addObject:@"foo"];
+
+ NSMutableIndexSet *imset = [[NSMutableIndexSet alloc] init];
+ [imset addIndex:4];
+
+ CFBinaryHeapRef binheap_ref = CFBinaryHeapCreate(NULL, 15, &kCFStringBinaryHeapCallBacks, NULL);
+ CFBinaryHeapAddValue(binheap_ref, CFSTR("Hello world"));
+
+ NSSet* nsset = [[NSSet alloc] initWithObjects:@"foo",nil];
+
+ NSData *immutableData = [[NSData alloc] initWithBytes:"HELLO" length:1];
+
+
+ [pool drain];// Set break point at this line.
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/TestPtrToArrayFormatting.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/TestPtrToArrayFormatting.py
new file mode 100644
index 000000000000..86cd3c427288
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/TestPtrToArrayFormatting.py
@@ -0,0 +1,57 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class PtrToArrayDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test_with_run_command(self):
+ """Test that LLDB handles the clang typeclass Paren correctly."""
+ self.build()
+ self.data_formatter_commands()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def data_formatter_commands(self):
+ """Test that LLDB handles the clang typeclass Paren correctly."""
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format delete hex', check=False)
+ self.runCmd('type summary clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.expect('p *(int (*)[3])foo',
+ substrs = ['(int [3]) $','[0] = 1','[1] = 2','[2] = 3'])
+
+ self.expect('p *(int (*)[3])foo', matching=False,
+ substrs = ['01 00 00 00 02 00 00 00 03 00 00 00'])
+ self.expect('p *(int (*)[3])foo', matching=False,
+ substrs = ['0x000000030000000200000001'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/main.cpp
new file mode 100644
index 000000000000..15fa5614d7fd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-ptr-to-array/main.cpp
@@ -0,0 +1,17 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+bool bar(int const *foo) {
+ return foo != 0; // Set break point at this line.
+}
+
+int main() {
+ int foo[] = {1,2,3};
+ return bar(foo);
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py
new file mode 100644
index 000000000000..d202ff5d64e1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/TestDataFormatterPythonSynth.py
@@ -0,0 +1,252 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class PythonSynthDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfFreeBSD # llvm.org/pr20545 bogus output confuses buildbot parser
+ def test_with_run_command(self):
+ """Test data formatter commands."""
+ self.build()
+ self.data_formatter_commands()
+
+ def test_rdar10960550_with_run_command(self):
+ """Test data formatter commands."""
+ self.build()
+ self.rdar10960550_formatter_commands()
+
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+ self.line2 = line_number('main.cpp', '// Set cast break point at this line.')
+ self.line3 = line_number('main.cpp', '// Set second cast break point at this line.')
+
+ def data_formatter_commands(self):
+ """Test using Python synthetic children provider."""
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ # print the f00_1 variable without a synth
+ self.expect("frame variable f00_1",
+ substrs = ['a = 0',
+ 'b = 1',
+ 'r = 33']);
+
+ # now set up the synth
+ self.runCmd("script from fooSynthProvider import *")
+ self.runCmd("type synth add -l fooSynthProvider foo")
+
+ # check that we get the two real vars and the fake_a variables
+ self.expect("frame variable f00_1",
+ substrs = ['r = 33',
+ 'fake_a = 16777216',
+ 'a = 0']);
+
+ # check that we do not get the extra vars
+ self.expect("frame variable f00_1", matching=False,
+ substrs = ['b = 1']);
+
+ # check access to members by name
+ self.expect('frame variable f00_1.fake_a',
+ substrs = ['16777216'])
+
+ # check access to members by index
+ self.expect('frame variable f00_1[1]',
+ substrs = ['16777216'])
+
+ # put synthetic children in summary in several combinations
+ self.runCmd("type summary add --summary-string \"fake_a=${svar.fake_a}\" foo")
+ self.expect('frame variable f00_1',
+ substrs = ['fake_a=16777216'])
+ self.runCmd("type summary add --summary-string \"fake_a=${svar[1]}\" foo")
+ self.expect('frame variable f00_1',
+ substrs = ['fake_a=16777216'])
+
+ # clear the summary
+ self.runCmd("type summary delete foo")
+
+ # check that the caching does not span beyond the stopoint
+ self.runCmd("n")
+
+ self.expect("frame variable f00_1",
+ substrs = ['r = 33',
+ 'fake_a = 16777216',
+ 'a = 1']);
+
+ # check that altering the object also alters fake_a
+ self.runCmd("expr f00_1.a = 280")
+ self.expect("frame variable f00_1",
+ substrs = ['r = 33',
+ 'fake_a = 16777217',
+ 'a = 280']);
+
+ # check that expanding a pointer does the right thing
+ self.expect("frame variable --ptr-depth 1 f00_ptr",
+ substrs = ['r = 45',
+ 'fake_a = 218103808',
+ 'a = 12'])
+
+ # now add a filter.. it should fail
+ self.expect("type filter add foo --child b --child j", error=True,
+ substrs = ['cannot add'])
+
+ # we get the synth again..
+ self.expect('frame variable f00_1', matching=False,
+ substrs = ['b = 1',
+ 'j = 17'])
+ self.expect("frame variable --ptr-depth 1 f00_ptr",
+ substrs = ['r = 45',
+ 'fake_a = 218103808',
+ 'a = 12'])
+
+ # now delete the synth and add the filter
+ self.runCmd("type synth delete foo")
+ self.runCmd("type filter add foo --child b --child j")
+
+ self.expect('frame variable f00_1',
+ substrs = ['b = 1',
+ 'j = 17'])
+ self.expect("frame variable --ptr-depth 1 f00_ptr", matching=False,
+ substrs = ['r = 45',
+ 'fake_a = 218103808',
+ 'a = 12'])
+
+ # now add the synth and it should fail
+ self.expect("type synth add -l fooSynthProvider foo", error=True,
+ substrs = ['cannot add'])
+
+ # check the listing
+ self.expect('type synth list', matching=False,
+ substrs = ['foo',
+ 'Python class fooSynthProvider'])
+ self.expect('type filter list',
+ substrs = ['foo',
+ '.b',
+ '.j'])
+
+ # delete the filter, add the synth
+ self.runCmd("type filter delete foo")
+ self.runCmd("type synth add -l fooSynthProvider foo")
+
+ self.expect('frame variable f00_1', matching=False,
+ substrs = ['b = 1',
+ 'j = 17'])
+ self.expect("frame variable --ptr-depth 1 f00_ptr",
+ substrs = ['r = 45',
+ 'fake_a = 218103808',
+ 'a = 12'])
+
+ # check the listing
+ self.expect('type synth list',
+ substrs = ['foo',
+ 'Python class fooSynthProvider'])
+ self.expect('type filter list', matching=False,
+ substrs = ['foo',
+ '.b',
+ '.j'])
+
+ # delete the synth and check that we get good output
+ self.runCmd("type synth delete foo")
+
+ self.expect("frame variable f00_1",
+ substrs = ['a = 280',
+ 'b = 1',
+ 'j = 17']);
+
+ self.expect("frame variable f00_1", matching=False,
+ substrs = ['fake_a = '])
+
+ def rdar10960550_formatter_commands(self):
+ """Test that synthetic children persist stoppoints."""
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ # The second breakpoint is on a multi-line expression, so the comment can't be on the right line...
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line2, num_expected_locations=1, loc_exact=False)
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line3, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.runCmd("command script import ./ftsp.py --allow-reload")
+ self.runCmd("type synth add -l ftsp.ftsp wrapint")
+
+ # we need to check that the VO is properly updated so that the same synthetic children are reused
+ # but their values change correctly across stop-points - in order to do this, self.runCmd("next")
+ # does not work because it forces a wipe of the stack frame - this is why we are using this more contrived
+ # mechanism to achieve our goal of preserving test_cast as a VO
+ test_cast = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('test_cast')
+
+ str_cast = str(test_cast)
+
+ if self.TraceOn():
+ print(str_cast)
+
+ self.assertTrue(str_cast.find('A') != -1, 'could not find A in output')
+ self.assertTrue(str_cast.find('B') != -1, 'could not find B in output')
+ self.assertTrue(str_cast.find('C') != -1, 'could not find C in output')
+ self.assertTrue(str_cast.find('D') != -1, 'could not find D in output')
+ self.assertTrue(str_cast.find("4 = '\\0'") != -1, 'could not find item 4 == 0')
+
+ self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().StepOver()
+
+ str_cast = str(test_cast)
+
+ if self.TraceOn():
+ print(str_cast)
+
+ # we detect that all the values of the child objects have changed - but the counter-generated item
+ # is still fixed at 0 because it is cached - this would fail if update(self): in ftsp returned False
+ # or if synthetic children were not being preserved
+ self.assertTrue(str_cast.find('Q') != -1, 'could not find Q in output')
+ self.assertTrue(str_cast.find('X') != -1, 'could not find X in output')
+ self.assertTrue(str_cast.find('T') != -1, 'could not find T in output')
+ self.assertTrue(str_cast.find('F') != -1, 'could not find F in output')
+ self.assertTrue(str_cast.find("4 = '\\0'") != -1, 'could not find item 4 == 0')
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/fooSynthProvider.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/fooSynthProvider.py
new file mode 100644
index 000000000000..0dc2c233e2a6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/fooSynthProvider.py
@@ -0,0 +1,23 @@
+import lldb
+class fooSynthProvider:
+ def __init__(self, valobj, dict):
+ self.valobj = valobj;
+ self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt)
+ def num_children(self):
+ return 3;
+ def get_child_at_index(self, index):
+ if index == 0:
+ child = self.valobj.GetChildMemberWithName('a');
+ if index == 1:
+ child = self.valobj.CreateChildAtOffset ('fake_a', 1, self.int_type);
+ if index == 2:
+ child = self.valobj.GetChildMemberWithName('r');
+ return child;
+ def get_child_index(self, name):
+ if name == 'a':
+ return 0;
+ if name == 'fake_a':
+ return 1;
+ return 2;
+ def update(self):
+ return True \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/ftsp.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/ftsp.py
new file mode 100644
index 000000000000..d162b00db329
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/ftsp.py
@@ -0,0 +1,32 @@
+import lldb
+
+counter = 0
+
+class ftsp:
+ def __init__(self, valobj, dict):
+ self.valobj = valobj;
+ def num_children(self):
+ if self.char.IsValid():
+ return 5;
+ return 0;
+ def get_child_index(self,name):
+ return 0;
+ def get_child_at_index(self,index):
+ if index == 0:
+ return self.x.Cast(self.char)
+ if index == 4:
+ return self.valobj.CreateValueFromExpression(str(index),'(char)('+str(self.count)+')')
+ return self.x.CreateChildAtOffset(str(index),
+ index,
+ self.char);
+ def update(self):
+ self.x = self.valobj.GetChildMemberWithName('x');
+ self.char = self.valobj.GetType().GetBasicType(lldb.eBasicTypeChar)
+ global counter
+ self.count = counter
+ counter = counter + 1
+ return True # important: if we return False here, or fail to return, the test will fail
+
+def __lldb_init_module(debugger, dict):
+ global counter
+ counter = 0 \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/main.cpp
new file mode 100644
index 000000000000..48b29dcfd6e4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-python-synth/main.cpp
@@ -0,0 +1,66 @@
+struct foo
+{
+ int a;
+ int b;
+ int c;
+ int d;
+ int e;
+ int f;
+ int g;
+ int h;
+ int i;
+ int j;
+ int k;
+ int l;
+ int m;
+ int n;
+ int o;
+ int p;
+ int q;
+ int r;
+
+ foo(int X) :
+ a(X),
+ b(X+1),
+ c(X+3),
+ d(X+5),
+ e(X+7),
+ f(X+9),
+ g(X+11),
+ h(X+13),
+ i(X+15),
+ j(X+17),
+ k(X+19),
+ l(X+21),
+ m(X+23),
+ n(X+25),
+ o(X+27),
+ p(X+29),
+ q(X+31),
+ r(X+33) {}
+};
+
+struct wrapint
+{
+ int x;
+ wrapint(int X) : x(X) {}
+};
+
+int main()
+{
+ foo f00_1(0);
+ foo *f00_ptr = new foo(12);
+
+ f00_1.a++; // Set break point at this line.
+
+ wrapint test_cast('A' +
+ 256*'B' +
+ 256*256*'C'+
+ 256*256*256*'D');
+ // Set cast break point at this line.
+ test_cast.x = 'Q' +
+ 256*'X' +
+ 256*256*'T'+
+ 256*256*256*'F';
+ return 0; // Set second cast break point at this line.
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/TestDataFormatterScript.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/TestDataFormatterScript.py
new file mode 100644
index 000000000000..324b372cb11e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/TestDataFormatterScript.py
@@ -0,0 +1,170 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ScriptDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test_with_run_command(self):
+ """Test data formatter commands."""
+ self.build()
+ self.data_formatter_commands()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def data_formatter_commands(self):
+ """Test that that file and class static variables display correctly."""
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ # Set the script here to ease the formatting
+ script = 'a = valobj.GetChildMemberWithName(\'integer\'); a_val = a.GetValue(); str = \'Hello from Python, \' + a_val + \' time\'; return str + (\'!\' if a_val == \'1\' else \'s!\');'
+
+ self.runCmd("type summary add i_am_cool --python-script \"%s\"" % script)
+
+ self.expect("frame variable one",
+ substrs = ['Hello from Python',
+ '1 time!'])
+
+ self.expect("frame variable two",
+ substrs = ['Hello from Python',
+ '4 times!'])
+
+ self.runCmd("n"); # skip ahead to make values change
+
+ self.expect("frame variable three",
+ substrs = ['Hello from Python, 10 times!',
+ 'Hello from Python, 4 times!'])
+
+ self.runCmd("n"); # skip ahead to make values change
+
+ self.expect("frame variable two",
+ substrs = ['Hello from Python',
+ '1 time!'])
+
+ script = 'a = valobj.GetChildMemberWithName(\'integer\'); a_val = a.GetValue(); str = \'int says \' + a_val; return str;'
+
+ # Check that changes in the script are immediately reflected
+ self.runCmd("type summary add i_am_cool --python-script \"%s\"" % script)
+
+ self.expect("frame variable two",
+ substrs = ['int says 1'])
+
+ self.expect("frame variable twoptr",
+ substrs = ['int says 1'])
+
+ # Change the summary
+ self.runCmd("type summary add --summary-string \"int says ${var.integer}, and float says ${var.floating}\" i_am_cool")
+
+ self.expect("frame variable two",
+ substrs = ['int says 1',
+ 'and float says 2.71'])
+ # Try it for pointers
+ self.expect("frame variable twoptr",
+ substrs = ['int says 1',
+ 'and float says 2.71'])
+
+ # Force a failure for pointers
+ self.runCmd("type summary add i_am_cool -p --python-script \"%s\"" % script)
+
+ self.expect("frame variable twoptr", matching=False,
+ substrs = ['and float says 2.71'])
+
+ script = 'return \'Python summary\'';
+
+ self.runCmd("type summary add --name test_summary --python-script \"%s\"" % script)
+
+ # attach the Python named summary to someone
+ self.expect("frame variable one --summary test_summary",
+ substrs = ['Python summary'])
+
+ # should not bind to the type
+ self.expect("frame variable two", matching=False,
+ substrs = ['Python summary'])
+
+ # and should not stick to the variable
+ self.expect("frame variable one",matching=False,
+ substrs = ['Python summary'])
+
+ self.runCmd("type summary add i_am_cool --summary-string \"Text summary\"")
+
+ # should be temporary only
+ self.expect("frame variable one",matching=False,
+ substrs = ['Python summary'])
+
+ # use the type summary
+ self.expect("frame variable two",
+ substrs = ['Text summary'])
+
+ self.runCmd("n"); # skip ahead to make values change
+
+ # both should use the type summary now
+ self.expect("frame variable one",
+ substrs = ['Text summary'])
+
+ self.expect("frame variable two",
+ substrs = ['Text summary'])
+
+ # disable type summary for pointers, and make a Python regex summary
+ self.runCmd("type summary add i_am_cool -p --summary-string \"Text summary\"")
+ self.runCmd("type summary add -x cool --python-script \"%s\"" % script)
+
+ # variables should stick to the type summary
+ self.expect("frame variable one",
+ substrs = ['Text summary'])
+
+ self.expect("frame variable two",
+ substrs = ['Text summary'])
+
+ # array and pointer should match the Python one
+ self.expect("frame variable twoptr",
+ substrs = ['Python summary'])
+
+ self.expect("frame variable array",
+ substrs = ['Python summary'])
+
+ # return pointers to the type summary
+ self.runCmd("type summary add i_am_cool --summary-string \"Text summary\"")
+
+ self.expect("frame variable one",
+ substrs = ['Text summary'])
+
+ self.expect("frame variable two",
+ substrs = ['Text summary'])
+
+ self.expect("frame variable twoptr",
+ substrs = ['Text summary'])
+
+ self.expect("frame variable array",
+ substrs = ['Python summary'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/main.cpp
new file mode 100644
index 000000000000..aaccb6329acf
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-script/main.cpp
@@ -0,0 +1,53 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+
+struct i_am_cool
+{
+ int integer;
+ float floating;
+ char character;
+ i_am_cool(int I, float F, char C) :
+ integer(I), floating(F), character(C) {}
+ i_am_cool() : integer(1), floating(2), character('3') {}
+
+};
+
+struct i_am_cooler
+{
+ i_am_cool first_cool;
+ i_am_cool second_cool;
+ float floating;
+
+ i_am_cooler(int I1, int I2, float F1, float F2, char C1, char C2) :
+ first_cool(I1,F1,C1),
+ second_cool(I2,F2,C2),
+ floating((F1 + F2)/2) {}
+};
+
+int main (int argc, const char * argv[])
+{
+ i_am_cool one(1,3.14,'E');
+ i_am_cool two(4,2.71,'G');
+
+ i_am_cool* twoptr = &two;
+
+ i_am_cool array[5];
+
+ i_am_cooler three(10,4,1985,1/1/2011,'B','E'); // Set break point at this line.
+
+ two.integer = 1;
+
+ int dummy = 1;
+
+ return 0;
+} \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/Makefile
new file mode 100644
index 000000000000..b438bbb970f6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/Makefile
@@ -0,0 +1,19 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+# clang-3.5+ outputs FullDebugInfo by default for Darwin/FreeBSD
+# targets. Other targets do not, which causes this test to fail.
+# This flag enables FullDebugInfo for all targets.
+ifneq (,$(findstring clang,$(CC)))
+ CFLAGS_EXTRAS += -fno-limit-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
+
+CXXFLAGS += -O0
+
+ifeq (,$(findstring gcc,$(CC)))
+CXXFLAGS += -stdlib=libstdc++
+LDFLAGS += -stdlib=libstdc++
+endif
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/TestDataFormatterSkipSummary.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/TestDataFormatterSkipSummary.py
new file mode 100644
index 000000000000..38e700812d05
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/TestDataFormatterSkipSummary.py
@@ -0,0 +1,175 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class SkipSummaryDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureFreeBSD("llvm.org/pr20548") # fails to build on lab.llvm.org buildbot
+ @expectedFailureWindows("llvm.org/pr24462") # Data formatters have problems on Windows
+ def test_with_run_command(self):
+ """Test data formatter commands."""
+ self.build()
+ self.data_formatter_commands()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def data_formatter_commands(self):
+ """Test that that file and class static variables display correctly."""
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ #import lldbsuite.test.lldbutil as lldbutil
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ # Setup the summaries for this scenario
+ #self.runCmd("type summary add --summary-string \"${var._M_dataplus._M_p}\" std::string")
+ self.runCmd("type summary add --summary-string \"Level 1\" \"DeepData_1\"")
+ self.runCmd("type summary add --summary-string \"Level 2\" \"DeepData_2\" -e")
+ self.runCmd("type summary add --summary-string \"Level 3\" \"DeepData_3\"")
+ self.runCmd("type summary add --summary-string \"Level 4\" \"DeepData_4\"")
+ self.runCmd("type summary add --summary-string \"Level 5\" \"DeepData_5\"")
+
+ # Default case, just print out summaries
+ self.expect('frame variable',
+ substrs = ['(DeepData_1) data1 = Level 1',
+ '(DeepData_2) data2 = Level 2 {',
+ 'm_child1 = Level 3',
+ 'm_child2 = Level 3',
+ 'm_child3 = Level 3',
+ 'm_child4 = Level 3',
+ '}'])
+
+ # Skip the default (should be 1) levels of summaries
+ self.expect('frame variable --no-summary-depth',
+ substrs = ['(DeepData_1) data1 = {',
+ 'm_child1 = 0x',
+ '}',
+ '(DeepData_2) data2 = {',
+ 'm_child1 = Level 3',
+ 'm_child2 = Level 3',
+ 'm_child3 = Level 3',
+ 'm_child4 = Level 3',
+ '}'])
+
+ # Now skip 2 levels of summaries
+ self.expect('frame variable --no-summary-depth=2',
+ substrs = ['(DeepData_1) data1 = {',
+ 'm_child1 = 0x',
+ '}',
+ '(DeepData_2) data2 = {',
+ 'm_child1 = {',
+ 'm_child1 = 0x',
+ 'Level 4',
+ 'm_child2 = {',
+ 'm_child3 = {',
+ '}'])
+
+ # Check that no "Level 3" comes out
+ self.expect('frame variable data1.m_child1 --no-summary-depth=2', matching=False,
+ substrs = ['Level 3'])
+
+ # Now expand a pointer with 2 level of skipped summaries
+ self.expect('frame variable data1.m_child1 --no-summary-depth=2',
+ substrs = ['(DeepData_2 *) data1.m_child1 = 0x'])
+
+ # Deref and expand said pointer
+ self.expect('frame variable *data1.m_child1 --no-summary-depth=2',
+ substrs = ['(DeepData_2) *data1.m_child1 = {',
+ 'm_child2 = {',
+ 'm_child1 = 0x',
+ 'Level 4',
+ '}'])
+
+ # Expand an expression, skipping 2 layers of summaries
+ self.expect('frame variable data1.m_child1->m_child2 --no-summary-depth=2',
+ substrs = ['(DeepData_3) data1.m_child1->m_child2 = {',
+ 'm_child2 = {',
+ 'm_child1 = Level 5',
+ 'm_child2 = Level 5',
+ 'm_child3 = Level 5',
+ '}'])
+
+ # Expand same expression, skipping only 1 layer of summaries
+ self.expect('frame variable data1.m_child1->m_child2 --no-summary-depth=1',
+ substrs = ['(DeepData_3) data1.m_child1->m_child2 = {',
+ 'm_child1 = 0x',
+ 'Level 4',
+ 'm_child2 = Level 4',
+ '}'])
+
+ # Bad debugging info on SnowLeopard gcc (Apple Inc. build 5666).
+ # Skip the following tests if the condition is met.
+ if self.getCompiler().endswith('gcc') and not self.getCompiler().endswith('llvm-gcc'):
+ import re
+ gcc_version_output = system([[lldbutil.which(self.getCompiler()), "-v"]])[1]
+ #print("my output:", gcc_version_output)
+ for line in gcc_version_output.split(os.linesep):
+ m = re.search('\(Apple Inc\. build ([0-9]+)\)', line)
+ #print("line:", line)
+ if m:
+ gcc_build = int(m.group(1))
+ #print("gcc build:", gcc_build)
+ if gcc_build >= 5666:
+ # rdar://problem/9804600"
+ self.skipTest("rdar://problem/9804600 wrong namespace for std::string in debug info")
+
+ # Expand same expression, skipping 3 layers of summaries
+ self.expect('frame variable data1.m_child1->m_child2 --show-types --no-summary-depth=3',
+ substrs = ['(DeepData_3) data1.m_child1->m_child2 = {',
+ 'm_some_text = "Just a test"',
+ 'm_child2 = {',
+ 'm_some_text = "Just a test"'])
+
+ # Expand within a standard string (might depend on the implementation of the C++ stdlib you use)
+ self.expect('frame variable data1.m_child1->m_child2.m_child1.m_child2 --no-summary-depth=2',
+ substrs = ['(DeepData_5) data1.m_child1->m_child2.m_child1.m_child2 = {',
+ 'm_some_text = {',
+ '_M_dataplus = (_M_p = "Just a test")'])
+
+ # Repeat the above, but only skip 1 level of summaries
+ self.expect('frame variable data1.m_child1->m_child2.m_child1.m_child2 --no-summary-depth=1',
+ substrs = ['(DeepData_5) data1.m_child1->m_child2.m_child1.m_child2 = {',
+ 'm_some_text = "Just a test"',
+ '}'])
+
+ # Change summary and expand, first without --no-summary-depth then with --no-summary-depth
+ self.runCmd("type summary add --summary-string \"${var.m_some_text}\" DeepData_5")
+
+ self.expect('fr var data2.m_child4.m_child2.m_child2',
+ substrs = ['(DeepData_5) data2.m_child4.m_child2.m_child2 = "Just a test"'])
+
+ self.expect('fr var data2.m_child4.m_child2.m_child2 --no-summary-depth',
+ substrs = ['(DeepData_5) data2.m_child4.m_child2.m_child2 = {',
+ 'm_some_text = "Just a test"',
+ '}'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/main.cpp
new file mode 100644
index 000000000000..82ffb2c20d47
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-skip-summary/main.cpp
@@ -0,0 +1,57 @@
+#include <string>
+
+struct DeepData_5
+{
+ std::string m_some_text;
+ DeepData_5() :
+ m_some_text("Just a test") {}
+};
+
+struct DeepData_4
+{
+ DeepData_5 m_child1;
+ DeepData_5 m_child2;
+ DeepData_5 m_child3;
+};
+
+struct DeepData_3
+{
+ DeepData_4& m_child1;
+ DeepData_4 m_child2;
+
+ DeepData_3() : m_child1(* (new DeepData_4())), m_child2(DeepData_4()) {}
+};
+
+struct DeepData_2
+{
+ DeepData_3 m_child1;
+ DeepData_3 m_child2;
+ DeepData_3 m_child3;
+ DeepData_3 m_child4;
+};
+
+struct DeepData_1
+{
+ DeepData_2 *m_child1;
+
+ DeepData_1() :
+ m_child1(new DeepData_2())
+ {}
+};
+
+/*
+ type summary add -f "${var._M_dataplus._M_p}" std::string
+ type summary add -f "Level 1" "DeepData_1"
+ type summary add -f "Level 2" "DeepData_2" -e
+ type summary add -f "Level 3" "DeepData_3"
+ type summary add -f "Level 4" "DeepData_4"
+ type summary add -f "Level 5" "DeepData_5"
+ */
+
+int main()
+{
+ DeepData_1 data1;
+ DeepData_2 data2;
+
+ return 0; // Set break point at this line.
+} \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/TestDataFormatterSmartArray.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/TestDataFormatterSmartArray.py
new file mode 100644
index 000000000000..ca8858dbad9b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/TestDataFormatterSmartArray.py
@@ -0,0 +1,348 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class SmartArrayDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureWindows("llvm.org/pr24462") # Data formatters have problems on Windows
+ def test_with_run_command(self):
+ """Test data formatter commands."""
+ self.build()
+ self.data_formatter_commands()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def data_formatter_commands(self):
+ """Test that that file and class static variables display correctly."""
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+# check that we are not looping here
+ self.runCmd("type summary add --summary-string \"${var%V}\" SomeData")
+
+ self.expect("frame variable data",
+ substrs = ['SomeData @ 0x'])
+# ${var%s}
+ self.runCmd("type summary add --summary-string \"ptr = ${var%s}\" \"char *\"")
+
+ self.expect("frame variable strptr",
+ substrs = ['ptr = \"',
+ 'Hello world!'])
+
+ self.expect("frame variable other.strptr",
+ substrs = ['ptr = \"',
+ 'Nested Hello world!'])
+
+ self.runCmd("type summary add --summary-string \"arr = ${var%s}\" -x \"char \\[[0-9]+\\]\"")
+
+ self.expect("frame variable strarr",
+ substrs = ['arr = \"',
+ 'Hello world!'])
+
+ self.expect("frame variable other.strarr",
+ substrs = ['arr = \"',
+ 'Nested Hello world!'])
+
+ self.expect("p strarr",
+ substrs = ['arr = \"',
+ 'Hello world!'])
+
+ self.expect("p other.strarr",
+ substrs = ['arr = \"',
+ 'Nested Hello world!'])
+
+# ${var%c}
+ self.runCmd("type summary add --summary-string \"ptr = ${var%c}\" \"char *\"")
+
+ self.expect("frame variable strptr",
+ substrs = ['ptr = \"',
+ 'Hello world!'])
+
+ self.expect("frame variable other.strptr",
+ substrs = ['ptr = \"',
+ 'Nested Hello world!'])
+
+ self.expect("p strptr",
+ substrs = ['ptr = \"',
+ 'Hello world!'])
+
+ self.expect("p other.strptr",
+ substrs = ['ptr = \"',
+ 'Nested Hello world!'])
+
+ self.runCmd("type summary add --summary-string \"arr = ${var%c}\" -x \"char \\[[0-9]+\\]\"")
+
+ self.expect("frame variable strarr",
+ substrs = ['arr = \"',
+ 'Hello world!'])
+
+ self.expect("frame variable other.strarr",
+ substrs = ['arr = \"',
+ 'Nested Hello world!'])
+
+ self.expect("p strarr",
+ substrs = ['arr = \"',
+ 'Hello world!'])
+
+ self.expect("p other.strarr",
+ substrs = ['arr = \"',
+ 'Nested Hello world!'])
+
+# ${var%char[]}
+ self.runCmd("type summary add --summary-string \"arr = ${var%char[]}\" -x \"char \\[[0-9]+\\]\"")
+
+ self.expect("frame variable strarr",
+ substrs = ['arr = \"',
+ 'Hello world!'])
+
+ self.expect("frame variable other.strarr",
+ substrs = ['arr = ',
+ 'Nested Hello world!'])
+
+ self.expect("p strarr",
+ substrs = ['arr = \"',
+ 'Hello world!'])
+
+ self.expect("p other.strarr",
+ substrs = ['arr = ',
+ 'Nested Hello world!'])
+
+ self.runCmd("type summary add --summary-string \"ptr = ${var%char[]}\" \"char *\"")
+
+ self.expect("frame variable strptr",
+ substrs = ['ptr = \"',
+ 'Hello world!'])
+
+ self.expect("frame variable other.strptr",
+ substrs = ['ptr = \"',
+ 'Nested Hello world!'])
+
+ self.expect("p strptr",
+ substrs = ['ptr = \"',
+ 'Hello world!'])
+
+ self.expect("p other.strptr",
+ substrs = ['ptr = \"',
+ 'Nested Hello world!'])
+
+# ${var%a}
+ self.runCmd("type summary add --summary-string \"arr = ${var%a}\" -x \"char \\[[0-9]+\\]\"")
+
+ self.expect("frame variable strarr",
+ substrs = ['arr = \"',
+ 'Hello world!'])
+
+ self.expect("frame variable other.strarr",
+ substrs = ['arr = ',
+ 'Nested Hello world!'])
+
+ self.expect("p strarr",
+ substrs = ['arr = \"',
+ 'Hello world!'])
+
+ self.expect("p other.strarr",
+ substrs = ['arr = ',
+ 'Nested Hello world!'])
+
+ self.runCmd("type summary add --summary-string \"ptr = ${var%a}\" \"char *\"")
+
+ self.expect("frame variable strptr",
+ substrs = ['ptr = \"',
+ 'Hello world!'])
+
+ self.expect("frame variable other.strptr",
+ substrs = ['ptr = \"',
+ 'Nested Hello world!'])
+
+ self.expect("p strptr",
+ substrs = ['ptr = \"',
+ 'Hello world!'])
+
+ self.expect("p other.strptr",
+ substrs = ['ptr = \"',
+ 'Nested Hello world!'])
+
+ self.runCmd("type summary add --summary-string \"ptr = ${var[]%char[]}\" \"char *\"")
+
+# I do not know the size of the data, but you are asking for a full array slice..
+# use the ${var%char[]} to obtain a string as result
+ self.expect("frame variable strptr", matching=False,
+ substrs = ['ptr = \"',
+ 'Hello world!'])
+
+ self.expect("frame variable other.strptr", matching=False,
+ substrs = ['ptr = \"',
+ 'Nested Hello world!'])
+
+ self.expect("p strptr", matching=False,
+ substrs = ['ptr = \"',
+ 'Hello world!'])
+
+ self.expect("p other.strptr", matching=False,
+ substrs = ['ptr = \"',
+ 'Nested Hello world!'])
+
+# You asked an array-style printout...
+ self.runCmd("type summary add --summary-string \"ptr = ${var[0-1]%char[]}\" \"char *\"")
+
+ self.expect("frame variable strptr",
+ substrs = ['ptr = ',
+ '[{H},{e}]'])
+
+ self.expect("frame variable other.strptr",
+ substrs = ['ptr = ',
+ '[{N},{e}]'])
+
+ self.expect("p strptr",
+ substrs = ['ptr = ',
+ '[{H},{e}]'])
+
+ self.expect("p other.strptr",
+ substrs = ['ptr = ',
+ '[{N},{e}]'])
+
+# using [] is required here
+ self.runCmd("type summary add --summary-string \"arr = ${var%x}\" \"int [5]\"")
+
+ self.expect("frame variable intarr",matching=False,
+ substrs = ['0x00000001,0x00000001,0x00000002,0x00000003,0x00000005'])
+
+ self.expect("frame variable other.intarr", matching=False,
+ substrs = ['0x00000009,0x00000008,0x00000007,0x00000006,0x00000005'])
+
+ self.runCmd("type summary add --summary-string \"arr = ${var[]%x}\" \"int [5]\"")
+
+ self.expect("frame variable intarr",
+ substrs = ['intarr = arr =',
+ '0x00000001,0x00000001,0x00000002,0x00000003,0x00000005'])
+
+ self.expect("frame variable other.intarr",
+ substrs = ['intarr = arr =',
+ '0x00000009,0x00000008,0x00000007,0x00000006,0x00000005'])
+
+# printing each array item as an array
+ self.runCmd("type summary add --summary-string \"arr = ${var[]%uint32_t[]}\" \"int [5]\"")
+
+ self.expect("frame variable intarr",
+ substrs = ['intarr = arr =',
+ '{0x00000001},{0x00000001},{0x00000002},{0x00000003},{0x00000005}'])
+
+ self.expect("frame variable other.intarr",
+ substrs = ['intarr = arr = ',
+ '{0x00000009},{0x00000008},{0x00000007},{0x00000006},{0x00000005}'])
+
+# printing full array as an array
+ self.runCmd("type summary add --summary-string \"arr = ${var%uint32_t[]}\" \"int [5]\"")
+
+ self.expect("frame variable intarr",
+ substrs = ['intarr = arr =',
+ '0x00000001,0x00000001,0x00000002,0x00000003,0x00000005'])
+
+ self.expect("frame variable other.intarr",
+ substrs = ['intarr = arr =',
+ '0x00000009,0x00000008,0x00000007,0x00000006,0x00000005'])
+
+# printing each array item as an array
+ self.runCmd("type summary add --summary-string \"arr = ${var[]%float32[]}\" \"float [7]\"")
+
+ self.expect("frame variable flarr",
+ substrs = ['flarr = arr =',
+ '{78.5},{77.25},{78},{76.125},{76.75},{76.875},{77}'])
+
+ self.expect("frame variable other.flarr",
+ substrs = ['flarr = arr = ',
+ '{25.5},{25.25},{25.125},{26.75},{27.375},{27.5},{26.125}'])
+
+# printing full array as an array
+ self.runCmd("type summary add --summary-string \"arr = ${var%float32[]}\" \"float [7]\"")
+
+ self.expect("frame variable flarr",
+ substrs = ['flarr = arr =',
+ '78.5,77.25,78,76.125,76.75,76.875,77'])
+
+ self.expect("frame variable other.flarr",
+ substrs = ['flarr = arr =',
+ '25.5,25.25,25.125,26.75,27.375,27.5,26.125'])
+
+# using array smart summary strings for pointers should make no sense
+ self.runCmd("type summary add --summary-string \"arr = ${var%float32[]}\" \"float *\"")
+ self.runCmd("type summary add --summary-string \"arr = ${var%int32_t[]}\" \"int *\"")
+
+ self.expect("frame variable flptr", matching=False,
+ substrs = ['78.5,77.25,78,76.125,76.75,76.875,77'])
+
+ self.expect("frame variable intptr", matching=False,
+ substrs = ['1,1,2,3,5'])
+
+# use y and Y
+ self.runCmd("type summary add --summary-string \"arr = ${var%y}\" \"float [7]\"")
+ self.runCmd("type summary add --summary-string \"arr = ${var%y}\" \"int [5]\"")
+
+ self.expect("frame variable flarr",
+ substrs = ['flarr = arr =',
+ '00 00 9d 42,00 80 9a 42,00 00 9c 42,00 40 98 42,00 80 99 42,00 c0 99 42,00 00 9a 42'])
+
+ self.expect("frame variable other.flarr",
+ substrs = ['flarr = arr =',
+ '00 00 cc 41,00 00 ca 41,00 00 c9 41,00 00 d6 41,00 00 db 41,00 00 dc 41,00 00 d1 41'])
+
+ self.expect("frame variable intarr",
+ substrs = ['intarr = arr =',
+ '01 00 00 00,01 00 00 00,02 00 00 00,03 00 00 00,05 00 00 00'])
+
+ self.expect("frame variable other.intarr",
+ substrs = ['intarr = arr = ',
+ '09 00 00 00,08 00 00 00,07 00 00 00,06 00 00 00,05 00 00 00'])
+
+ self.runCmd("type summary add --summary-string \"arr = ${var%Y}\" \"float [7]\"")
+ self.runCmd("type summary add --summary-string \"arr = ${var%Y}\" \"int [5]\"")
+
+ self.expect("frame variable flarr",
+ substrs = ['flarr = arr =',
+ '00 00 9d 42 ...B,00 80 9a 42 ...B,00 00 9c 42 ...B,00 40 98 42 .@.B,00 80 99 42 ...B,00 c0 99 42 ...B,00 00 9a 42 ...B'])
+
+ self.expect("frame variable other.flarr",
+ substrs = ['flarr = arr =',
+ '00 00 cc 41 ...A,00 00 ca 41 ...A,00 00 c9 41 ...A,00 00 d6 41 ...A,00 00 db 41 ...A,00 00 dc 41 ...A,00 00 d1 41 ...A'])
+
+ self.expect("frame variable intarr",
+ substrs = ['intarr = arr =',
+ '....,01 00 00 00',
+ '....,05 00 00 00'])
+
+ self.expect("frame variable other.intarr",
+ substrs = ['intarr = arr = ',
+ '09 00 00 00',
+ '....,07 00 00 00'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/main.cpp
new file mode 100644
index 000000000000..9279e414be31
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-smart-array/main.cpp
@@ -0,0 +1,65 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <string.h>
+
+struct SomeData
+{
+ int x;
+};
+
+struct SomeOtherData
+{
+ char strarr[32];
+ char *strptr;
+ int intarr[5];
+ float flarr[7];
+
+ SomeOtherData()
+ {
+ strcpy(strarr,"Nested Hello world!");
+ strptr = new char[128];
+ strcpy(strptr,"Nested Hello world!");
+ intarr[0] = 9;
+ intarr[1] = 8;
+ intarr[2] = 7;
+ intarr[3] = 6;
+ intarr[4] = 5;
+
+ flarr[0] = 25.5;
+ flarr[1] = 25.25;
+ flarr[2] = 25.125;
+ flarr[3] = 26.75;
+ flarr[4] = 27.375;
+ flarr[5] = 27.5;
+ flarr[6] = 26.125;
+ }
+};
+
+int main (int argc, const char * argv[])
+{
+ char strarr[32] = "Hello world!";
+ char *strptr = NULL;
+ strptr = "Hello world!";
+ int intarr[5] = {1,1,2,3,5};
+ float flarr[7] = {78.5,77.25,78.0,76.125,76.75,76.875,77.0};
+
+ SomeData data;
+
+ SomeOtherData other;
+
+ float* flptr = flarr;
+ int* intptr = intarr;
+
+ return 0; // Set break point at this line.
+
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/Makefile
new file mode 100644
index 000000000000..d37bef7dc5cc
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/Makefile
@@ -0,0 +1,4 @@
+LEVEL = ../../../../../make
+CXX_SOURCES := main.cpp
+CXXFLAGS += -std=c++11
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/TestInitializerList.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/TestInitializerList.py
new file mode 100644
index 000000000000..e01f1b6679fc
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/TestInitializerList.py
@@ -0,0 +1,40 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class InitializerListTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfWindows # libc++ not ported to Windows yet
+ @skipIfGcc
+ @expectedFailureLinux # fails on clang 3.5 and tot
+ def test(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ bkpt = self.target().FindBreakpointByID(lldbutil.run_break_set_by_source_regexp (self, "Set break point at this line."))
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+"))
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ self.expect("frame variable ili", substrs = ['[1] = 2','[4] = 5'])
+ self.expect("frame variable ils", substrs = ['[4] = "surprise it is a long string!! yay!!"'])
+
+ self.expect('image list', substrs = self.getLibcPlusPlusLibs())
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/main.cpp
new file mode 100644
index 000000000000..9109a20cb510
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/initializerlist/main.cpp
@@ -0,0 +1,21 @@
+//===-- main.cpp --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <string>
+#include <vector>
+#include <initializer_list>
+
+int main ()
+{
+ std::initializer_list<int> ili{1,2,3,4,5};
+ std::initializer_list<std::string> ils{"1","2","3","4","surprise it is a long string!! yay!!"};
+
+ return 0; // Set break point at this line.
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/Makefile
new file mode 100644
index 000000000000..1f609a41d908
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../../../make
+
+CXX_SOURCES := main.cpp
+
+USE_LIBCPP := 1
+include $(LEVEL)/Makefile.rules
+CXXFLAGS += -O0
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/TestDataFormatterLibccIterator.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/TestDataFormatterLibccIterator.py
new file mode 100644
index 000000000000..a87a2ed2d434
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/TestDataFormatterLibccIterator.py
@@ -0,0 +1,66 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class LibcxxIteratorDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ @skipIfGcc
+ @skipIfWindows # libc++ not ported to Windows yet
+ def test_with_run_command(self):
+ """Test that libc++ iterators format properly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+"))
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.expect('image list', substrs = self.getLibcPlusPlusLibs())
+
+ self.expect('frame variable ivI', substrs = ['item = 3'])
+ self.expect('expr ivI', substrs = ['item = 3'])
+
+ self.expect('frame variable iimI', substrs = ['first = 0','second = 12'])
+ self.expect('expr iimI', substrs = ['first = 0','second = 12'])
+
+ self.expect('frame variable simI', substrs = ['first = "world"','second = 42'])
+ self.expect('expr simI', substrs = ['first = "world"','second = 42'])
+
+ self.expect('frame variable svI', substrs = ['item = "hello"'])
+ self.expect('expr svI', substrs = ['item = "hello"'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/main.cpp
new file mode 100644
index 000000000000..97b37851f53d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/iterator/main.cpp
@@ -0,0 +1,42 @@
+#include <string>
+#ifdef _LIBCPP_INLINE_VISIBILITY
+#undef _LIBCPP_INLINE_VISIBILITY
+#endif
+#define _LIBCPP_INLINE_VISIBILITY
+#include <map>
+#include <vector>
+
+typedef std::map<int, int> intint_map;
+typedef std::map<std::string, int> strint_map;
+
+typedef std::vector<int> int_vector;
+typedef std::vector<std::string> string_vector;
+
+typedef intint_map::iterator iimter;
+typedef strint_map::iterator simter;
+
+typedef int_vector::iterator ivter;
+typedef string_vector::iterator svter;
+
+int main()
+{
+ intint_map iim;
+ iim[0] = 12;
+
+ strint_map sim;
+ sim["world"] = 42;
+
+ int_vector iv;
+ iv.push_back(3);
+
+ string_vector sv;
+ sv.push_back("hello");
+
+ iimter iimI = iim.begin();
+ simter simI = sim.begin();
+
+ ivter ivI = iv.begin();
+ svter svI = sv.begin();
+
+ return 0; // Set break point at this line.
+} \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/Makefile
new file mode 100644
index 000000000000..1f609a41d908
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../../../make
+
+CXX_SOURCES := main.cpp
+
+USE_LIBCPP := 1
+include $(LEVEL)/Makefile.rules
+CXXFLAGS += -O0
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/TestDataFormatterLibcxxList.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/TestDataFormatterLibcxxList.py
new file mode 100644
index 000000000000..18ee31a86106
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/TestDataFormatterLibcxxList.py
@@ -0,0 +1,186 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time, re
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class LibcxxListDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+ self.line2 = line_number('main.cpp', '// Set second break point at this line.')
+ self.line3 = line_number('main.cpp', '// Set third break point at this line.')
+ self.line4 = line_number('main.cpp', '// Set fourth break point at this line.')
+
+ @skipIfGcc
+ @skipIfWindows # libc++ not ported to Windows yet
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1)
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line2, num_expected_locations=-1)
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line3, num_expected_locations=-1)
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line4, num_expected_locations=-1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+"))
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.runCmd("frame variable numbers_list --show-types")
+ self.runCmd("type summary add std::int_list std::string_list int_list string_list --summary-string \"list has ${svar%#} items\" -e")
+ self.runCmd("type format add -f hex int")
+
+ self.expect("frame variable numbers_list --raw", matching=False,
+ substrs = ['list has 0 items',
+ '{}'])
+
+ self.expect("frame variable numbers_list",
+ substrs = ['list has 0 items',
+ '{}'])
+
+ self.expect("p numbers_list",
+ substrs = ['list has 0 items',
+ '{}'])
+
+ self.runCmd("n")
+
+ self.expect("frame variable numbers_list",
+ substrs = ['list has 1 items',
+ '[0] = ',
+ '0x12345678'])
+
+ self.runCmd("n");self.runCmd("n");self.runCmd("n");
+
+ self.expect("frame variable numbers_list",
+ substrs = ['list has 4 items',
+ '[0] = ',
+ '0x12345678',
+ '[1] =',
+ '0x11223344',
+ '[2] =',
+ '0xbeeffeed',
+ '[3] =',
+ '0x00abba00'])
+
+ self.runCmd("n");self.runCmd("n");
+
+ self.expect("frame variable numbers_list",
+ substrs = ['list has 6 items',
+ '[0] = ',
+ '0x12345678',
+ '0x11223344',
+ '0xbeeffeed',
+ '0x00abba00',
+ '[4] =',
+ '0x0abcdef0',
+ '[5] =',
+ '0x0cab0cab'])
+
+ self.expect("p numbers_list",
+ substrs = ['list has 6 items',
+ '[0] = ',
+ '0x12345678',
+ '0x11223344',
+ '0xbeeffeed',
+ '0x00abba00',
+ '[4] =',
+ '0x0abcdef0',
+ '[5] =',
+ '0x0cab0cab'])
+
+ # check access-by-index
+ self.expect("frame variable numbers_list[0]",
+ substrs = ['0x12345678']);
+ self.expect("frame variable numbers_list[1]",
+ substrs = ['0x11223344']);
+
+ self.runCmd("n")
+
+ self.expect("frame variable numbers_list",
+ substrs = ['list has 0 items',
+ '{}'])
+
+ self.runCmd("n");self.runCmd("n");self.runCmd("n");self.runCmd("n");
+
+ self.expect("frame variable numbers_list",
+ substrs = ['list has 4 items',
+ '[0] = ', '1',
+ '[1] = ', '2',
+ '[2] = ', '3',
+ '[3] = ', '4'])
+
+ # check that MightHaveChildren() gets it right
+ self.assertTrue(self.frame().FindVariable("numbers_list").MightHaveChildren(), "numbers_list.MightHaveChildren() says False for non empty!")
+
+ self.runCmd("type format delete int")
+
+ self.runCmd("c")
+
+ self.expect("frame variable text_list",
+ substrs = ['list has 3 items',
+ '[0]', 'goofy',
+ '[1]', 'is',
+ '[2]', 'smart'])
+
+ # check that MightHaveChildren() gets it right
+ self.assertTrue(self.frame().FindVariable("text_list").MightHaveChildren(), "text_list.MightHaveChildren() says False for non empty!")
+
+ self.expect("p text_list",
+ substrs = ['list has 3 items',
+ '\"goofy\"',
+ '\"is\"',
+ '\"smart\"'])
+
+ self.runCmd("n")
+
+ # check access-by-index
+ self.expect("frame variable text_list[0]",
+ substrs = ['goofy']);
+ self.expect("frame variable text_list[3]",
+ substrs = ['!!!']);
+
+ self.runCmd("continue")
+
+ # check that the list provider correctly updates if elements move
+ countingList = self.frame().FindVariable("countingList")
+ countingList.SetPreferDynamicValue(True)
+ countingList.SetPreferSyntheticValue(True)
+
+ self.assertTrue(countingList.GetChildAtIndex(0).GetValueAsUnsigned(0) == 3141, "list[0] == 3141")
+ self.assertTrue(countingList.GetChildAtIndex(1).GetValueAsUnsigned(0) == 3141, "list[1] == 3141")
+
+ self.runCmd("continue")
+
+ self.assertTrue(countingList.GetChildAtIndex(0).GetValueAsUnsigned(0) == 3141, "uniqued list[0] == 3141")
+ self.assertTrue(countingList.GetChildAtIndex(1).GetValueAsUnsigned(0) == 3142, "uniqued list[1] == 3142")
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/Makefile
new file mode 100644
index 000000000000..a5dabdb6349d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../../../../make
+
+CXX_SOURCES := main.cpp
+
+USE_LIBCPP := 1
+include $(LEVEL)/Makefile.rules
+CXXFLAGS += -O0
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/TestDataFormatterLibcxxListLoop.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/TestDataFormatterLibcxxListLoop.py
new file mode 100644
index 000000000000..167cb2b887af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/TestDataFormatterLibcxxListLoop.py
@@ -0,0 +1,54 @@
+"""
+Test that the debugger handles loops in std::list (which can appear as a result of e.g. memory
+corruption).
+"""
+
+from __future__ import print_function
+
+
+
+import os, time, re
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class LibcxxListDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfGcc
+ @skipIfWindows # libc++ not ported to Windows yet
+ @add_test_categories(["pyapi"])
+ def test_with_run_command(self):
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target and target.IsValid(), "Target is valid")
+
+ file_spec = lldb.SBFileSpec ("main.cpp", False)
+ breakpoint1 = target.BreakpointCreateBySourceRegex('// Set break point at this line.', file_spec)
+ self.assertTrue(breakpoint1 and breakpoint1.IsValid())
+ breakpoint2 = target.BreakpointCreateBySourceRegex('// Set second break point at this line.', file_spec)
+ self.assertTrue(breakpoint2 and breakpoint2.IsValid())
+
+ # Run the program, it should stop at breakpoint 1.
+ process = target.LaunchSimple(None, None, self.get_process_working_directory())
+ lldbutil.skip_if_library_missing(self, target, lldbutil.PrintableRegex("libc\+\+"))
+ self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID)
+ self.assertEqual(len(lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint1)), 1)
+
+ # verify our list is displayed correctly
+ self.expect("frame variable *numbers_list", substrs=['[0] = 1', '[1] = 2', '[2] = 3', '[3] = 4', '[5] = 6'])
+
+ # Continue to breakpoint 2.
+ process.Continue()
+ self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID)
+ self.assertEqual(len(lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint2)), 1)
+
+ # The list is now inconsistent. However, we should be able to get the first three
+ # elements at least (and most importantly, not crash).
+ self.expect("frame variable *numbers_list", substrs=['[0] = 1', '[1] = 2', '[2] = 3'])
+
+ # Run to completion.
+ process.Continue()
+ self.assertEqual(process.GetState(), lldb.eStateExited, PROCESS_EXITED)
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/main.cpp
new file mode 100644
index 000000000000..6a1266528d5e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/loop/main.cpp
@@ -0,0 +1,30 @@
+// Evil hack: To simulate memory corruption, we want to fiddle with some internals of std::list.
+// Make those accessible to us.
+#define private public
+#define protected public
+
+#ifdef _LIBCPP_INLINE_VISIBILITY
+#undef _LIBCPP_INLINE_VISIBILITY
+#endif
+#define _LIBCPP_INLINE_VISIBILITY
+#include <list>
+
+#include <assert.h>
+
+typedef std::list<int> int_list;
+
+int main()
+{
+#ifdef LLDB_USING_LIBCPP
+ int_list *numbers_list = new int_list{1,2,3,4,5,6,7,8,9,10};
+
+ auto *third_elem = numbers_list->__end_.__next_->__next_->__next_; // Set break point at this line.
+ assert(third_elem->__value_ == 3);
+ auto *fifth_elem = third_elem->__next_->__next_;
+ assert(fifth_elem->__value_ == 5);
+ fifth_elem->__next_ = third_elem;
+#endif
+
+ // Any attempt to free the list will probably crash the program. Let's just leak it.
+ return 0; // Set second break point at this line.
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/main.cpp
new file mode 100644
index 000000000000..4f2bd74495a9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/list/main.cpp
@@ -0,0 +1,43 @@
+#include <string>
+#ifdef _LIBCPP_INLINE_VISIBILITY
+#undef _LIBCPP_INLINE_VISIBILITY
+#endif
+#define _LIBCPP_INLINE_VISIBILITY
+#include <list>
+
+
+typedef std::list<int> int_list;
+typedef std::list<std::string> string_list;
+
+int main()
+{
+ int_list numbers_list;
+
+ (numbers_list.push_back(0x12345678)); // Set break point at this line.
+ (numbers_list.push_back(0x11223344));
+ (numbers_list.push_back(0xBEEFFEED));
+ (numbers_list.push_back(0x00ABBA00));
+ (numbers_list.push_back(0x0ABCDEF0));
+ (numbers_list.push_back(0x0CAB0CAB));
+
+ numbers_list.clear();
+
+ (numbers_list.push_back(1));
+ (numbers_list.push_back(2));
+ (numbers_list.push_back(3));
+ (numbers_list.push_back(4));
+
+ string_list text_list;
+ (text_list.push_back(std::string("goofy")));
+ (text_list.push_back(std::string("is")));
+ (text_list.push_back(std::string("smart")));
+
+ (text_list.push_back(std::string("!!!"))); // Set second break point at this line.
+
+ std::list<int> countingList = {3141, 3142, 3142,3142,3142, 3142, 3142, 3141};
+ countingList.sort();
+ countingList.unique(); // Set third break point at this line.
+ countingList.size(); // Set fourth break point at this line.
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/Makefile
new file mode 100644
index 000000000000..1f609a41d908
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../../../make
+
+CXX_SOURCES := main.cpp
+
+USE_LIBCPP := 1
+include $(LEVEL)/Makefile.rules
+CXXFLAGS += -O0
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/TestDataFormatterLibccMap.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/TestDataFormatterLibccMap.py
new file mode 100644
index 000000000000..70a98f9c2cae
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/TestDataFormatterLibccMap.py
@@ -0,0 +1,298 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class LibcxxMapDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfGcc
+ @skipIfWindows # libc++ not ported to Windows yet
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ bkpt = self.target().FindBreakpointByID(lldbutil.run_break_set_by_source_regexp (self, "Set break point at this line."))
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+"))
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.expect('image list', substrs = self.getLibcPlusPlusLibs())
+
+ self.expect('frame variable ii',
+ substrs = ['size=0',
+ '{}'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect('frame variable ii',
+ substrs = ['size=2',
+ '[0] = ',
+ 'first = 0',
+ 'second = 0',
+ '[1] = ',
+ 'first = 1',
+ 'second = 1'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect('frame variable ii',
+ substrs = ['size=4',
+ '[2] = ',
+ 'first = 2',
+ 'second = 0',
+ '[3] = ',
+ 'first = 3',
+ 'second = 1'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect("frame variable ii",
+ substrs = ['size=8',
+ '[5] = ',
+ 'first = 5',
+ 'second = 0',
+ '[7] = ',
+ 'first = 7',
+ 'second = 1'])
+
+ self.expect("p ii",
+ substrs = ['size=8',
+ '[5] = ',
+ 'first = 5',
+ 'second = 0',
+ '[7] = ',
+ 'first = 7',
+ 'second = 1'])
+
+ # check access-by-index
+ self.expect("frame variable ii[0]",
+ substrs = ['first = 0',
+ 'second = 0']);
+ self.expect("frame variable ii[3]",
+ substrs = ['first =',
+ 'second =']);
+
+ # check that MightHaveChildren() gets it right
+ self.assertTrue(self.frame().FindVariable("ii").MightHaveChildren(), "ii.MightHaveChildren() says False for non empty!")
+
+ # check that the expression parser does not make use of
+ # synthetic children instead of running code
+ # TOT clang has a fix for this, which makes the expression command here succeed
+ # since this would make the test fail or succeed depending on clang version in use
+ # this is safer commented for the time being
+ #self.expect("expression ii[8]", matching=False, error=True,
+ # substrs = ['1234567'])
+
+ self.runCmd("continue");
+
+ self.expect('frame variable ii',
+ substrs = ['size=0',
+ '{}'])
+
+ self.expect('frame variable si',
+ substrs = ['size=0',
+ '{}'])
+
+ self.runCmd("continue");
+
+ self.expect('frame variable si',
+ substrs = ['size=1',
+ '[0] = ',
+ 'first = \"zero\"',
+ 'second = 0'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect("frame variable si",
+ substrs = ['size=4',
+ '[0] = ',
+ 'first = \"zero\"',
+ 'second = 0',
+ '[1] = ',
+ 'first = \"one\"',
+ 'second = 1',
+ '[2] = ',
+ 'first = \"two\"',
+ 'second = 2',
+ '[3] = ',
+ 'first = \"three\"',
+ 'second = 3'])
+
+ self.expect("p si",
+ substrs = ['size=4',
+ '[0] = ',
+ 'first = \"zero\"',
+ 'second = 0',
+ '[1] = ',
+ 'first = \"one\"',
+ 'second = 1',
+ '[2] = ',
+ 'first = \"two\"',
+ 'second = 2',
+ '[3] = ',
+ 'first = \"three\"',
+ 'second = 3'])
+
+ # check that MightHaveChildren() gets it right
+ self.assertTrue(self.frame().FindVariable("si").MightHaveChildren(), "si.MightHaveChildren() says False for non empty!")
+
+ # check access-by-index
+ self.expect("frame variable si[0]",
+ substrs = ['first = ', 'one',
+ 'second = 1']);
+
+ # check that the expression parser does not make use of
+ # synthetic children instead of running code
+ # TOT clang has a fix for this, which makes the expression command here succeed
+ # since this would make the test fail or succeed depending on clang version in use
+ # this is safer commented for the time being
+ #self.expect("expression si[0]", matching=False, error=True,
+ # substrs = ['first = ', 'zero'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect('frame variable si',
+ substrs = ['size=0',
+ '{}'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect('frame variable is',
+ substrs = ['size=0',
+ '{}'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect("frame variable is",
+ substrs = ['size=4',
+ '[0] = ',
+ 'second = \"goofy\"',
+ 'first = 85',
+ '[1] = ',
+ 'second = \"is\"',
+ 'first = 1',
+ '[2] = ',
+ 'second = \"smart\"',
+ 'first = 2',
+ '[3] = ',
+ 'second = \"!!!\"',
+ 'first = 3'])
+
+ self.expect("p is",
+ substrs = ['size=4',
+ '[0] = ',
+ 'second = \"goofy\"',
+ 'first = 85',
+ '[1] = ',
+ 'second = \"is\"',
+ 'first = 1',
+ '[2] = ',
+ 'second = \"smart\"',
+ 'first = 2',
+ '[3] = ',
+ 'second = \"!!!\"',
+ 'first = 3'])
+
+ # check that MightHaveChildren() gets it right
+ self.assertTrue(self.frame().FindVariable("is").MightHaveChildren(), "is.MightHaveChildren() says False for non empty!")
+
+ # check access-by-index
+ self.expect("frame variable is[0]",
+ substrs = ['first = ',
+ 'second =']);
+
+ # check that the expression parser does not make use of
+ # synthetic children instead of running code
+ # TOT clang has a fix for this, which makes the expression command here succeed
+ # since this would make the test fail or succeed depending on clang version in use
+ # this is safer commented for the time being
+ #self.expect("expression is[0]", matching=False, error=True,
+ # substrs = ['first = ', 'goofy'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect('frame variable is',
+ substrs = ['size=0',
+ '{}'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect('frame variable ss',
+ substrs = ['size=0',
+ '{}'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect("frame variable ss",
+ substrs = ['size=3',
+ '[0] = ',
+ 'second = \"hello\"',
+ 'first = \"ciao\"',
+ '[1] = ',
+ 'second = \"house\"',
+ 'first = \"casa\"',
+ '[2] = ',
+ 'second = \"cat\"',
+ 'first = \"gatto\"'])
+
+ self.expect("p ss",
+ substrs = ['size=3',
+ '[0] = ',
+ 'second = \"hello\"',
+ 'first = \"ciao\"',
+ '[1] = ',
+ 'second = \"house\"',
+ 'first = \"casa\"',
+ '[2] = ',
+ 'second = \"cat\"',
+ 'first = \"gatto\"'])
+
+ # check that MightHaveChildren() gets it right
+ self.assertTrue(self.frame().FindVariable("ss").MightHaveChildren(), "ss.MightHaveChildren() says False for non empty!")
+
+ # check access-by-index
+ self.expect("frame variable ss[2]",
+ substrs = ['gatto', 'cat']);
+
+ # check that the expression parser does not make use of
+ # synthetic children instead of running code
+ # TOT clang has a fix for this, which makes the expression command here succeed
+ # since this would make the test fail or succeed depending on clang version in use
+ # this is safer commented for the time being
+ #self.expect("expression ss[3]", matching=False, error=True,
+ # substrs = ['gatto'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect('frame variable ss',
+ substrs = ['size=0',
+ '{}'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/main.cpp
new file mode 100644
index 000000000000..6247ca8b2412
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/map/main.cpp
@@ -0,0 +1,77 @@
+#include <string>
+#include <map>
+
+#define intint_map std::map<int, int>
+#define strint_map std::map<std::string, int>
+#define intstr_map std::map<int, std::string>
+#define strstr_map std::map<std::string, std::string>
+
+int g_the_foo = 0;
+
+int thefoo_rw(int arg = 1)
+{
+ if (arg < 0)
+ arg = 0;
+ if (!arg)
+ arg = 1;
+ g_the_foo += arg;
+ return g_the_foo;
+}
+
+int main()
+{
+ intint_map ii;
+
+ ii[0] = 0; // Set break point at this line.
+ ii[1] = 1;
+ thefoo_rw(1); // Set break point at this line.
+ ii[2] = 0;
+ ii[3] = 1;
+ thefoo_rw(1); // Set break point at this line.
+ ii[4] = 0;
+ ii[5] = 1;
+ ii[6] = 0;
+ ii[7] = 1;
+ thefoo_rw(1); // Set break point at this line.
+ ii[85] = 1234567;
+
+ ii.clear();
+
+ strint_map si;
+ thefoo_rw(1); // Set break point at this line.
+
+ si["zero"] = 0;
+ thefoo_rw(1); // Set break point at this line.
+ si["one"] = 1;
+ si["two"] = 2;
+ si["three"] = 3;
+ thefoo_rw(1); // Set break point at this line.
+ si["four"] = 4;
+
+ si.clear();
+ thefoo_rw(1); // Set break point at this line.
+
+ intstr_map is;
+ thefoo_rw(1); // Set break point at this line.
+ is[85] = "goofy";
+ is[1] = "is";
+ is[2] = "smart";
+ is[3] = "!!!";
+ thefoo_rw(1); // Set break point at this line.
+
+ is.clear();
+ thefoo_rw(1); // Set break point at this line.
+
+ strstr_map ss;
+ thefoo_rw(1); // Set break point at this line.
+
+ ss["ciao"] = "hello";
+ ss["casa"] = "house";
+ ss["gatto"] = "cat";
+ thefoo_rw(1); // Set break point at this line.
+ ss["a Mac.."] = "..is always a Mac!";
+
+ ss.clear();
+ thefoo_rw(1); // Set break point at this line.
+ return 0;
+} \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/Makefile
new file mode 100644
index 000000000000..1f609a41d908
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../../../make
+
+CXX_SOURCES := main.cpp
+
+USE_LIBCPP := 1
+include $(LEVEL)/Makefile.rules
+CXXFLAGS += -O0
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/TestDataFormatterLibccMultiMap.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/TestDataFormatterLibccMultiMap.py
new file mode 100644
index 000000000000..d0ca73d3251d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/TestDataFormatterLibccMultiMap.py
@@ -0,0 +1,298 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class LibcxxMultiMapDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfWindows # libc++ not ported to Windows yet
+ @skipIfGcc
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ bkpt = self.target().FindBreakpointByID(lldbutil.run_break_set_by_source_regexp (self, "Set break point at this line."))
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+"))
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.expect('image list', substrs = self.getLibcPlusPlusLibs())
+
+ self.expect('frame variable ii',
+ substrs = ['size=0',
+ '{}'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect('frame variable ii',
+ substrs = ['size=2',
+ '[0] = ',
+ 'first = 0',
+ 'second = 0',
+ '[1] = ',
+ 'first = 1',
+ 'second = 1'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect('frame variable ii',
+ substrs = ['size=4',
+ '[2] = ',
+ 'first = 2',
+ 'second = 0',
+ '[3] = ',
+ 'first = 3',
+ 'second = 1'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect("frame variable ii",
+ substrs = ['size=8',
+ '[5] = ',
+ 'first = 5',
+ 'second = 0',
+ '[7] = ',
+ 'first = 7',
+ 'second = 1'])
+
+ self.expect("p ii",
+ substrs = ['size=8',
+ '[5] = ',
+ 'first = 5',
+ 'second = 0',
+ '[7] = ',
+ 'first = 7',
+ 'second = 1'])
+
+ # check access-by-index
+ self.expect("frame variable ii[0]",
+ substrs = ['first = 0',
+ 'second = 0']);
+ self.expect("frame variable ii[3]",
+ substrs = ['first =',
+ 'second =']);
+
+ # check that MightHaveChildren() gets it right
+ self.assertTrue(self.frame().FindVariable("ii").MightHaveChildren(), "ii.MightHaveChildren() says False for non empty!")
+
+ # check that the expression parser does not make use of
+ # synthetic children instead of running code
+ # TOT clang has a fix for this, which makes the expression command here succeed
+ # since this would make the test fail or succeed depending on clang version in use
+ # this is safer commented for the time being
+ #self.expect("expression ii[8]", matching=False, error=True,
+ # substrs = ['1234567'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect('frame variable ii',
+ substrs = ['size=0',
+ '{}'])
+
+ self.expect('frame variable si',
+ substrs = ['size=0',
+ '{}'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect('frame variable si',
+ substrs = ['size=1',
+ '[0] = ',
+ 'first = \"zero\"',
+ 'second = 0'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect("frame variable si",
+ substrs = ['size=4',
+ '[0] = ',
+ 'first = \"zero\"',
+ 'second = 0',
+ '[1] = ',
+ 'first = \"one\"',
+ 'second = 1',
+ '[2] = ',
+ 'first = \"two\"',
+ 'second = 2',
+ '[3] = ',
+ 'first = \"three\"',
+ 'second = 3'])
+
+ self.expect("p si",
+ substrs = ['size=4',
+ '[0] = ',
+ 'first = \"zero\"',
+ 'second = 0',
+ '[1] = ',
+ 'first = \"one\"',
+ 'second = 1',
+ '[2] = ',
+ 'first = \"two\"',
+ 'second = 2',
+ '[3] = ',
+ 'first = \"three\"',
+ 'second = 3'])
+
+ # check that MightHaveChildren() gets it right
+ self.assertTrue(self.frame().FindVariable("si").MightHaveChildren(), "si.MightHaveChildren() says False for non empty!")
+
+ # check access-by-index
+ self.expect("frame variable si[0]",
+ substrs = ['first = ', 'one',
+ 'second = 1']);
+
+ # check that the expression parser does not make use of
+ # synthetic children instead of running code
+ # TOT clang has a fix for this, which makes the expression command here succeed
+ # since this would make the test fail or succeed depending on clang version in use
+ # this is safer commented for the time being
+ #self.expect("expression si[0]", matching=False, error=True,
+ # substrs = ['first = ', 'zero'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect('frame variable si',
+ substrs = ['size=0',
+ '{}'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect('frame variable is',
+ substrs = ['size=0',
+ '{}'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect("frame variable is",
+ substrs = ['size=4',
+ '[0] = ',
+ 'second = \"goofy\"',
+ 'first = 85',
+ '[1] = ',
+ 'second = \"is\"',
+ 'first = 1',
+ '[2] = ',
+ 'second = \"smart\"',
+ 'first = 2',
+ '[3] = ',
+ 'second = \"!!!\"',
+ 'first = 3'])
+
+ self.expect("p is",
+ substrs = ['size=4',
+ '[0] = ',
+ 'second = \"goofy\"',
+ 'first = 85',
+ '[1] = ',
+ 'second = \"is\"',
+ 'first = 1',
+ '[2] = ',
+ 'second = \"smart\"',
+ 'first = 2',
+ '[3] = ',
+ 'second = \"!!!\"',
+ 'first = 3'])
+
+ # check that MightHaveChildren() gets it right
+ self.assertTrue(self.frame().FindVariable("is").MightHaveChildren(), "is.MightHaveChildren() says False for non empty!")
+
+ # check access-by-index
+ self.expect("frame variable is[0]",
+ substrs = ['first = ',
+ 'second =']);
+
+ # check that the expression parser does not make use of
+ # synthetic children instead of running code
+ # TOT clang has a fix for this, which makes the expression command here succeed
+ # since this would make the test fail or succeed depending on clang version in use
+ # this is safer commented for the time being
+ #self.expect("expression is[0]", matching=False, error=True,
+ # substrs = ['first = ', 'goofy'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect('frame variable is',
+ substrs = ['size=0',
+ '{}'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect('frame variable ss',
+ substrs = ['size=0',
+ '{}'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect("frame variable ss",
+ substrs = ['size=3',
+ '[0] = ',
+ 'second = \"hello\"',
+ 'first = \"ciao\"',
+ '[1] = ',
+ 'second = \"house\"',
+ 'first = \"casa\"',
+ '[2] = ',
+ 'second = \"cat\"',
+ 'first = \"gatto\"'])
+
+ self.expect("p ss",
+ substrs = ['size=3',
+ '[0] = ',
+ 'second = \"hello\"',
+ 'first = \"ciao\"',
+ '[1] = ',
+ 'second = \"house\"',
+ 'first = \"casa\"',
+ '[2] = ',
+ 'second = \"cat\"',
+ 'first = \"gatto\"'])
+
+ # check that MightHaveChildren() gets it right
+ self.assertTrue(self.frame().FindVariable("ss").MightHaveChildren(), "ss.MightHaveChildren() says False for non empty!")
+
+ # check access-by-index
+ self.expect("frame variable ss[2]",
+ substrs = ['gatto', 'cat']);
+
+ # check that the expression parser does not make use of
+ # synthetic children instead of running code
+ # TOT clang has a fix for this, which makes the expression command here succeed
+ # since this would make the test fail or succeed depending on clang version in use
+ # this is safer commented for the time being
+ #self.expect("expression ss[3]", matching=False, error=True,
+ # substrs = ['gatto'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect('frame variable ss',
+ substrs = ['size=0',
+ '{}'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/main.cpp
new file mode 100644
index 000000000000..e8385994125d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multimap/main.cpp
@@ -0,0 +1,77 @@
+#include <string>
+#include <map>
+
+#define intint_map std::multimap<int, int>
+#define strint_map std::multimap<std::string, int>
+#define intstr_map std::multimap<int, std::string>
+#define strstr_map std::multimap<std::string, std::string>
+
+int g_the_foo = 0;
+
+int thefoo_rw(int arg = 1)
+{
+ if (arg < 0)
+ arg = 0;
+ if (!arg)
+ arg = 1;
+ g_the_foo += arg;
+ return g_the_foo;
+}
+
+int main()
+{
+ intint_map ii;
+
+ ii.emplace(0,0); // Set break point at this line.
+ ii.emplace(1,1);
+ thefoo_rw(1); // Set break point at this line.
+ ii.emplace(2,0);
+ ii.emplace(3,1);
+ thefoo_rw(1); // Set break point at this line.
+ ii.emplace(4,0);
+ ii.emplace(5,1);
+ ii.emplace(6,0);
+ ii.emplace(7,1);
+ thefoo_rw(1); // Set break point at this line.
+ ii.emplace(85,1234567);
+
+ ii.clear();
+
+ strint_map si;
+ thefoo_rw(1); // Set break point at this line.
+
+ si.emplace("zero",0);
+ thefoo_rw(1); // Set break point at this line.
+ si.emplace("one",1);
+ si.emplace("two",2);
+ si.emplace("three",3);
+ thefoo_rw(1); // Set break point at this line.
+ si.emplace("four",4);
+
+ si.clear();
+ thefoo_rw(1); // Set break point at this line.
+
+ intstr_map is;
+ thefoo_rw(1); // Set break point at this line.
+ is.emplace(85,"goofy");
+ is.emplace(1,"is");
+ is.emplace(2,"smart");
+ is.emplace(3,"!!!");
+ thefoo_rw(1); // Set break point at this line.
+
+ is.clear();
+ thefoo_rw(1); // Set break point at this line.
+
+ strstr_map ss;
+ thefoo_rw(1); // Set break point at this line.
+
+ ss.emplace("ciao","hello");
+ ss.emplace("casa","house");
+ ss.emplace("gatto","cat");
+ thefoo_rw(1); // Set break point at this line.
+ ss.emplace("a Mac..","..is always a Mac!");
+
+ ss.clear();
+ thefoo_rw(1); // Set break point at this line.
+ return 0;
+} \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/Makefile
new file mode 100644
index 000000000000..1f609a41d908
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../../../make
+
+CXX_SOURCES := main.cpp
+
+USE_LIBCPP := 1
+include $(LEVEL)/Makefile.rules
+CXXFLAGS += -O0
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/TestDataFormatterLibcxxMultiSet.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/TestDataFormatterLibcxxMultiSet.py
new file mode 100644
index 000000000000..384f6130d0c0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/TestDataFormatterLibcxxMultiSet.py
@@ -0,0 +1,69 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class LibcxxMultiSetDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfGcc
+ @skipIfWindows # libc++ not ported to Windows yet
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ bkpt = self.target().FindBreakpointByID(lldbutil.run_break_set_by_source_regexp (self, "Set break point at this line."))
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+"))
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.expect('image list', substrs = self.getLibcPlusPlusLibs())
+
+ self.expect("frame variable ii",substrs = ["size=0","{}"])
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+ self.expect("frame variable ii",substrs = ["size=6","[0] = 0","[1] = 1", "[2] = 2", "[3] = 3", "[4] = 4", "[5] = 5"])
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+ self.expect("frame variable ii",substrs = ["size=7","[2] = 2", "[3] = 3", "[6] = 6"])
+ self.expect("p ii",substrs = ["size=7","[2] = 2", "[3] = 3", "[6] = 6"])
+ self.expect("frame variable ii[2]",substrs = [" = 2"])
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+ self.expect("frame variable ii",substrs = ["size=0","{}"])
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+ self.expect("frame variable ii",substrs = ["size=0","{}"])
+ self.expect("frame variable ss",substrs = ["size=0","{}"])
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+ self.expect("frame variable ss",substrs = ["size=2",'[0] = "a"','[1] = "a very long string is right here"'])
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+ self.expect("frame variable ss",substrs = ["size=4",'[2] = "b"','[3] = "c"','[0] = "a"','[1] = "a very long string is right here"'])
+ self.expect("p ss",substrs = ["size=4",'[2] = "b"','[3] = "c"','[0] = "a"','[1] = "a very long string is right here"'])
+ self.expect("frame variable ss[2]",substrs = [' = "b"'])
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+ self.expect("frame variable ss",substrs = ["size=3",'[0] = "a"','[1] = "a very long string is right here"','[2] = "c"'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/main.cpp
new file mode 100644
index 000000000000..1e1dd3b16039
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/multiset/main.cpp
@@ -0,0 +1,57 @@
+#include <string>
+#ifdef _LIBCPP_INLINE_VISIBILITY
+#undef _LIBCPP_INLINE_VISIBILITY
+#endif
+#define _LIBCPP_INLINE_VISIBILITY
+#include <set>
+
+typedef std::multiset<int> intset;
+typedef std::multiset<std::string> stringset;
+
+int g_the_foo = 0;
+
+int thefoo_rw(int arg = 1)
+{
+ if (arg < 0)
+ arg = 0;
+ if (!arg)
+ arg = 1;
+ g_the_foo += arg;
+ return g_the_foo;
+}
+
+int main()
+{
+ intset ii;
+ thefoo_rw(1); // Set break point at this line.
+
+ ii.insert(0);
+ ii.insert(1);
+ ii.insert(2);
+ ii.insert(3);
+ ii.insert(4);
+ ii.insert(5);
+ thefoo_rw(1); // Set break point at this line.
+
+ ii.insert(6);
+ thefoo_rw(1); // Set break point at this line.
+
+ ii.clear();
+ thefoo_rw(1); // Set break point at this line.
+
+ stringset ss;
+ thefoo_rw(1); // Set break point at this line.
+
+ ss.insert("a");
+ ss.insert("a very long string is right here");
+ thefoo_rw(1); // Set break point at this line.
+
+ ss.insert("b");
+ ss.insert("c");
+ thefoo_rw(1); // Set break point at this line.
+
+ ss.erase("b");
+ thefoo_rw(1); // Set break point at this line.
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/Makefile
new file mode 100644
index 000000000000..1f609a41d908
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../../../make
+
+CXX_SOURCES := main.cpp
+
+USE_LIBCPP := 1
+include $(LEVEL)/Makefile.rules
+CXXFLAGS += -O0
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/TestDataFormatterLibcxxSet.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/TestDataFormatterLibcxxSet.py
new file mode 100644
index 000000000000..fcbfb0a8f0ed
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/TestDataFormatterLibcxxSet.py
@@ -0,0 +1,69 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class LibcxxSetDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfGcc
+ @skipIfWindows # libc++ not ported to Windows yet
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ bkpt = self.target().FindBreakpointByID(lldbutil.run_break_set_by_source_regexp (self, "Set break point at this line."))
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+"))
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.expect('image list', substrs = self.getLibcPlusPlusLibs())
+
+ self.expect("frame variable ii",substrs = ["size=0","{}"])
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+ self.expect("frame variable ii",substrs = ["size=6","[0] = 0","[1] = 1", "[2] = 2", "[3] = 3", "[4] = 4", "[5] = 5"])
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+ self.expect("frame variable ii",substrs = ["size=7","[2] = 2", "[3] = 3", "[6] = 6"])
+ self.expect("frame variable ii[2]",substrs = [" = 2"])
+ self.expect("p ii",substrs = ["size=7","[2] = 2", "[3] = 3", "[6] = 6"])
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+ self.expect("frame variable ii",substrs = ["size=0","{}"])
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+ self.expect("frame variable ii",substrs = ["size=0","{}"])
+ self.expect("frame variable ss",substrs = ["size=0","{}"])
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+ self.expect("frame variable ss",substrs = ["size=2",'[0] = "a"','[1] = "a very long string is right here"'])
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+ self.expect("frame variable ss",substrs = ["size=4",'[2] = "b"','[3] = "c"','[0] = "a"','[1] = "a very long string is right here"'])
+ self.expect("p ss",substrs = ["size=4",'[2] = "b"','[3] = "c"','[0] = "a"','[1] = "a very long string is right here"'])
+ self.expect("frame variable ss[2]",substrs = [' = "b"'])
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+ self.expect("frame variable ss",substrs = ["size=3",'[0] = "a"','[1] = "a very long string is right here"','[2] = "c"'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/main.cpp
new file mode 100644
index 000000000000..cc3033ef26e4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/set/main.cpp
@@ -0,0 +1,57 @@
+#include <string>
+#ifdef _LIBCPP_INLINE_VISIBILITY
+#undef _LIBCPP_INLINE_VISIBILITY
+#endif
+#define _LIBCPP_INLINE_VISIBILITY
+#include <set>
+
+typedef std::set<int> intset;
+typedef std::set<std::string> stringset;
+
+int g_the_foo = 0;
+
+int thefoo_rw(int arg = 1)
+{
+ if (arg < 0)
+ arg = 0;
+ if (!arg)
+ arg = 1;
+ g_the_foo += arg;
+ return g_the_foo;
+}
+
+int main()
+{
+ intset ii;
+ thefoo_rw(1); // Set break point at this line.
+
+ ii.insert(0);
+ ii.insert(1);
+ ii.insert(2);
+ ii.insert(3);
+ ii.insert(4);
+ ii.insert(5);
+ thefoo_rw(1); // Set break point at this line.
+
+ ii.insert(6);
+ thefoo_rw(1); // Set break point at this line.
+
+ ii.clear();
+ thefoo_rw(1); // Set break point at this line.
+
+ stringset ss;
+ thefoo_rw(1); // Set break point at this line.
+
+ ss.insert("a");
+ ss.insert("a very long string is right here");
+ thefoo_rw(1); // Set break point at this line.
+
+ ss.insert("b");
+ ss.insert("c");
+ thefoo_rw(1); // Set break point at this line.
+
+ ss.erase("b");
+ thefoo_rw(1); // Set break point at this line.
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/Makefile
new file mode 100644
index 000000000000..1f609a41d908
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../../../make
+
+CXX_SOURCES := main.cpp
+
+USE_LIBCPP := 1
+include $(LEVEL)/Makefile.rules
+CXXFLAGS += -O0
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/TestDataFormatterLibcxxString.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/TestDataFormatterLibcxxString.py
new file mode 100644
index 000000000000..942124255f55
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/TestDataFormatterLibcxxString.py
@@ -0,0 +1,86 @@
+#coding=utf8
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class LibcxxStringDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ @skipIfGcc
+ @skipIfWindows # libc++ not ported to Windows yet
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+"))
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.expect("frame variable",
+ substrs = ['(std::__1::wstring) s = L"hello world! מזל טוב!"',
+ '(std::__1::wstring) S = L"!!!!"',
+ '(const wchar_t *) mazeltov = 0x','L"מזל טוב"',
+ '(std::__1::string) q = "hello world"',
+ '(std::__1::string) Q = "quite a long std::strin with lots of info inside it"',
+ '(std::__1::string) IHaveEmbeddedZeros = "a\\0b\\0c\\0d"',
+ '(std::__1::wstring) IHaveEmbeddedZerosToo = L"hello world!\\0てざ ル゜䋨ミ㠧槊 きゅへ狦穤襩 じゃ馩リョ 䤦監"'])
+
+ self.runCmd("n")
+
+ TheVeryLongOne = self.frame().FindVariable("TheVeryLongOne");
+ summaryOptions = lldb.SBTypeSummaryOptions()
+ summaryOptions.SetCapping(lldb.eTypeSummaryUncapped)
+ uncappedSummaryStream = lldb.SBStream()
+ TheVeryLongOne.GetSummary(uncappedSummaryStream,summaryOptions)
+ uncappedSummary = uncappedSummaryStream.GetData()
+ self.assertTrue(uncappedSummary.find("someText") > 0, "uncappedSummary does not include the full string")
+ summaryOptions.SetCapping(lldb.eTypeSummaryCapped)
+ cappedSummaryStream = lldb.SBStream()
+ TheVeryLongOne.GetSummary(cappedSummaryStream,summaryOptions)
+ cappedSummary = cappedSummaryStream.GetData()
+ self.assertTrue(cappedSummary.find("someText") <= 0, "cappedSummary includes the full string")
+
+ self.expect("frame variable",
+ substrs = ['(std::__1::wstring) s = L"hello world! מזל טוב!"',
+ '(std::__1::wstring) S = L"!!!!!"',
+ '(const wchar_t *) mazeltov = 0x','L"מזל טוב"',
+ '(std::__1::string) q = "hello world"',
+ '(std::__1::string) Q = "quite a long std::strin with lots of info inside it"',
+ '(std::__1::string) IHaveEmbeddedZeros = "a\\0b\\0c\\0d"',
+ '(std::__1::wstring) IHaveEmbeddedZerosToo = L"hello world!\\0てざ ル゜䋨ミ㠧槊 きゅへ狦穤襩 じゃ馩リョ 䤦監"'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/main.cpp
new file mode 100644
index 000000000000..9ca0da39cfc8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/string/main.cpp
@@ -0,0 +1,15 @@
+#include <string>
+
+int main()
+{
+ std::wstring s(L"hello world! מזל טוב!");
+ std::wstring S(L"!!!!");
+ const wchar_t *mazeltov = L"מזל טוב";
+ std::string q("hello world");
+ std::string Q("quite a long std::strin with lots of info inside it");
+ std::string TheVeryLongOne("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890someText1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890");
+ std::string IHaveEmbeddedZeros("a\0b\0c\0d",7);
+ std::wstring IHaveEmbeddedZerosToo(L"hello world!\0てざ ル゜䋨ミ㠧槊 きゅへ狦穤襩 じゃ馩リョ 䤦監", 38);
+ S.assign(L"!!!!!"); // Set break point at this line.
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/Makefile
new file mode 100644
index 000000000000..1f609a41d908
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../../../make
+
+CXX_SOURCES := main.cpp
+
+USE_LIBCPP := 1
+include $(LEVEL)/Makefile.rules
+CXXFLAGS += -O0
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/TestDataFormatterUnordered.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/TestDataFormatterUnordered.py
new file mode 100644
index 000000000000..5e6ec2519323
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/TestDataFormatterUnordered.py
@@ -0,0 +1,75 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class LibcxxUnorderedDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfWindows # libc++ not ported to Windows yet
+ @skipIfGcc
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_source_regexp (self, "Set break point at this line.")
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+"))
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.expect('image list', substrs = self.getLibcPlusPlusLibs())
+
+ self.look_for_content_and_continue(
+ "map", ['size=5 {', 'hello', 'world', 'this', 'is', 'me'])
+
+ self.look_for_content_and_continue(
+ "mmap", ['size=6 {', 'first = 3', 'second = "this"',
+ 'first = 2', 'second = "hello"'])
+
+ self.look_for_content_and_continue(
+ "iset", ['size=5 {', '\[\d\] = 5', '\[\d\] = 3', '\[\d\] = 2'])
+
+ self.look_for_content_and_continue(
+ "sset", ['size=5 {', '\[\d\] = "is"', '\[\d\] = "world"',
+ '\[\d\] = "hello"'])
+
+ self.look_for_content_and_continue(
+ "imset", ['size=6 {', '(\[\d\] = 3(\\n|.)+){3}',
+ '\[\d\] = 2', '\[\d\] = 1'])
+
+ self.look_for_content_and_continue(
+ "smset",
+ ['size=5 {', '(\[\d\] = "is"(\\n|.)+){2}',
+ '(\[\d\] = "world"(\\n|.)+){2}'])
+
+ def look_for_content_and_continue(self, var_name, patterns):
+ self.expect( ("frame variable %s" % var_name), patterns=patterns)
+ self.runCmd("continue")
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/main.cpp
new file mode 100644
index 000000000000..4e8a1a779c0c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/unordered/main.cpp
@@ -0,0 +1,84 @@
+#include <string>
+#ifdef _LIBCPP_INLINE_VISIBILITY
+#undef _LIBCPP_INLINE_VISIBILITY
+#endif
+#define _LIBCPP_INLINE_VISIBILITY
+#include <unordered_map>
+#include <unordered_set>
+
+using std::string;
+
+#define intstr_map std::unordered_map<int, string>
+#define intstr_mmap std::unordered_multimap<int, string>
+
+#define int_set std::unordered_set<int>
+#define str_set std::unordered_set<string>
+#define int_mset std::unordered_multiset<int>
+#define str_mset std::unordered_multiset<string>
+
+int g_the_foo = 0;
+
+int thefoo_rw(int arg = 1)
+{
+ if (arg < 0)
+ arg = 0;
+ if (!arg)
+ arg = 1;
+ g_the_foo += arg;
+ return g_the_foo;
+}
+
+int main()
+{
+ intstr_map map;
+ map.emplace(1,"hello");
+ map.emplace(2,"world");
+ map.emplace(3,"this");
+ map.emplace(4,"is");
+ map.emplace(5,"me");
+ thefoo_rw(); // Set break point at this line.
+
+ intstr_mmap mmap;
+ mmap.emplace(1,"hello");
+ mmap.emplace(2,"hello");
+ mmap.emplace(2,"world");
+ mmap.emplace(3,"this");
+ mmap.emplace(3,"this");
+ mmap.emplace(3,"this");
+ thefoo_rw(); // Set break point at this line.
+
+ int_set iset;
+ iset.emplace(1);
+ iset.emplace(2);
+ iset.emplace(3);
+ iset.emplace(4);
+ iset.emplace(5);
+ thefoo_rw(); // Set break point at this line.
+
+ str_set sset;
+ sset.emplace("hello");
+ sset.emplace("world");
+ sset.emplace("this");
+ sset.emplace("is");
+ sset.emplace("me");
+ thefoo_rw(); // Set break point at this line.
+
+ int_mset imset;
+ imset.emplace(1);
+ imset.emplace(2);
+ imset.emplace(2);
+ imset.emplace(3);
+ imset.emplace(3);
+ imset.emplace(3);
+ thefoo_rw(); // Set break point at this line.
+
+ str_mset smset;
+ smset.emplace("hello");
+ smset.emplace("world");
+ smset.emplace("world");
+ smset.emplace("is");
+ smset.emplace("is");
+ thefoo_rw(); // Set break point at this line.
+
+ return 0;
+} \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/Makefile
new file mode 100644
index 000000000000..637fa7e80bfd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../../../make
+
+CXX_SOURCES := main.cpp
+USE_LIBCPP := 1
+include $(LEVEL)/Makefile.rules
+CXXFLAGS += -O0
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/TestDataFormatterLibcxxVBool.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/TestDataFormatterLibcxxVBool.py
new file mode 100644
index 000000000000..9771a819aa6b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/TestDataFormatterLibcxxVBool.py
@@ -0,0 +1,58 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class LibcxxVBoolDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ @skipIfGcc
+ @skipIfWindows # libc++ not ported to Windows.
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+"))
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.expect("frame variable vBool",
+ substrs = ['size=49','[0] = false','[1] = true','[18] = false','[27] = true','[36] = false','[47] = true','[48] = true'])
+
+ self.expect("expr vBool",
+ substrs = ['size=49','[0] = false','[1] = true','[18] = false','[27] = true','[36] = false','[47] = true','[48] = true'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/main.cpp
new file mode 100644
index 000000000000..7b9956ed36ea
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vbool/main.cpp
@@ -0,0 +1,69 @@
+#include <string>
+#ifdef _LIBCPP_INLINE_VISIBILITY
+#undef _LIBCPP_INLINE_VISIBILITY
+#endif
+#define _LIBCPP_INLINE_VISIBILITY
+
+#include <vector>
+
+int main()
+{
+ std::vector<bool> vBool;
+
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(true);
+
+ return 0; // Set break point at this line.
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/Makefile
new file mode 100644
index 000000000000..1f609a41d908
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../../../make
+
+CXX_SOURCES := main.cpp
+
+USE_LIBCPP := 1
+include $(LEVEL)/Makefile.rules
+CXXFLAGS += -O0
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/TestDataFormatterLibcxxVector.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/TestDataFormatterLibcxxVector.py
new file mode 100644
index 000000000000..f8cd65be0931
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/TestDataFormatterLibcxxVector.py
@@ -0,0 +1,180 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class LibcxxVectorDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfGcc
+ @skipIfWindows # libc++ not ported to Windows yet
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.skip_if_library_missing(self, self.target(), lldbutil.PrintableRegex("libc\+\+"))
+
+ bkpt = self.target().FindBreakpointByID(lldbutil.run_break_set_by_source_regexp (self, "break here"))
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ # empty vectors (and storage pointers SHOULD BOTH BE NULL..)
+ self.expect("frame variable numbers",
+ substrs = ['numbers = size=0'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ # first value added
+ self.expect("frame variable numbers",
+ substrs = ['numbers = size=1',
+ '[0] = 1',
+ '}'])
+
+ # add some more data
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect("frame variable numbers",
+ substrs = ['numbers = size=4',
+ '[0] = 1',
+ '[1] = 12',
+ '[2] = 123',
+ '[3] = 1234',
+ '}'])
+
+ self.expect("p numbers",
+ substrs = ['$', 'size=4',
+ '[0] = 1',
+ '[1] = 12',
+ '[2] = 123',
+ '[3] = 1234',
+ '}'])
+
+
+ # check access to synthetic children
+ self.runCmd("type summary add --summary-string \"item 0 is ${var[0]}\" std::int_vect int_vect")
+ self.expect('frame variable numbers',
+ substrs = ['item 0 is 1']);
+
+ self.runCmd("type summary add --summary-string \"item 0 is ${svar[0]}\" std::int_vect int_vect")
+ self.expect('frame variable numbers',
+ substrs = ['item 0 is 1']);
+ # move on with synths
+ self.runCmd("type summary delete std::int_vect")
+ self.runCmd("type summary delete int_vect")
+
+ # add some more data
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect("frame variable numbers",
+ substrs = ['numbers = size=7',
+ '[0] = 1',
+ '[1] = 12',
+ '[2] = 123',
+ '[3] = 1234',
+ '[4] = 12345',
+ '[5] = 123456',
+ '[6] = 1234567',
+ '}'])
+
+ self.expect("p numbers",
+ substrs = ['$', 'size=7',
+ '[0] = 1',
+ '[1] = 12',
+ '[2] = 123',
+ '[3] = 1234',
+ '[4] = 12345',
+ '[5] = 123456',
+ '[6] = 1234567',
+ '}'])
+
+ # check access-by-index
+ self.expect("frame variable numbers[0]",
+ substrs = ['1']);
+ self.expect("frame variable numbers[1]",
+ substrs = ['12']);
+ self.expect("frame variable numbers[2]",
+ substrs = ['123']);
+ self.expect("frame variable numbers[3]",
+ substrs = ['1234']);
+
+ # clear out the vector and see that we do the right thing once again
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect("frame variable numbers",
+ substrs = ['numbers = size=0'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ # first value added
+ self.expect("frame variable numbers",
+ substrs = ['numbers = size=1',
+ '[0] = 7',
+ '}'])
+
+ # check if we can display strings
+ self.expect("frame variable strings",
+ substrs = ['goofy',
+ 'is',
+ 'smart'])
+
+ self.expect("p strings",
+ substrs = ['goofy',
+ 'is',
+ 'smart'])
+
+ # test summaries based on synthetic children
+ self.runCmd("type summary add std::string_vect string_vect --summary-string \"vector has ${svar%#} items\" -e")
+ self.expect("frame variable strings",
+ substrs = ['vector has 3 items',
+ 'goofy',
+ 'is',
+ 'smart'])
+
+ self.expect("p strings",
+ substrs = ['vector has 3 items',
+ 'goofy',
+ 'is',
+ 'smart'])
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect("frame variable strings",
+ substrs = ['vector has 4 items'])
+
+ # check access-by-index
+ self.expect("frame variable strings[0]",
+ substrs = ['goofy']);
+ self.expect("frame variable strings[1]",
+ substrs = ['is']);
+
+ lldbutil.continue_to_breakpoint(self.process(), bkpt)
+
+ self.expect("frame variable strings",
+ substrs = ['vector has 0 items'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/main.cpp
new file mode 100644
index 000000000000..a9aeacf90e43
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libcxx/vector/main.cpp
@@ -0,0 +1,35 @@
+#include <string>
+#ifdef _LIBCPP_INLINE_VISIBILITY
+#undef _LIBCPP_INLINE_VISIBILITY
+#endif
+#define _LIBCPP_INLINE_VISIBILITY
+#include <vector>
+typedef std::vector<int> int_vect;
+typedef std::vector<std::string> string_vect;
+
+int main()
+{
+ int_vect numbers;
+ (numbers.push_back(1)); // break here
+ (numbers.push_back(12)); // break here
+ (numbers.push_back(123));
+ (numbers.push_back(1234));
+ (numbers.push_back(12345)); // break here
+ (numbers.push_back(123456));
+ (numbers.push_back(1234567));
+
+ numbers.clear(); // break here
+
+ (numbers.push_back(7)); // break here
+
+ string_vect strings;
+ (strings.push_back(std::string("goofy")));
+ (strings.push_back(std::string("is")));
+ (strings.push_back(std::string("smart")));
+
+ (strings.push_back(std::string("!!!"))); // break here
+
+ strings.clear(); // break here
+
+ return 0; // break here
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/Makefile
new file mode 100644
index 000000000000..7fe01d004f03
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/Makefile
@@ -0,0 +1,15 @@
+LEVEL = ../../../../../make
+
+CXX_SOURCES := main.cpp
+
+CFLAGS_EXTRAS += -O0
+USE_LIBSTDCPP := 1
+
+# clang-3.5+ outputs FullDebugInfo by default for Darwin/FreeBSD
+# targets. Other targets do not, which causes this test to fail.
+# This flag enables FullDebugInfo for all targets.
+ifneq (,$(findstring clang,$(CC)))
+ CFLAGS_EXTRAS += -fno-limit-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/TestDataFormatterStdIterator.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/TestDataFormatterStdIterator.py
new file mode 100644
index 000000000000..6742c9e71701
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/TestDataFormatterStdIterator.py
@@ -0,0 +1,62 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class StdIteratorDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ @skipIfWindows # libstdcpp not ported to Windows
+ @expectedFailureIcc # llvm.org/pr15301 LLDB prints incorrect sizes of STL containers
+ def test_with_run_command(self):
+ """Test that libstdcpp iterators format properly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.expect('frame variable ivI', substrs = ['item = 3'])
+ self.expect('expr ivI', substrs = ['item = 3'])
+
+ self.expect('frame variable iimI', substrs = ['first = 0','second = 12'])
+ self.expect('expr iimI', substrs = ['first = 0','second = 12'])
+
+ self.expect('frame variable simI', substrs = ['first = "world"','second = 42'])
+ self.expect('expr simI', substrs = ['first = "world"','second = 42'])
+
+ self.expect('frame variable svI', substrs = ['item = "hello"'])
+ self.expect('expr svI', substrs = ['item = "hello"'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/main.cpp
new file mode 100644
index 000000000000..d7b046c5bff8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/iterator/main.cpp
@@ -0,0 +1,38 @@
+#include <string>
+#include <map>
+#include <vector>
+
+typedef std::map<int, int> intint_map;
+typedef std::map<std::string, int> strint_map;
+
+typedef std::vector<int> int_vector;
+typedef std::vector<std::string> string_vector;
+
+typedef intint_map::iterator iimter;
+typedef strint_map::iterator simter;
+
+typedef int_vector::iterator ivter;
+typedef string_vector::iterator svter;
+
+int main()
+{
+ intint_map iim;
+ iim[0] = 12;
+
+ strint_map sim;
+ sim["world"] = 42;
+
+ int_vector iv;
+ iv.push_back(3);
+
+ string_vector sv;
+ sv.push_back("hello");
+
+ iimter iimI = iim.begin();
+ simter simI = sim.begin();
+
+ ivter ivI = iv.begin();
+ svter svI = sv.begin();
+
+ return 0; // Set break point at this line.
+} \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/Makefile
new file mode 100644
index 000000000000..7fe01d004f03
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/Makefile
@@ -0,0 +1,15 @@
+LEVEL = ../../../../../make
+
+CXX_SOURCES := main.cpp
+
+CFLAGS_EXTRAS += -O0
+USE_LIBSTDCPP := 1
+
+# clang-3.5+ outputs FullDebugInfo by default for Darwin/FreeBSD
+# targets. Other targets do not, which causes this test to fail.
+# This flag enables FullDebugInfo for all targets.
+ifneq (,$(findstring clang,$(CC)))
+ CFLAGS_EXTRAS += -fno-limit-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/TestDataFormatterStdList.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/TestDataFormatterStdList.py
new file mode 100644
index 000000000000..5147d18da0fe
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/TestDataFormatterStdList.py
@@ -0,0 +1,188 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class StdListDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break at for the different tests.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+ self.optional_line = line_number('main.cpp', '// Optional break point at this line.')
+ self.final_line = line_number('main.cpp', '// Set final break point at this line.')
+
+ @skipIfWindows # libstdcpp not ported to Windows
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.runCmd("frame variable numbers_list --show-types")
+
+ self.runCmd("type format add -f hex int")
+
+ self.expect("frame variable numbers_list --raw", matching=False,
+ substrs = ['size=0',
+ '{}'])
+ self.expect("frame variable &numbers_list._M_impl._M_node --raw", matching=False,
+ substrs = ['size=0',
+ '{}'])
+
+ self.expect("frame variable numbers_list",
+ substrs = ['size=0',
+ '{}'])
+
+ self.expect("p numbers_list",
+ substrs = ['size=0',
+ '{}'])
+
+ self.runCmd("n")
+
+ self.expect("frame variable numbers_list",
+ substrs = ['size=1',
+ '[0] = ',
+ '0x12345678'])
+
+ self.runCmd("n");self.runCmd("n");self.runCmd("n");
+
+ self.expect("frame variable numbers_list",
+ substrs = ['size=4',
+ '[0] = ',
+ '0x12345678',
+ '[1] =',
+ '0x11223344',
+ '[2] =',
+ '0xbeeffeed',
+ '[3] =',
+ '0x00abba00'])
+
+ self.runCmd("n");self.runCmd("n");
+
+ self.expect("frame variable numbers_list",
+ substrs = ['size=6',
+ '[0] = ',
+ '0x12345678',
+ '0x11223344',
+ '0xbeeffeed',
+ '0x00abba00',
+ '[4] =',
+ '0x0abcdef0',
+ '[5] =',
+ '0x0cab0cab'])
+
+ self.expect("p numbers_list",
+ substrs = ['size=6',
+ '[0] = ',
+ '0x12345678',
+ '0x11223344',
+ '0xbeeffeed',
+ '0x00abba00',
+ '[4] =',
+ '0x0abcdef0',
+ '[5] =',
+ '0x0cab0cab'])
+
+ # check access-by-index
+ self.expect("frame variable numbers_list[0]",
+ substrs = ['0x12345678']);
+ self.expect("frame variable numbers_list[1]",
+ substrs = ['0x11223344']);
+
+ # but check that expression does not rely on us
+ self.expect("expression numbers_list[0]", matching=False, error=True,
+ substrs = ['0x12345678'])
+
+ # check that MightHaveChildren() gets it right
+ self.assertTrue(self.frame().FindVariable("numbers_list").MightHaveChildren(), "numbers_list.MightHaveChildren() says False for non empty!")
+
+ self.runCmd("n")
+
+ self.expect("frame variable numbers_list",
+ substrs = ['size=0',
+ '{}'])
+
+ self.runCmd("n");self.runCmd("n");self.runCmd("n");self.runCmd("n");
+
+ self.expect("frame variable numbers_list",
+ substrs = ['size=4',
+ '[0] = ', '1',
+ '[1] = ', '2',
+ '[2] = ', '3',
+ '[3] = ', '4'])
+
+ self.runCmd("type format delete int")
+
+ self.runCmd("n")
+
+ self.expect("frame variable text_list",
+ substrs = ['size=0',
+ '{}'])
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.final_line, num_expected_locations=-1)
+
+ self.runCmd("c", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ self.expect("frame variable text_list",
+ substrs = ['size=4',
+ '[0]', 'goofy',
+ '[1]', 'is',
+ '[2]', 'smart',
+ '[3]', '!!!'])
+
+ self.expect("p text_list",
+ substrs = ['size=4',
+ '\"goofy\"',
+ '\"is\"',
+ '\"smart\"',
+ '\"!!!\"'])
+
+ # check access-by-index
+ self.expect("frame variable text_list[0]",
+ substrs = ['goofy']);
+ self.expect("frame variable text_list[3]",
+ substrs = ['!!!']);
+
+ # but check that expression does not rely on us
+ self.expect("expression text_list[0]", matching=False, error=True,
+ substrs = ['goofy'])
+
+ # check that MightHaveChildren() gets it right
+ self.assertTrue(self.frame().FindVariable("text_list").MightHaveChildren(), "text_list.MightHaveChildren() says False for non empty!")
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/main.cpp
new file mode 100644
index 000000000000..191acdcc97be
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/list/main.cpp
@@ -0,0 +1,34 @@
+#include <list>
+#include <string>
+
+typedef std::list<int> int_list;
+typedef std::list<std::string> string_list;
+
+int main()
+{
+ int_list numbers_list;
+
+ numbers_list.push_back(0x12345678); // Set break point at this line.
+ numbers_list.push_back(0x11223344);
+ numbers_list.push_back(0xBEEFFEED);
+ numbers_list.push_back(0x00ABBA00);
+ numbers_list.push_back(0x0ABCDEF0);
+ numbers_list.push_back(0x0CAB0CAB);
+
+ numbers_list.clear();
+
+ numbers_list.push_back(1);
+ numbers_list.push_back(2);
+ numbers_list.push_back(3);
+ numbers_list.push_back(4);
+
+ string_list text_list;
+ text_list.push_back(std::string("goofy")); // Optional break point at this line.
+ text_list.push_back(std::string("is"));
+ text_list.push_back(std::string("smart"));
+
+ text_list.push_back(std::string("!!!"));
+
+ return 0; // Set final break point at this line.
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/Makefile
new file mode 100644
index 000000000000..2c6c3cf72842
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/Makefile
@@ -0,0 +1,14 @@
+LEVEL = ../../../../../make
+
+CXX_SOURCES := main.cpp
+
+USE_LIBSTDCPP := 1
+
+# clang-3.5+ outputs FullDebugInfo by default for Darwin/FreeBSD
+# targets. Other targets do not, which causes this test to fail.
+# This flag enables FullDebugInfo for all targets.
+ifneq (,$(findstring clang,$(CC)))
+ CFLAGS_EXTRAS += -fno-limit-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/TestDataFormatterStdMap.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/TestDataFormatterStdMap.py
new file mode 100644
index 000000000000..e21c4e94c2c4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/TestDataFormatterStdMap.py
@@ -0,0 +1,322 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class StdMapDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ @expectedFailureIcc # llvm.org/pr15301: LLDB prints incorrect size of libstdc++ containers
+ @skipIfWindows # libstdcpp not ported to Windows
+ @skipIfFreeBSD
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_source_regexp (self, "Set break point at this line.")
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.runCmd("frame variable ii --show-types")
+
+ self.runCmd("type summary add -x \"std::map<\" --summary-string \"map has ${svar%#} items\" -e")
+
+ self.expect('frame variable ii',
+ substrs = ['map has 0 items',
+ '{}'])
+
+ self.runCmd("c");
+
+ self.expect('frame variable ii',
+ substrs = ['map has 2 items',
+ '[0] = ',
+ 'first = 0',
+ 'second = 0',
+ '[1] = ',
+ 'first = 1',
+ 'second = 1'])
+
+ self.runCmd("c");
+
+ self.expect('frame variable ii',
+ substrs = ['map has 4 items',
+ '[2] = ',
+ 'first = 2',
+ 'second = 0',
+ '[3] = ',
+ 'first = 3',
+ 'second = 1'])
+
+ self.runCmd("c");
+
+ self.expect("frame variable ii",
+ substrs = ['map has 9 items',
+ '[5] = ',
+ 'first = 5',
+ 'second = 0',
+ '[7] = ',
+ 'first = 7',
+ 'second = 1'])
+
+ self.expect("p ii",
+ substrs = ['map has 9 items',
+ '[5] = ',
+ 'first = 5',
+ 'second = 0',
+ '[7] = ',
+ 'first = 7',
+ 'second = 1'])
+
+ # check access-by-index
+ self.expect("frame variable ii[0]",
+ substrs = ['first = 0',
+ 'second = 0']);
+ self.expect("frame variable ii[3]",
+ substrs = ['first =',
+ 'second =']);
+
+ self.expect("frame variable ii[8]", matching=True,
+ substrs = ['1234567'])
+
+ # check that MightHaveChildren() gets it right
+ self.assertTrue(self.frame().FindVariable("ii").MightHaveChildren(), "ii.MightHaveChildren() says False for non empty!")
+
+ # check that the expression parser does not make use of
+ # synthetic children instead of running code
+ # TOT clang has a fix for this, which makes the expression command here succeed
+ # since this would make the test fail or succeed depending on clang version in use
+ # this is safer commented for the time being
+ #self.expect("expression ii[8]", matching=False, error=True,
+ # substrs = ['1234567'])
+
+ self.runCmd("c")
+
+ self.expect('frame variable ii',
+ substrs = ['map has 0 items',
+ '{}'])
+
+ self.runCmd("frame variable si --show-types")
+
+ self.expect('frame variable si',
+ substrs = ['map has 0 items',
+ '{}'])
+
+ self.runCmd("c")
+
+ self.expect('frame variable si',
+ substrs = ['map has 1 items',
+ '[0] = ',
+ 'first = \"zero\"',
+ 'second = 0'])
+
+ self.runCmd("c");
+
+ self.expect("frame variable si",
+ substrs = ['map has 5 items',
+ '[0] = ',
+ 'first = \"zero\"',
+ 'second = 0',
+ '[1] = ',
+ 'first = \"one\"',
+ 'second = 1',
+ '[2] = ',
+ 'first = \"two\"',
+ 'second = 2',
+ '[3] = ',
+ 'first = \"three\"',
+ 'second = 3',
+ '[4] = ',
+ 'first = \"four\"',
+ 'second = 4'])
+
+ self.expect("p si",
+ substrs = ['map has 5 items',
+ '[0] = ',
+ 'first = \"zero\"',
+ 'second = 0',
+ '[1] = ',
+ 'first = \"one\"',
+ 'second = 1',
+ '[2] = ',
+ 'first = \"two\"',
+ 'second = 2',
+ '[3] = ',
+ 'first = \"three\"',
+ 'second = 3',
+ '[4] = ',
+ 'first = \"four\"',
+ 'second = 4'])
+
+ # check access-by-index
+ self.expect("frame variable si[0]",
+ substrs = ['first = ', 'four',
+ 'second = 4']);
+
+ # check that MightHaveChildren() gets it right
+ self.assertTrue(self.frame().FindVariable("si").MightHaveChildren(), "si.MightHaveChildren() says False for non empty!")
+
+ # check that the expression parser does not make use of
+ # synthetic children instead of running code
+ # TOT clang has a fix for this, which makes the expression command here succeed
+ # since this would make the test fail or succeed depending on clang version in use
+ # this is safer commented for the time being
+ #self.expect("expression si[0]", matching=False, error=True,
+ # substrs = ['first = ', 'zero'])
+
+ self.runCmd("c")
+
+ self.expect('frame variable si',
+ substrs = ['map has 0 items',
+ '{}'])
+
+ self.runCmd("frame variable is --show-types")
+
+ self.expect('frame variable is',
+ substrs = ['map has 0 items',
+ '{}'])
+
+ self.runCmd("c");
+
+ self.expect("frame variable is",
+ substrs = ['map has 4 items',
+ '[0] = ',
+ 'second = \"goofy\"',
+ 'first = 85',
+ '[1] = ',
+ 'second = \"is\"',
+ 'first = 1',
+ '[2] = ',
+ 'second = \"smart\"',
+ 'first = 2',
+ '[3] = ',
+ 'second = \"!!!\"',
+ 'first = 3'])
+
+ self.expect("p is",
+ substrs = ['map has 4 items',
+ '[0] = ',
+ 'second = \"goofy\"',
+ 'first = 85',
+ '[1] = ',
+ 'second = \"is\"',
+ 'first = 1',
+ '[2] = ',
+ 'second = \"smart\"',
+ 'first = 2',
+ '[3] = ',
+ 'second = \"!!!\"',
+ 'first = 3'])
+
+ # check access-by-index
+ self.expect("frame variable is[0]",
+ substrs = ['first = ',
+ 'second =']);
+
+ # check that MightHaveChildren() gets it right
+ self.assertTrue(self.frame().FindVariable("is").MightHaveChildren(), "is.MightHaveChildren() says False for non empty!")
+
+ # check that the expression parser does not make use of
+ # synthetic children instead of running code
+ # TOT clang has a fix for this, which makes the expression command here succeed
+ # since this would make the test fail or succeed depending on clang version in use
+ # this is safer commented for the time being
+ #self.expect("expression is[0]", matching=False, error=True,
+ # substrs = ['first = ', 'goofy'])
+
+ self.runCmd("c")
+
+ self.expect('frame variable is',
+ substrs = ['map has 0 items',
+ '{}'])
+
+ self.runCmd("frame variable ss --show-types")
+
+ self.expect('frame variable ss',
+ substrs = ['map has 0 items',
+ '{}'])
+
+ self.runCmd("c");
+
+ self.expect("frame variable ss",
+ substrs = ['map has 4 items',
+ '[0] = ',
+ 'second = \"hello\"',
+ 'first = \"ciao\"',
+ '[1] = ',
+ 'second = \"house\"',
+ 'first = \"casa\"',
+ '[2] = ',
+ 'second = \"cat\"',
+ 'first = \"gatto\"',
+ '[3] = ',
+ 'second = \"..is always a Mac!\"',
+ 'first = \"a Mac..\"'])
+
+ self.expect("p ss",
+ substrs = ['map has 4 items',
+ '[0] = ',
+ 'second = \"hello\"',
+ 'first = \"ciao\"',
+ '[1] = ',
+ 'second = \"house\"',
+ 'first = \"casa\"',
+ '[2] = ',
+ 'second = \"cat\"',
+ 'first = \"gatto\"',
+ '[3] = ',
+ 'second = \"..is always a Mac!\"',
+ 'first = \"a Mac..\"'])
+
+ # check access-by-index
+ self.expect("frame variable ss[3]",
+ substrs = ['gatto', 'cat']);
+
+ # check that MightHaveChildren() gets it right
+ self.assertTrue(self.frame().FindVariable("ss").MightHaveChildren(), "ss.MightHaveChildren() says False for non empty!")
+
+ # check that the expression parser does not make use of
+ # synthetic children instead of running code
+ # TOT clang has a fix for this, which makes the expression command here succeed
+ # since this would make the test fail or succeed depending on clang version in use
+ # this is safer commented for the time being
+ #self.expect("expression ss[3]", matching=False, error=True,
+ # substrs = ['gatto'])
+
+ self.runCmd("c")
+
+ self.expect('frame variable ss',
+ substrs = ['map has 0 items',
+ '{}'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/main.cpp
new file mode 100644
index 000000000000..568c35efe072
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/map/main.cpp
@@ -0,0 +1,55 @@
+#include <map>
+#include <string>
+
+#define intint_map std::map<int, int>
+#define strint_map std::map<std::string, int>
+#define intstr_map std::map<int, std::string>
+#define strstr_map std::map<std::string, std::string>
+
+
+int main()
+{
+ intint_map ii;
+
+ ii[0] = 0; // Set break point at this line.
+ ii[1] = 1;
+ ii[2] = 0;// Set break point at this line.
+ ii[3] = 1;
+ ii[4] = 0;// Set break point at this line.
+ ii[5] = 1;
+ ii[6] = 0;
+ ii[7] = 1;
+ ii[85] = 1234567;
+
+ ii.clear();// Set break point at this line.
+
+ strint_map si;
+
+ si["zero"] = 0;// Set break point at this line.
+ si["one"] = 1;// Set break point at this line.
+ si["two"] = 2;
+ si["three"] = 3;
+ si["four"] = 4;
+
+ si.clear();// Set break point at this line.
+
+ intstr_map is;
+
+ is[85] = "goofy";// Set break point at this line.
+ is[1] = "is";
+ is[2] = "smart";
+ is[3] = "!!!";
+
+ is.clear();// Set break point at this line.
+
+ strstr_map ss;
+
+ ss["ciao"] = "hello";// Set break point at this line.
+ ss["casa"] = "house";
+ ss["gatto"] = "cat";
+ ss["a Mac.."] = "..is always a Mac!";
+
+ ss.clear();// Set break point at this line.
+
+ return 0;// Set break point at this line.
+} \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/Makefile
new file mode 100644
index 000000000000..7fe01d004f03
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/Makefile
@@ -0,0 +1,15 @@
+LEVEL = ../../../../../make
+
+CXX_SOURCES := main.cpp
+
+CFLAGS_EXTRAS += -O0
+USE_LIBSTDCPP := 1
+
+# clang-3.5+ outputs FullDebugInfo by default for Darwin/FreeBSD
+# targets. Other targets do not, which causes this test to fail.
+# This flag enables FullDebugInfo for all targets.
+ifneq (,$(findstring clang,$(CC)))
+ CFLAGS_EXTRAS += -fno-limit-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/TestDataFormatterStdString.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/TestDataFormatterStdString.py
new file mode 100644
index 000000000000..2d6af24c6afc
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/TestDataFormatterStdString.py
@@ -0,0 +1,66 @@
+#coding=utf8
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class StdStringDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ @skipIfWindows # libstdcpp not ported to Windows
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ var_s = self.frame().FindVariable('s')
+ var_S = self.frame().FindVariable('S')
+ var_mazeltov = self.frame().FindVariable('mazeltov')
+ var_q = self.frame().FindVariable('q')
+ var_Q = self.frame().FindVariable('Q')
+
+ self.assertTrue(var_s.GetSummary() == 'L"hello world! מזל טוב!"', "s summary wrong")
+ self.assertTrue(var_S.GetSummary() == 'L"!!!!"', "S summary wrong")
+ self.assertTrue(var_mazeltov.GetSummary() == 'L"מזל טוב"', "mazeltov summary wrong")
+ self.assertTrue(var_q.GetSummary() == '"hello world"', "q summary wrong")
+ self.assertTrue(var_Q.GetSummary() == '"quite a long std::strin with lots of info inside it"', "Q summary wrong")
+
+ self.runCmd("next")
+
+ self.assertTrue(var_S.GetSummary() == 'L"!!!!!"', "new S summary wrong")
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/main.cpp
new file mode 100644
index 000000000000..4a9b4fc7d0db
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/string/main.cpp
@@ -0,0 +1,12 @@
+#include <string>
+
+int main()
+{
+ std::wstring s(L"hello world! מזל טוב!");
+ std::wstring S(L"!!!!");
+ const wchar_t *mazeltov = L"מזל טוב";
+ std::string q("hello world");
+ std::string Q("quite a long std::strin with lots of info inside it");
+ S.assign(L"!!!!!"); // Set break point at this line.
+ return 0;
+} \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/Makefile
new file mode 100644
index 000000000000..2e8bcb9079bd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../../../../make
+
+CXX_SOURCES := main.cpp
+
+CFLAGS_EXTRAS += -O0
+USE_LIBSTDCPP := 1
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/TestDataFormatterStdVBool.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/TestDataFormatterStdVBool.py
new file mode 100644
index 000000000000..9e73009aba83
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/TestDataFormatterStdVBool.py
@@ -0,0 +1,58 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class StdVBoolDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ @expectedFailureFreeBSD("llvm.org/pr20548") # fails to build on lab.llvm.org buildbot
+ @expectedFailureIcc # llvm.org/pr15301: lldb does not print the correct sizes of STL containers when building with ICC
+ @skipIfWindows # libstdcpp not ported to Windows.
+ @skipIfDarwin
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.expect("frame variable vBool",
+ substrs = ['size=49','[0] = false','[1] = true','[18] = false','[27] = true','[36] = false','[47] = true','[48] = true'])
+
+ self.expect("expr vBool",
+ substrs = ['size=49','[0] = false','[1] = true','[18] = false','[27] = true','[36] = false','[47] = true','[48] = true'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/main.cpp
new file mode 100644
index 000000000000..73956dd3fda3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vbool/main.cpp
@@ -0,0 +1,63 @@
+#include <vector>
+
+int main()
+{
+ std::vector<bool> vBool;
+
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(false);
+ vBool.push_back(true);
+ vBool.push_back(true);
+
+ return 0; // Set break point at this line.
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/Makefile
new file mode 100644
index 000000000000..88cb026aba1c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/Makefile
@@ -0,0 +1,15 @@
+LEVEL = ../../../../../make
+
+CXX_SOURCES := main.cpp
+
+CXXFLAGS := -O0
+USE_LIBSTDCPP := 1
+
+# clang-3.5+ outputs FullDebugInfo by default for Darwin/FreeBSD
+# targets. Other targets do not, which causes this test to fail.
+# This flag enables FullDebugInfo for all targets.
+ifneq (,$(findstring clang,$(CC)))
+ CFLAGS_EXTRAS += -fno-limit-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/TestDataFormatterStdVector.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/TestDataFormatterStdVector.py
new file mode 100644
index 000000000000..ed4313657e93
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/TestDataFormatterStdVector.py
@@ -0,0 +1,207 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class StdVectorDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ @skipIfFreeBSD
+ @expectedFailureIcc # llvm.org/pr15301 LLDB prints incorrect sizes of STL containers
+ @skipIfWindows # libstdcpp not ported to Windows
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_source_regexp (self, "Set break point at this line.")
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ # empty vectors (and storage pointers SHOULD BOTH BE NULL..)
+ self.expect("frame variable numbers",
+ substrs = ['numbers = size=0'])
+
+ self.runCmd("c")
+
+ # first value added
+ self.expect("frame variable numbers",
+ substrs = ['numbers = size=1',
+ '[0] = 1',
+ '}'])
+
+ # add some more data
+ self.runCmd("c");
+
+ self.expect("frame variable numbers",
+ substrs = ['numbers = size=4',
+ '[0] = 1',
+ '[1] = 12',
+ '[2] = 123',
+ '[3] = 1234',
+ '}'])
+
+ self.expect("p numbers",
+ substrs = ['$', 'size=4',
+ '[0] = 1',
+ '[1] = 12',
+ '[2] = 123',
+ '[3] = 1234',
+ '}'])
+
+
+ # check access to synthetic children
+ self.runCmd("type summary add --summary-string \"item 0 is ${var[0]}\" std::int_vect int_vect")
+ self.expect('frame variable numbers',
+ substrs = ['item 0 is 1']);
+
+ self.runCmd("type summary add --summary-string \"item 0 is ${svar[0]}\" std::int_vect int_vect")
+ #import time
+ #time.sleep(19)
+ self.expect('frame variable numbers',
+ substrs = ['item 0 is 1']);
+ # move on with synths
+ self.runCmd("type summary delete std::int_vect")
+ self.runCmd("type summary delete int_vect")
+
+ # add some more data
+ self.runCmd("c");
+
+ self.expect("frame variable numbers",
+ substrs = ['numbers = size=7',
+ '[0] = 1',
+ '[1] = 12',
+ '[2] = 123',
+ '[3] = 1234',
+ '[4] = 12345',
+ '[5] = 123456',
+ '[6] = 1234567',
+ '}'])
+
+ self.expect("p numbers",
+ substrs = ['$', 'size=7',
+ '[0] = 1',
+ '[1] = 12',
+ '[2] = 123',
+ '[3] = 1234',
+ '[4] = 12345',
+ '[5] = 123456',
+ '[6] = 1234567',
+ '}'])
+
+ # check access-by-index
+ self.expect("frame variable numbers[0]",
+ substrs = ['1']);
+ self.expect("frame variable numbers[1]",
+ substrs = ['12']);
+ self.expect("frame variable numbers[2]",
+ substrs = ['123']);
+ self.expect("frame variable numbers[3]",
+ substrs = ['1234']);
+
+ # but check that expression does not rely on us
+ # (when expression gets to call into STL code correctly, we will have to find
+ # another way to check this)
+ self.expect("expression numbers[6]", matching=False, error=True,
+ substrs = ['1234567'])
+
+ # check that MightHaveChildren() gets it right
+ self.assertTrue(self.frame().FindVariable("numbers").MightHaveChildren(), "numbers.MightHaveChildren() says False for non empty!")
+
+ # clear out the vector and see that we do the right thing once again
+ self.runCmd("c")
+
+ self.expect("frame variable numbers",
+ substrs = ['numbers = size=0'])
+
+ self.runCmd("c")
+
+ # first value added
+ self.expect("frame variable numbers",
+ substrs = ['numbers = size=1',
+ '[0] = 7',
+ '}'])
+
+ # check if we can display strings
+ self.runCmd("c")
+
+ self.expect("frame variable strings",
+ substrs = ['goofy',
+ 'is',
+ 'smart'])
+
+ self.expect("p strings",
+ substrs = ['goofy',
+ 'is',
+ 'smart'])
+
+ # test summaries based on synthetic children
+ self.runCmd("type summary add std::string_vect string_vect --summary-string \"vector has ${svar%#} items\" -e")
+ self.expect("frame variable strings",
+ substrs = ['vector has 3 items',
+ 'goofy',
+ 'is',
+ 'smart'])
+
+ self.expect("p strings",
+ substrs = ['vector has 3 items',
+ 'goofy',
+ 'is',
+ 'smart'])
+
+ self.runCmd("c");
+
+ self.expect("frame variable strings",
+ substrs = ['vector has 4 items'])
+
+ # check access-by-index
+ self.expect("frame variable strings[0]",
+ substrs = ['goofy']);
+ self.expect("frame variable strings[1]",
+ substrs = ['is']);
+
+ # but check that expression does not rely on us
+ # (when expression gets to call into STL code correctly, we will have to find
+ # another way to check this)
+ self.expect("expression strings[0]", matching=False, error=True,
+ substrs = ['goofy'])
+
+ # check that MightHaveChildren() gets it right
+ self.assertTrue(self.frame().FindVariable("strings").MightHaveChildren(), "strings.MightHaveChildren() says False for non empty!")
+
+ self.runCmd("c")
+
+ self.expect("frame variable strings",
+ substrs = ['vector has 0 items'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/main.cpp
new file mode 100644
index 000000000000..010917995e40
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-stl/libstdcpp/vector/main.cpp
@@ -0,0 +1,31 @@
+#include <string>
+#include <vector>
+typedef std::vector<int> int_vect;
+typedef std::vector<std::string> string_vect;
+
+int main()
+{
+ int_vect numbers;
+ numbers.push_back(1); // Set break point at this line.
+ numbers.push_back(12); // Set break point at this line.
+ numbers.push_back(123);
+ numbers.push_back(1234);
+ numbers.push_back(12345); // Set break point at this line.
+ numbers.push_back(123456);
+ numbers.push_back(1234567);
+
+ numbers.clear(); // Set break point at this line.
+
+ numbers.push_back(7); // Set break point at this line.
+
+ string_vect strings; // Set break point at this line.
+ strings.push_back(std::string("goofy"));
+ strings.push_back(std::string("is"));
+ strings.push_back(std::string("smart"));
+
+ strings.push_back(std::string("!!!")); // Set break point at this line.
+
+ strings.clear(); // Set break point at this line.
+
+ return 0;// Set break point at this line.
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/Makefile
new file mode 100644
index 000000000000..04f39271f0cd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/Makefile
@@ -0,0 +1,12 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+# clang-3.5+ outputs FullDebugInfo by default for Darwin/FreeBSD
+# targets. Other targets do not, which causes this test to fail.
+# This flag enables FullDebugInfo for all targets.
+ifneq (,$(findstring clang,$(CC)))
+ CFLAGS_EXTRAS += -fno-limit-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/TestDataFormatterSynth.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/TestDataFormatterSynth.py
new file mode 100644
index 000000000000..8cebf20ddd2a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/TestDataFormatterSynth.py
@@ -0,0 +1,205 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class SynthDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ # Pick some values and check that the basics work
+ self.runCmd("type filter add BagOfInts --child x --child z")
+ self.expect("frame variable int_bag",
+ substrs = ['x = 6',
+ 'z = 8'])
+
+ # Check we can still access the missing child by summary
+ self.runCmd("type summary add BagOfInts --summary-string \"y=${var.y}\"")
+ self.expect('frame variable int_bag',
+ substrs = ['y=7'])
+
+ # Even if we have synth children, the summary prevails
+ self.expect("frame variable int_bag", matching=False,
+ substrs = ['x = 6',
+ 'z = 8'])
+
+ # if we skip synth and summary show y
+ self.expect("frame variable int_bag --synthetic-type false --no-summary-depth=1",
+ substrs = ['x = 6',
+ 'y = 7',
+ 'z = 8'])
+
+ # if we ask for raw output same happens
+ self.expect("frame variable int_bag --raw-output",
+ substrs = ['x = 6',
+ 'y = 7',
+ 'z = 8'])
+
+ # Summary+Synth must work together
+ self.runCmd("type summary add BagOfInts --summary-string \"x=${var.x}\" -e")
+ self.expect('frame variable int_bag',
+ substrs = ['x=6',
+ 'x = 6',
+ 'z = 8'])
+
+ # Same output, but using Python
+ self.runCmd("type summary add BagOfInts --python-script \"return 'x=%s' % valobj.GetChildMemberWithName('x').GetValue()\" -e")
+ self.expect('frame variable int_bag',
+ substrs = ['x=6',
+ 'x = 6',
+ 'z = 8'])
+
+ # If I skip summaries, still give me the artificial children
+ self.expect("frame variable int_bag --no-summary-depth=1",
+ substrs = ['x = 6',
+ 'z = 8'])
+
+ # Delete synth and check that the view reflects it immediately
+ self.runCmd("type filter delete BagOfInts")
+ self.expect("frame variable int_bag",
+ substrs = ['x = 6',
+ 'y = 7',
+ 'z = 8'])
+
+ # Add the synth again and check that it's honored deeper in the hierarchy
+ self.runCmd("type filter add BagOfInts --child x --child z")
+ self.expect('frame variable bag_bag',
+ substrs = ['x = x=69 {',
+ 'x = 69',
+ 'z = 71',
+ 'y = x=66 {',
+ 'x = 66',
+ 'z = 68'])
+ self.expect('frame variable bag_bag', matching=False,
+ substrs = ['y = 70',
+ 'y = 67'])
+
+ # Check that a synth can expand nested stuff
+ self.runCmd("type filter add BagOfBags --child x.y --child y.z")
+ self.expect('frame variable bag_bag',
+ substrs = ['x.y = 70',
+ 'y.z = 68'])
+
+ # ...even if we get -> and . wrong
+ self.runCmd("type filter add BagOfBags --child x.y --child \"y->z\"")
+ self.expect('frame variable bag_bag',
+ substrs = ['x.y = 70',
+ 'y->z = 68'])
+
+ # ...even bitfields
+ self.runCmd("type filter add BagOfBags --child x.y --child \"y->z[1-2]\"")
+ self.expect('frame variable bag_bag --show-types',
+ substrs = ['x.y = 70',
+ '(int:2) y->z[1-2] = 2'])
+
+ # ...even if we format the bitfields
+ self.runCmd("type filter add BagOfBags --child x.y --child \"y->y[0-0]\"")
+ self.runCmd("type format add \"int:1\" -f bool")
+ self.expect('frame variable bag_bag --show-types',
+ substrs = ['x.y = 70',
+ '(int:1) y->y[0-0] = true'])
+
+ # ...even if we use one-liner summaries
+ self.runCmd("type summary add -c BagOfBags")
+ self.expect('frame variable bag_bag',
+ substrs = ['(BagOfBags) bag_bag = (x.y = 70, y->y[0-0] = true)'])
+
+ self.runCmd("type summary delete BagOfBags")
+
+ # now check we are dynamic (and arrays work)
+ self.runCmd("type filter add Plenty --child bitfield --child array[0] --child array[2]")
+ self.expect('frame variable plenty_of_stuff',
+ substrs = ['bitfield = 1',
+ 'array[0] = 5',
+ 'array[2] = 3'])
+
+ self.runCmd("n")
+ self.expect('frame variable plenty_of_stuff',
+ substrs = ['bitfield = 17',
+ 'array[0] = 5',
+ 'array[2] = 3'])
+
+ # skip synthetic children
+ self.expect('frame variable plenty_of_stuff --synthetic-type no',
+ substrs = ['some_values = 0x',
+ 'array = 0x',
+ 'array_size = 5'])
+
+
+ # check flat printing with synthetic children
+ self.expect('frame variable plenty_of_stuff --flat',
+ substrs = ['plenty_of_stuff.bitfield = 17',
+ '*(plenty_of_stuff.array) = 5',
+ '*(plenty_of_stuff.array) = 3'])
+
+ # check that we do not lose location information for our children
+ self.expect('frame variable plenty_of_stuff --location',
+ substrs = ['0x',
+ ': bitfield = 17'])
+
+ # check we work across pointer boundaries
+ self.expect('frame variable plenty_of_stuff.some_values --ptr-depth=1',
+ substrs = ['(BagOfInts *) plenty_of_stuff.some_values',
+ 'x = 5',
+ 'z = 7'])
+
+ # but not if we don't want to
+ self.runCmd("type filter add BagOfInts --child x --child z -p")
+ self.expect('frame variable plenty_of_stuff.some_values --ptr-depth=1',
+ substrs = ['(BagOfInts *) plenty_of_stuff.some_values',
+ 'x = 5',
+ 'y = 6',
+ 'z = 7'])
+
+ # check we're dynamic even if nested
+ self.runCmd("type filter add BagOfBags --child x.z")
+ self.expect('frame variable bag_bag',
+ substrs = ['x.z = 71'])
+
+ self.runCmd("n")
+ self.expect('frame variable bag_bag',
+ substrs = ['x.z = 12'])
+
+ self.runCmd('type summary add -e -s "I am always empty but have" EmptyStruct')
+ self.expect('frame variable es', substrs = ["I am always empty but have {}"])
+ self.runCmd('type summary add -e -h -s "I am really empty" EmptyStruct')
+ self.expect('frame variable es', substrs = ["I am really empty"])
+ self.expect('frame variable es', substrs = ["I am really empty {}"], matching=False)
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/main.cpp
new file mode 100644
index 000000000000..bac38d84fae3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synth/main.cpp
@@ -0,0 +1,86 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+
+struct BagOfInts
+{
+ int x;
+ int y;
+ int z;
+ BagOfInts(int X) :
+ x(X),
+ y(X+1),
+ z(X+2) {}
+};
+
+struct BagOfFloats
+{
+ float x;
+ float y;
+ float z;
+ BagOfFloats(float X) :
+ x(X+0.334),
+ y(X+0.500),
+ z(X+0.667) {}
+};
+
+struct BagOfBags
+{
+ BagOfInts x;
+ BagOfInts y;
+ BagOfFloats z;
+ BagOfFloats q;
+ BagOfBags() :
+ x('E'),
+ y('B'),
+ z(1.1),
+ q(20.11) {}
+};
+
+struct EmptyStruct {};
+
+struct Plenty
+{
+ BagOfInts *some_values;
+ int* array;
+ int array_size;
+ int bitfield;
+
+ Plenty(int N, bool flagA, bool flagB) :
+ some_values(new BagOfInts(N)),
+ array(new int[N]),
+ array_size(N),
+ bitfield( (flagA ? 0x01 : 0x00) | (flagB ? 0x10 : 0x00) )
+ {
+ for (int j = 0; j < N; j++)
+ array[j] = N-j;
+ }
+};
+
+int main (int argc, const char * argv[])
+{
+ BagOfInts int_bag(6);
+ BagOfFloats float_bag(2.71);
+
+ BagOfBags bag_bag;
+ EmptyStruct es;
+
+ Plenty plenty_of_stuff(5,true,false);
+
+ plenty_of_stuff.bitfield = 0x11; // Set break point at this line.
+
+ bag_bag.x.z = 12;
+
+ return 0;
+
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/TestDataFormatterSynthVal.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/TestDataFormatterSynthVal.py
new file mode 100644
index 000000000000..8d6e5df37a5c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/TestDataFormatterSynthVal.py
@@ -0,0 +1,96 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class DataFormatterSynthValueTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', 'break here')
+
+ @skipIfFreeBSD # llvm.org/pr20545 bogus output confuses buildbot parser
+ @expectedFailureWindows("llvm.org/pr24462") # Data formatters have problems on Windows
+ def test_with_run_command(self):
+ """Test using Python synthetic children provider to provide a value."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ x = self.frame().FindVariable("x")
+ x.SetPreferSyntheticValue(True)
+ y = self.frame().FindVariable("y")
+ y.SetPreferSyntheticValue(True)
+ z = self.frame().FindVariable("z")
+ z.SetPreferSyntheticValue(True)
+
+ x_val = x.GetValueAsUnsigned
+ y_val = y.GetValueAsUnsigned
+ z_val = z.GetValueAsUnsigned
+
+ if self.TraceOn():
+ print("x_val = %s; y_val = %s; z_val = %s" % (x_val(),y_val(),z_val()))
+
+ self.assertFalse(x_val() == 3, "x == 3 before synthetics")
+ self.assertFalse(y_val() == 4, "y == 4 before synthetics")
+ self.assertFalse(z_val() == 7, "z == 7 before synthetics")
+
+ # now set up the synth
+ self.runCmd("script from myIntSynthProvider import *")
+ self.runCmd("type synth add -l myIntSynthProvider myInt")
+ self.runCmd("type synth add -l myArraySynthProvider myArray")
+
+ if self.TraceOn():
+ print("x_val = %s; y_val = %s; z_val = %s" % (x_val(),y_val(),z_val()))
+
+ self.assertTrue(x_val() == 3, "x != 3 after synthetics")
+ self.assertTrue(y_val() == 4, "y != 4 after synthetics")
+ self.assertTrue(z_val() == 7, "z != 7 after synthetics")
+
+ self.expect("frame variable x", substrs=['3'])
+ self.expect("frame variable x", substrs=['theValue = 3'], matching=False)
+
+ # check that an aptly defined synthetic provider does not affect one-lining
+ self.expect("expression struct S { myInt theInt{12}; }; S()", substrs = ['(theInt = 12)'])
+
+ # check that we can use a synthetic value in a summary
+ self.runCmd("type summary add hasAnInt -s ${var.theInt}")
+ hi = self.frame().FindVariable("hi")
+ self.assertEqual(hi.GetSummary(), "42")
+
+ ma = self.frame().FindVariable("ma")
+ self.assertTrue(ma.IsValid())
+ self.assertEqual(ma.GetNumChildren(15), 15)
+ self.assertEqual(ma.GetNumChildren(16), 16)
+ self.assertEqual(ma.GetNumChildren(17), 16)
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/main.cpp
new file mode 100644
index 000000000000..accbf0a5a578
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/main.cpp
@@ -0,0 +1,29 @@
+class myInt {
+ private: int theValue;
+ public: myInt() : theValue(0) {}
+ public: myInt(int _x) : theValue(_x) {}
+ int val() { return theValue; }
+};
+
+class myArray {
+public:
+ int array[16];
+};
+
+class hasAnInt {
+ public:
+ myInt theInt;
+ hasAnInt() : theInt(42) {}
+};
+
+myInt operator + (myInt x, myInt y) { return myInt(x.val() + y.val()); }
+
+int main() {
+ myInt x{3};
+ myInt y{4};
+ myInt z {x+y};
+ hasAnInt hi;
+ myArray ma;
+
+ return z.val(); // break here
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/myIntSynthProvider.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/myIntSynthProvider.py
new file mode 100644
index 000000000000..c8517a442932
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/data-formatter-synthval/myIntSynthProvider.py
@@ -0,0 +1,36 @@
+class myIntSynthProvider(object):
+ def __init__(self, valobj, dict):
+ self.valobj = valobj;
+ self.val = self.valobj.GetChildMemberWithName("theValue")
+ def num_children(self):
+ return 0;
+ def get_child_at_index(self, index):
+ return None
+ def get_child_index(self, name):
+ return None
+ def update(self):
+ return False
+ def has_children(self):
+ return False
+ def get_value(self):
+ return self.val
+
+
+class myArraySynthProvider(object):
+ def __init__(self, valobj, dict):
+ self.valobj = valobj
+ self.array = self.valobj.GetChildMemberWithName("array")
+
+ def num_children(self, max_count):
+ if 16 < max_count:
+ return 16
+ return max_count
+
+ def get_child_at_index(self, index):
+ return None # Keep it simple when this is not tested here.
+
+ def get_child_index(self, name):
+ return None # Keep it simple when this is not tested here.
+
+ def has_children(self):
+ return True
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/Makefile
new file mode 100644
index 000000000000..69dde1b76184
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/Makefile
@@ -0,0 +1,12 @@
+LEVEL = ../../../make
+CXX_SOURCES := main.cpp
+CXXFLAGS += -std=c++11
+
+# clang-3.5+ outputs FullDebugInfo by default for Darwin/FreeBSD
+# targets. Other targets do not, which causes this test to fail.
+# This flag enables FullDebugInfo for all targets.
+ifneq (,$(findstring clang,$(CC)))
+ CFLAGS_EXTRAS += -fno-limit-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/TestDumpDynamic.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/TestDumpDynamic.py
new file mode 100644
index 000000000000..8ae09d691940
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/TestDumpDynamic.py
@@ -0,0 +1,5 @@
+from __future__ import absolute_import
+
+from lldbsuite.test import lldbinline
+
+lldbinline.MakeInlineTest(__file__, globals(), [lldbinline.expectedFailureWindows("llvm.org/pr24663")])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/main.cpp
new file mode 100644
index 000000000000..bc8e05829316
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/dump_dynamic/main.cpp
@@ -0,0 +1,35 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+class Base {
+public:
+ Base () = default;
+ virtual int func() { return 1; }
+ virtual ~Base() = default;
+};
+
+class Derived : public Base {
+private:
+ int m_derived_data;
+public:
+ Derived () : Base(), m_derived_data(0x0fedbeef) {}
+ virtual ~Derived() = default;
+ virtual int func() { return m_derived_data; }
+};
+
+int main (int argc, char const *argv[])
+{
+ Base *base = new Derived();
+ return 0; //% stream = lldb.SBStream()
+ //% base = self.frame().FindVariable("base")
+ //% base.SetPreferDynamicValue(lldb.eDynamicDontRunTarget)
+ //% base.GetDescription(stream)
+ //% if self.TraceOn(): print(stream.GetData())
+ //% self.assertTrue(stream.GetData().startswith("(Derived *"))
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/TestFormatPropagation.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/TestFormatPropagation.py
new file mode 100644
index 000000000000..5cb7c82c9e09
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/TestFormatPropagation.py
@@ -0,0 +1,75 @@
+"""
+Check if changing Format on an SBValue correctly propagates that new format to children as it should
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class FormatPropagationTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ # rdar://problem/14035604
+ def test_with_run_command(self):
+ """Check for an issue where capping does not work because the Target pointer appears to be changing behind our backs."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ pass
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ # extract the parent and the children
+ frame = self.frame()
+ parent = self.frame().FindVariable("f")
+ self.assertTrue(parent != None and parent.IsValid(),"could not find f")
+ X = parent.GetChildMemberWithName("X")
+ self.assertTrue(X != None and X.IsValid(),"could not find X")
+ Y = parent.GetChildMemberWithName("Y")
+ self.assertTrue(Y != None and Y.IsValid(),"could not find Y")
+ # check their values now
+ self.assertTrue(X.GetValue() == "1", "X has an invalid value")
+ self.assertTrue(Y.GetValue() == "2", "Y has an invalid value")
+ # set the format on the parent
+ parent.SetFormat(lldb.eFormatHex)
+ self.assertTrue(X.GetValue() == "0x00000001", "X has not changed format")
+ self.assertTrue(Y.GetValue() == "0x00000002", "Y has not changed format")
+ # Step and check if the values make sense still
+ self.runCmd("next")
+ self.assertTrue(X.GetValue() == "0x00000004", "X has not become 4")
+ self.assertTrue(Y.GetValue() == "0x00000002", "Y has not stuck as hex")
+ # Check that children can still make their own choices
+ Y.SetFormat(lldb.eFormatDecimal)
+ self.assertTrue(X.GetValue() == "0x00000004", "X is still hex")
+ self.assertTrue(Y.GetValue() == "2", "Y has not been reset")
+ # Make a few more changes
+ parent.SetFormat(lldb.eFormatDefault)
+ X.SetFormat(lldb.eFormatHex)
+ Y.SetFormat(lldb.eFormatDefault)
+ self.assertTrue(X.GetValue() == "0x00000004", "X is not hex as it asked")
+ self.assertTrue(Y.GetValue() == "2", "Y is not defaulted")
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/main.cpp
new file mode 100644
index 000000000000..5822fbc2a710
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/format-propagation/main.cpp
@@ -0,0 +1,13 @@
+struct foo
+{
+ int X;
+ int Y;
+ foo(int a, int b) : X(a), Y(b) {}
+};
+
+int main()
+{
+ foo f(1,2);
+ f.X = 4; // Set break point at this line.
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/TestFrameFormatSmallStruct.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/TestFrameFormatSmallStruct.py
new file mode 100644
index 000000000000..555351998c2d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/TestFrameFormatSmallStruct.py
@@ -0,0 +1,38 @@
+"""
+Test that the user can input a format but it will not prevail over summary format's choices.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class FrameFormatSmallStructTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def test_with_run_command(self):
+ """Test that the user can input a format but it will not prevail over summary format's choices."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ self.expect("thread list", substrs = ['addPair(p=(x = 3, y = -3))'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/main.cpp
new file mode 100644
index 000000000000..120ef0ea0910
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/frameformat_smallstruct/main.cpp
@@ -0,0 +1,25 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+struct Pair {
+ int x;
+ int y;
+
+ Pair(int _x, int _y) : x(_x), y(_y) {}
+};
+
+int addPair(Pair p)
+{
+ return p.x + p.y; // Set break point at this line.
+}
+
+int main() {
+ Pair p1(3,-3);
+ return addPair(p1);
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/TestDataFormatterHexCaps.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/TestDataFormatterHexCaps.py
new file mode 100644
index 000000000000..3c28b68056f5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/TestDataFormatterHexCaps.py
@@ -0,0 +1,82 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class DataFormatterHexCapsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format delete hex', check=False)
+ self.runCmd('type summary clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.runCmd("type format add -f uppercase int")
+
+ self.expect('frame variable mine',
+ substrs = ['mine = ',
+ 'first = 0x001122AA', 'second = 0x1122BB44'])
+
+ self.runCmd("type format add -f hex int")
+
+ self.expect('frame variable mine',
+ substrs = ['mine = ',
+ 'first = 0x001122aa', 'second = 0x1122bb44'])
+
+ self.runCmd("type format delete int")
+
+ self.runCmd("type summary add -s \"${var.first%X} and ${var.second%x}\" foo")
+
+ self.expect('frame variable mine',
+ substrs = ['(foo) mine = 0x001122AA and 0x1122bb44'])
+
+ self.runCmd("type summary add -s \"${var.first%X} and ${var.second%X}\" foo")
+ self.runCmd("next")
+ self.runCmd("next")
+ self.expect('frame variable mine',
+ substrs = ['(foo) mine = 0xAABBCCDD and 0x1122BB44'])
+
+ self.runCmd("type summary add -s \"${var.first%x} and ${var.second%X}\" foo")
+ self.expect('frame variable mine',
+ substrs = ['(foo) mine = 0xaabbccdd and 0x1122BB44'])
+ self.runCmd("next")
+ self.runCmd("next")
+ self.runCmd("type summary add -s \"${var.first%x} and ${var.second%x}\" foo")
+ self.expect('frame variable mine',
+ substrs = ['(foo) mine = 0xaabbccdd and 0xff00ff00'])
+ self.runCmd("type summary add -s \"${var.first%X} and ${var.second%X}\" foo")
+ self.expect('frame variable mine',
+ substrs = ['(foo) mine = 0xAABBCCDD and 0xFF00FF00'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/main.cpp
new file mode 100644
index 000000000000..5ee113c17b28
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/hexcaps/main.cpp
@@ -0,0 +1,28 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+
+struct foo
+{
+ int first;
+ int second;
+};
+
+int main ()
+{
+ struct foo mine = {0x001122AA, 0x1122BB44};
+ printf("main.first = 0x%8.8x, main.second = 0x%8.8x\n", mine.first, mine.second);
+ mine.first = 0xAABBCCDD; // Set break point at this line.
+ printf("main.first = 0x%8.8x, main.second = 0x%8.8x\n", mine.first, mine.second);
+ mine.second = 0xFF00FF00;
+ printf("main.first = 0x%8.8x, main.second = 0x%8.8x\n", mine.first, mine.second);
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/TestDataFormatterLanguageCategoryUpdates.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/TestDataFormatterLanguageCategoryUpdates.py
new file mode 100644
index 000000000000..b7562c4336a6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/TestDataFormatterLanguageCategoryUpdates.py
@@ -0,0 +1,60 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class LanguageCategoryUpdatesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// break here')
+
+ @expectedFailureWindows("llvm.org/pr24462") # Data formatters have problems on Windows
+ def test_with_run_command(self):
+ """Test that LLDB correctly cleans caches when language categories change."""
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ if hasattr(self, 'type_category') and hasattr(self, 'type_specifier'):
+ self.type_category.DeleteTypeSummary(self.type_specifier)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ self.expect("frame variable", substrs = ['(S)', 'object', '123', '456'], matching=True)
+
+ self.type_category = self.dbg.GetCategory(lldb.eLanguageTypeC_plus_plus)
+ type_summary = lldb.SBTypeSummary.CreateWithSummaryString("this is an object of type S")
+ self.type_specifier = lldb.SBTypeNameSpecifier('S')
+ self.type_category.AddTypeSummary(self.type_specifier, type_summary)
+
+ self.expect("frame variable", substrs = ['this is an object of type S'], matching=True)
+
+ self.type_category.DeleteTypeSummary(self.type_specifier)
+ self.expect("frame variable", substrs = ['this is an object of type S'], matching=False)
+ self.expect("frame variable", substrs = ['(S)', 'object', '123', '456'], matching=True)
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/main.cpp
new file mode 100644
index 000000000000..ac77e537b80a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/language_category_updates/main.cpp
@@ -0,0 +1,20 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+struct S {
+ int x;
+ int y;
+
+ S() : x(123), y(456) {}
+};
+
+int main() {
+ S object;
+ return 0; // break here
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/Makefile
new file mode 100644
index 000000000000..9f7fb1ca6231
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+
+CFLAGS_EXTRAS += -w
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/TestNSArraySynthetic.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/TestNSArraySynthetic.py
new file mode 100644
index 000000000000..a12f9c841a7f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/TestNSArraySynthetic.py
@@ -0,0 +1,67 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import datetime
+import lldbsuite.test.lldbutil as lldbutil
+
+class NSArraySyntheticTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.m', '// Set break point at this line.')
+
+ @skipUnlessDarwin
+ def test_rdar11086338_with_run_command(self):
+ """Test that NSArray reports its synthetic children properly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type synth clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ # Now check that we are displaying Cocoa classes correctly
+ self.expect('frame variable arr',
+ substrs = ['@"6 elements"'])
+ self.expect('frame variable other_arr',
+ substrs = ['@"4 elements"'])
+ self.expect('frame variable arr --ptr-depth 1',
+ substrs = ['@"6 elements"','[0] = 0x','[1] = 0x','[2] = 0x','[3] = 0x','[4] = 0x','[5] = 0x'])
+ self.expect('frame variable other_arr --ptr-depth 1',
+ substrs = ['@"4 elements"','[0] = 0x','[1] = 0x','[2] = 0x','[3] = 0x'])
+ self.expect('frame variable arr --ptr-depth 1 -d no-run-target',
+ substrs = ['@"6 elements"','@"hello"','@"world"','@"this"','@"is"','@"me"','@"http://www.apple.com'])
+ self.expect('frame variable other_arr --ptr-depth 1 -d no-run-target',
+ substrs = ['@"4 elements"','(int)5','@"a string"','@"6 elements"'])
+ self.expect('frame variable other_arr --ptr-depth 2 -d no-run-target',
+ substrs = ['@"4 elements"','@"6 elements" {','@"hello"','@"world"','@"this"','@"is"','@"me"','@"http://www.apple.com'])
+
+ self.assertTrue(self.frame().FindVariable("arr").MightHaveChildren(), "arr says it does not have children!")
+ self.assertTrue(self.frame().FindVariable("other_arr").MightHaveChildren(), "arr says it does not have children!")
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/main.m b/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/main.m
new file mode 100644
index 000000000000..1b4a6e03857a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/nsarraysynth/main.m
@@ -0,0 +1,35 @@
+//===-- main.m ------------------------------------------------*- ObjC -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#import <Foundation/Foundation.h>
+
+int main (int argc, const char * argv[])
+{
+
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+
+
+ NSMutableArray* arr = [[NSMutableArray alloc] init];
+ [arr addObject:@"hello"];
+ [arr addObject:@"world"];
+ [arr addObject:@"this"];
+ [arr addObject:@"is"];
+ [arr addObject:@"me"];
+ [arr addObject:[NSURL URLWithString:@"http://www.apple.com/"]];
+
+ NSDate *aDate = [NSDate distantFuture];
+ NSValue *aValue = [NSNumber numberWithInt:5];
+ NSString *aString = @"a string";
+
+ NSArray *other_arr = [NSArray arrayWithObjects:aDate, aValue, aString, arr, nil];
+
+ [pool drain];// Set break point at this line.
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/Makefile
new file mode 100644
index 000000000000..9f7fb1ca6231
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+
+CFLAGS_EXTRAS += -w
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/TestNSDictionarySynthetic.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/TestNSDictionarySynthetic.py
new file mode 100644
index 000000000000..13d493ecbdcc
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/TestNSDictionarySynthetic.py
@@ -0,0 +1,69 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import datetime
+import lldbsuite.test.lldbutil as lldbutil
+
+class NSDictionarySyntheticTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.m', '// Set break point at this line.')
+
+ @skipUnlessDarwin
+ def test_rdar11988289_with_run_command(self):
+ """Test that NSDictionary reports its synthetic children properly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type synth clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ # Now check that we are displaying Cocoa classes correctly
+ self.expect('frame variable dictionary',
+ substrs = ['3 key/value pairs'])
+ self.expect('frame variable mutabledict',
+ substrs = ['4 key/value pairs'])
+ self.expect('frame variable dictionary --ptr-depth 1',
+ substrs = ['3 key/value pairs','[0] = ','key = 0x','value = 0x','[1] = ','[2] = '])
+ self.expect('frame variable mutabledict --ptr-depth 1',
+ substrs = ['4 key/value pairs','[0] = ','key = 0x','value = 0x','[1] = ','[2] = ','[3] = '])
+ self.expect('frame variable dictionary --ptr-depth 1 --dynamic-type no-run-target',
+ substrs = ['3 key/value pairs','@"bar"','@"2 elements"','@"baz"','2 key/value pairs'])
+ self.expect('frame variable mutabledict --ptr-depth 1 --dynamic-type no-run-target',
+ substrs = ['4 key/value pairs','(int)23','@"123"','@"http://www.apple.com"','@"sourceofstuff"','3 key/value pairs'])
+ self.expect('frame variable mutabledict --ptr-depth 2 --dynamic-type no-run-target',
+ substrs = ['4 key/value pairs','(int)23','@"123"','@"http://www.apple.com"','@"sourceofstuff"','3 key/value pairs','@"bar"','@"2 elements"'])
+ self.expect('frame variable mutabledict --ptr-depth 3 --dynamic-type no-run-target',
+ substrs = ['4 key/value pairs','(int)23','@"123"','@"http://www.apple.com"','@"sourceofstuff"','3 key/value pairs','@"bar"','@"2 elements"','(int)1','@"two"'])
+
+ self.assertTrue(self.frame().FindVariable("dictionary").MightHaveChildren(), "dictionary says it does not have children!")
+ self.assertTrue(self.frame().FindVariable("mutabledict").MightHaveChildren(), "mutable says it does not have children!")
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/main.m b/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/main.m
new file mode 100644
index 000000000000..fdc533aeaf24
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/nsdictionarysynth/main.m
@@ -0,0 +1,30 @@
+//===-- main.m ------------------------------------------------*- ObjC -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#import <Foundation/Foundation.h>
+
+int main (int argc, const char * argv[])
+{
+
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+
+
+ NSArray* keys = @[@"foo",@"bar",@"baz"];
+ NSArray* values = @[@"hello",@[@"X",@"Y"],@{@1 : @"one",@2 : @"two"}];
+ NSDictionary* dictionary = [NSDictionary dictionaryWithObjects:values forKeys:keys];
+ NSMutableDictionary* mutabledict = [NSMutableDictionary dictionaryWithCapacity:5];
+ [mutabledict setObject:@"123" forKey:@23];
+ [mutabledict setObject:[NSURL URLWithString:@"http://www.apple.com"] forKey:@"foobar"];
+ [mutabledict setObject:@[@"a",@12] forKey:@57];
+ [mutabledict setObject:dictionary forKey:@"sourceofstuff"];
+
+ [pool drain];// Set break point at this line.
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/Makefile
new file mode 100644
index 000000000000..9f7fb1ca6231
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+
+CFLAGS_EXTRAS += -w
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/TestNSSetSynthetic.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/TestNSSetSynthetic.py
new file mode 100644
index 000000000000..6c558001bb04
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/TestNSSetSynthetic.py
@@ -0,0 +1,74 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import datetime
+import lldbsuite.test.lldbutil as lldbutil
+
+class NSSetSyntheticTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.m', '// Set break point at this line.')
+
+ @skipUnlessDarwin
+ def test_rdar12529957_with_run_command(self):
+ """Test that NSSet reports its synthetic children properly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type synth clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ # Now check that we are displaying Cocoa classes correctly
+ self.expect('frame variable set',
+ substrs = ['4 elements'])
+ self.expect('frame variable mutable',
+ substrs = ['9 elements'])
+ self.expect('frame variable set --ptr-depth 1 -d run -T',
+ substrs = ['4 elements','[0]','[1]','[2]','[3]','hello','world','(int)1','(int)2'])
+ self.expect('frame variable mutable --ptr-depth 1 -d run -T',
+ substrs = ['9 elements','(int)5','@"3 elements"','@"www.apple.com"','(int)3','@"world"','(int)4'])
+
+ self.runCmd("next")
+ self.expect('frame variable mutable',
+ substrs = ['0 elements'])
+
+ self.runCmd("next")
+ self.expect('frame variable mutable',
+ substrs = ['4 elements'])
+ self.expect('frame variable mutable --ptr-depth 1 -d run -T',
+ substrs = ['4 elements','[0]','[1]','[2]','[3]','hello','world','(int)1','(int)2'])
+
+ self.runCmd("next")
+ self.expect('frame variable mutable',
+ substrs = ['4 elements'])
+ self.expect('frame variable mutable --ptr-depth 1 -d run -T',
+ substrs = ['4 elements','[0]','[1]','[2]','[3]','hello','world','(int)1','(int)2'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/main.m b/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/main.m
new file mode 100644
index 000000000000..7bc49583606f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/nssetsynth/main.m
@@ -0,0 +1,34 @@
+//===-- main.m ------------------------------------------------*- ObjC -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#import <Foundation/Foundation.h>
+
+int main (int argc, const char * argv[])
+{
+
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+
+ NSSet* set = [NSSet setWithArray:@[@1,@"hello",@2,@"world"]];
+ NSMutableSet* mutable = [NSMutableSet setWithCapacity:5];
+ [mutable addObject:@1];
+ [mutable addObject:@2];
+ [mutable addObject:@3];
+ [mutable addObject:@4];
+ [mutable addObject:@5];
+ [mutable addObject:[NSURL URLWithString:@"www.apple.com"]];
+ [mutable addObject:@[@1,@2,@3]];
+ [mutable unionSet:set];
+ [mutable removeAllObjects]; // Set break point at this line.
+ [mutable unionSet:set];
+ [mutable addObject:@1];
+
+ [pool drain];
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/Makefile
new file mode 100644
index 000000000000..261658b10ae8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../../make
+
+OBJCXX_SOURCES := main.mm
+
+CFLAGS_EXTRAS += -w
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/TestFormattersOsType.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/TestFormattersOsType.py
new file mode 100644
index 000000000000..4fb6176e9e4f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/TestFormattersOsType.py
@@ -0,0 +1,52 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import datetime
+import lldbsuite.test.lldbutil as lldbutil
+
+class DataFormatterOSTypeTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.mm', '// Set break point at this line.')
+
+ @skipUnlessDarwin
+ def test_ostype_with_run_command(self):
+ """Test the formatters we use for OSType."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.mm", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type synth clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ # Now check that we use the right summary for OSType
+ self.expect('frame variable',
+ substrs = ["'test'","'best'"])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/main.mm b/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/main.mm
new file mode 100644
index 000000000000..8d22659374a7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/ostypeformatting/main.mm
@@ -0,0 +1,23 @@
+//===-- main.m ------------------------------------------------*- ObjC -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#import <Foundation/Foundation.h>
+
+int main (int argc, const char * argv[])
+{
+
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+
+ OSType a = 'test';
+ OSType b = 'best';
+
+ [pool drain];// Set break point at this line.
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/Makefile
new file mode 100644
index 000000000000..d85e665333ea
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+CFLAGS_EXTRAS += -std=c++11
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/TestPtrRef2Typedef.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/TestPtrRef2Typedef.py
new file mode 100644
index 000000000000..bf98559cd0c1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/TestPtrRef2Typedef.py
@@ -0,0 +1,57 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class PtrRef2TypedefTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set breakpoint here')
+
+ def test_with_run_command(self):
+ """Test that a pointer/reference to a typedef is formatted as we want."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.runCmd('type summary add --cascade true -s "IntPointer" "int *"')
+ self.runCmd('type summary add --cascade true -s "IntLRef" "int &"')
+ self.runCmd('type summary add --cascade true -s "IntRRef" "int &&"')
+
+ self.expect("frame variable x", substrs = ['(Foo *) x = 0x','IntPointer'])
+ # note: Ubuntu 12.04 x86_64 build with gcc 4.8.2 is getting a
+ # const after the ref that isn't showing up on FreeBSD. This
+ # tweak changes the behavior so that the const is not part of
+ # the match.
+ self.expect("frame variable y", substrs = ['(Foo &', ') y = 0x','IntLRef'])
+ self.expect("frame variable z", substrs = ['(Foo &&', ') z = 0x','IntRRef'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/main.cpp
new file mode 100644
index 000000000000..219f398da3f5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/ptr_ref_typedef/main.cpp
@@ -0,0 +1,19 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+typedef int Foo;
+
+int main() {
+ int lval = 1;
+ Foo* x = &lval;
+ Foo& y = lval;
+ Foo&& z = 1;
+ return 0; // Set breakpoint here
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/TestDataFormatterRefPtrRecursion.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/TestDataFormatterRefPtrRecursion.py
new file mode 100644
index 000000000000..13b84e9f74c7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/TestDataFormatterRefPtrRecursion.py
@@ -0,0 +1,41 @@
+"""
+Test that ValueObjectPrinter does not cause an infinite loop when a reference to a struct that contains a pointer to itself is printed.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class DataFormatterRefPtrRecursionTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def test_with_run_command(self):
+ """Test that ValueObjectPrinter does not cause an infinite loop when a reference to a struct that contains a pointer to itself is printed."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ self.expect("frame variable foo", substrs = []);
+ self.expect("frame variable foo --ptr-depth=1", substrs = ['ID = 1']);
+ self.expect("frame variable foo --ptr-depth=2", substrs = ['ID = 1']);
+ self.expect("frame variable foo --ptr-depth=3", substrs = ['ID = 1']);
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/main.cpp
new file mode 100644
index 000000000000..4b576bd266dd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/refpointer-recursion/main.cpp
@@ -0,0 +1,21 @@
+int _ID = 0;
+
+class Foo {
+ public:
+ Foo *next;
+ int ID;
+
+ Foo () : next(0), ID(++_ID) {}
+};
+
+int evalFoo(Foo& foo)
+{
+ return foo.ID; // Set break point at this line.
+}
+
+int main() {
+ Foo f;
+ f.next = &f;
+ return evalFoo(f);
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/Makefile
new file mode 100644
index 000000000000..62a57f6cd9be
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/Makefile
@@ -0,0 +1,4 @@
+LEVEL = ../../../make
+OBJC_SOURCES := main.m
+include $(LEVEL)/Makefile.rules
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/TestSetValueFromCString.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/TestSetValueFromCString.py
new file mode 100644
index 000000000000..80305e303d03
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/TestSetValueFromCString.py
@@ -0,0 +1,4 @@
+import lldbsuite.test.lldbinline as lldbinline
+import lldbsuite.test.lldbtest as lldbtest
+
+lldbinline.MakeInlineTest(__file__, globals(), [lldbtest.skipIfFreeBSD,lldbtest.skipIfLinux,lldbtest.skipIfWindows])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/main.m b/packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/main.m
new file mode 100644
index 000000000000..3dd455081007
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/setvaluefromcstring/main.m
@@ -0,0 +1,19 @@
+//===-- main.m ---------------------------------------------------*- ObjC -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#import <Foundation/Foundation.h>
+
+int main() {
+ NSDictionary* dic = @{@1 : @2};
+ NSLog(@"hello world"); //% dic = self.frame().FindVariable("dic")
+ //% dic.SetPreferSyntheticValue(True)
+ //% dic.SetPreferDynamicValue(lldb.eDynamicCanRunTarget)
+ //% dic.SetValueFromCString("12")
+ return 0; //% dic = self.frame().FindVariable("dic")
+ //% self.assertTrue(dic.GetValueAsUnsigned() == 0xC, "failed to read what I wrote")
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/Makefile
new file mode 100644
index 000000000000..69dde1b76184
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/Makefile
@@ -0,0 +1,12 @@
+LEVEL = ../../../make
+CXX_SOURCES := main.cpp
+CXXFLAGS += -std=c++11
+
+# clang-3.5+ outputs FullDebugInfo by default for Darwin/FreeBSD
+# targets. Other targets do not, which causes this test to fail.
+# This flag enables FullDebugInfo for all targets.
+ifneq (,$(findstring clang,$(CC)))
+ CFLAGS_EXTRAS += -fno-limit-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/TestStringPrinter.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/TestStringPrinter.py
new file mode 100644
index 000000000000..69f7d48c8b6c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/TestStringPrinter.py
@@ -0,0 +1,4 @@
+import lldbsuite.test.lldbinline as lldbinline
+import lldbsuite.test.lldbtest as lldbtest
+
+lldbinline.MakeInlineTest(__file__, globals(), [lldbtest.expectedFailureWindows("llvm.org/pr24772")])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/main.cpp
new file mode 100644
index 000000000000..4a449e9716c3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/stringprinter/main.cpp
@@ -0,0 +1,40 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <string>
+
+int main (int argc, char const *argv[])
+{
+ std::string stdstring("Hello\t\tWorld\nI am here\t\tto say hello\n"); //%self.addTearDownHook(lambda x: x.runCmd("setting set escape-non-printables true"))
+ const char* constcharstar = stdstring.c_str();
+ std::string longstring(
+"I am a very long string; in fact I am longer than any reasonable length that a string should be; quite long indeed; oh my, so many words; so many letters; this is kind of like writing a poem; except in real life all that is happening"
+" is just me producing a very very long set of words; there is text here, text there, text everywhere; it fills me with glee to see so much text; all around me it's just letters, and symbols, and other pleasant drawings that cause me"
+" a large amount of joy upon visually seeing them with my eyes; well, this is now a lot of letters, but it is still not enough for the purpose of the test I want to test, so maybe I should copy and paste this a few times, you know.."
+" for science, or something"
+ "I am a very long string; in fact I am longer than any reasonable length that a string should be; quite long indeed; oh my, so many words; so many letters; this is kind of like writing a poem; except in real life all that is happening"
+ " is just me producing a very very long set of words; there is text here, text there, text everywhere; it fills me with glee to see so much text; all around me it's just letters, and symbols, and other pleasant drawings that cause me"
+ " a large amount of joy upon visually seeing them with my eyes; well, this is now a lot of letters, but it is still not enough for the purpose of the test I want to test, so maybe I should copy and paste this a few times, you know.."
+ " for science, or something"
+ "I am a very long string; in fact I am longer than any reasonable length that a string should be; quite long indeed; oh my, so many words; so many letters; this is kind of like writing a poem; except in real life all that is happening"
+ " is just me producing a very very long set of words; there is text here, text there, text everywhere; it fills me with glee to see so much text; all around me it's just letters, and symbols, and other pleasant drawings that cause me"
+ " a large amount of joy upon visually seeing them with my eyes; well, this is now a lot of letters, but it is still not enough for the purpose of the test I want to test, so maybe I should copy and paste this a few times, you know.."
+ " for science, or something"
+ );
+ const char* longconstcharstar = longstring.c_str();
+ return 0; //% if self.TraceOn(): self.runCmd('frame variable')
+ //% self.assertTrue(self.frame().FindVariable('stdstring').GetSummary() == '"Hello\\t\\tWorld\\nI am here\\t\\tto say hello\\n"')
+ //% self.assertTrue(self.frame().FindVariable('constcharstar').GetSummary() == '"Hello\\t\\tWorld\\nI am here\\t\\tto say hello\\n"')
+ //% self.runCmd("setting set escape-non-printables false")
+ //% self.assertTrue(self.frame().FindVariable('stdstring').GetSummary() == '"Hello\t\tWorld\nI am here\t\tto say hello\n"')
+ //% self.assertTrue(self.frame().FindVariable('constcharstar').GetSummary() == '"Hello\t\tWorld\nI am here\t\tto say hello\n"')
+ //% self.assertTrue(self.frame().FindVariable('longstring').GetSummary().endswith('"...'))
+ //% self.assertTrue(self.frame().FindVariable('longconstcharstar').GetSummary().endswith('"...'))
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/Makefile
new file mode 100644
index 000000000000..04f39271f0cd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/Makefile
@@ -0,0 +1,12 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+# clang-3.5+ outputs FullDebugInfo by default for Darwin/FreeBSD
+# targets. Other targets do not, which causes this test to fail.
+# This flag enables FullDebugInfo for all targets.
+ifneq (,$(findstring clang,$(CC)))
+ CFLAGS_EXTRAS += -fno-limit-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/Test-rdar-9974002.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/Test-rdar-9974002.py
new file mode 100644
index 000000000000..2873e35368fb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/Test-rdar-9974002.py
@@ -0,0 +1,133 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class Radar9974002DataFormatterTestCase(TestBase):
+
+ # test for rdar://problem/9974002 ()
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ if "clang" in self.getCompiler() and "3.4" in self.getCompilerVersion():
+ self.skipTest("llvm.org/pr16214 -- clang emits partial DWARF for structures referenced via typedef")
+
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type summary clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer.first}\" container")
+
+ self.expect('frame variable mine',
+ substrs = ['mine = ',
+ '1', '<parent is NULL>'])
+
+ self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer}\" container")
+
+ self.expect('frame variable mine',
+ substrs = ['mine = ',
+ '1', '0x000000'])
+
+ self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer%S}\" container")
+
+ self.expect('frame variable mine',
+ substrs = ['mine = ',
+ '1', '0x000000'])
+
+ self.runCmd("type summary add -s foo contained")
+
+ self.expect('frame variable mine',
+ substrs = ['mine = ',
+ '1', 'foo'])
+
+ self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer}\" container")
+
+ self.expect('frame variable mine',
+ substrs = ['mine = ',
+ '1', 'foo'])
+
+ self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer%V}\" container")
+
+ self.expect('frame variable mine',
+ substrs = ['mine = ',
+ '1', '0x000000'])
+
+ self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer.first}\" container")
+
+ self.expect('frame variable mine',
+ substrs = ['mine = ',
+ '1', '<parent is NULL>'])
+
+ self.runCmd("type summary delete contained")
+ self.runCmd("n")
+
+ self.expect('frame variable mine',
+ substrs = ['mine = ',
+ '1', '<parent is NULL>'])
+
+ self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer}\" container")
+
+ self.expect('frame variable mine',
+ substrs = ['mine = ',
+ '1', '0x000000'])
+
+ self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer%S}\" container")
+
+ self.expect('frame variable mine',
+ substrs = ['mine = ',
+ '1', '0x000000'])
+
+ self.runCmd("type summary add -s foo contained")
+
+ self.expect('frame variable mine',
+ substrs = ['mine = ',
+ '1', 'foo'])
+
+ self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer}\" container")
+
+ self.expect('frame variable mine',
+ substrs = ['mine = ',
+ '1', 'foo'])
+
+ self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer%V}\" container")
+
+ self.expect('frame variable mine',
+ substrs = ['mine = ',
+ '1', '0x000000'])
+
+ self.runCmd("type summary add -s \"${var.scalar} and ${var.pointer.first}\" container")
+
+ self.expect('frame variable mine',
+ substrs = ['mine = ',
+ '1', '<parent is NULL>'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/main.cpp
new file mode 100644
index 000000000000..03a9f278b7ec
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/summary-string-onfail/main.cpp
@@ -0,0 +1,30 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+
+struct contained
+{
+ int first;
+ int second;
+};
+
+struct container
+{
+ int scalar;
+ struct contained *pointer;
+};
+
+int main ()
+{
+ struct container mine = {1, 0};
+ printf ("Mine's scalar is the only thing that is good: %d.\n", mine.scalar); // Set break point at this line.
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/TestSyntheticCapping.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/TestSyntheticCapping.py
new file mode 100644
index 000000000000..0550f57ae62a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/TestSyntheticCapping.py
@@ -0,0 +1,75 @@
+"""
+Check for an issue where capping does not work because the Target pointer appears to be changing behind our backs
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class SyntheticCappingTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def test_with_run_command(self):
+ """Check for an issue where capping does not work because the Target pointer appears to be changing behind our backs."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ # set up the synthetic children provider
+ self.runCmd("script from fooSynthProvider import *")
+ self.runCmd("type synth add -l fooSynthProvider foo")
+
+ # check that the synthetic children work, so we know we are doing the right thing
+ self.expect("frame variable f00_1",
+ substrs = ['r = 33',
+ 'fake_a = 16777216',
+ 'a = 0']);
+
+ # check that capping works
+ self.runCmd("settings set target.max-children-count 2", check=False)
+
+ self.expect("frame variable f00_1",
+ substrs = ['...',
+ 'fake_a = 16777216',
+ 'a = 0']);
+
+ self.expect("frame variable f00_1", matching=False,
+ substrs = ['r = 33']);
+
+
+ self.runCmd("settings set target.max-children-count 256", check=False)
+
+ self.expect("frame variable f00_1", matching=True,
+ substrs = ['r = 33']);
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/fooSynthProvider.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/fooSynthProvider.py
new file mode 100644
index 000000000000..fb95ac2b54d0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/fooSynthProvider.py
@@ -0,0 +1,21 @@
+import lldb
+class fooSynthProvider:
+ def __init__(self, valobj, dict):
+ self.valobj = valobj;
+ self.int_type = valobj.GetType().GetBasicType(lldb.eBasicTypeInt)
+ def num_children(self):
+ return 3;
+ def get_child_at_index(self, index):
+ if index == 0:
+ child = self.valobj.GetChildMemberWithName('a');
+ if index == 1:
+ child = self.valobj.CreateChildAtOffset ('fake_a', 1, self.int_type);
+ if index == 2:
+ child = self.valobj.GetChildMemberWithName('r');
+ return child;
+ def get_child_index(self, name):
+ if name == 'a':
+ return 0;
+ if name == 'fake_a':
+ return 1;
+ return 2;
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/main.cpp
new file mode 100644
index 000000000000..b921915b91c5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/synthcapping/main.cpp
@@ -0,0 +1,62 @@
+struct foo
+{
+ int a;
+ int b;
+ int c;
+ int d;
+ int e;
+ int f;
+ int g;
+ int h;
+ int i;
+ int j;
+ int k;
+ int l;
+ int m;
+ int n;
+ int o;
+ int p;
+ int q;
+ int r;
+
+ foo(int X) :
+ a(X),
+ b(X+1),
+ c(X+3),
+ d(X+5),
+ e(X+7),
+ f(X+9),
+ g(X+11),
+ h(X+13),
+ i(X+15),
+ j(X+17),
+ k(X+19),
+ l(X+21),
+ m(X+23),
+ n(X+25),
+ o(X+27),
+ p(X+29),
+ q(X+31),
+ r(X+33) {}
+};
+
+struct wrapint
+{
+ int x;
+ wrapint(int X) : x(X) {}
+};
+
+int main()
+{
+ foo f00_1(0);
+ foo *f00_ptr = new foo(12);
+
+ f00_1.a++; // Set break point at this line.
+
+ wrapint test_cast('A' +
+ 256*'B' +
+ 256*256*'C'+
+ 256*256*256*'D');
+
+ return 0;
+} \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/Makefile
new file mode 100644
index 000000000000..a8e1853a1290
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/Makefile
@@ -0,0 +1,12 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+
+CFLAGS_EXTRAS += -w
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation
+
+clean::
+ rm -rf $(wildcard *.o *.d *.dSYM *.log)
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/TestSyntheticFilterRecompute.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/TestSyntheticFilterRecompute.py
new file mode 100644
index 000000000000..6b70a88b9f2c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/TestSyntheticFilterRecompute.py
@@ -0,0 +1,74 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import datetime
+import lldbsuite.test.lldbutil as lldbutil
+
+class SyntheticFilterRecomputingTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.m', '// Set break point at this line.')
+
+ @skipUnlessDarwin
+ def test_rdar12437442_with_run_command(self):
+ """Test that we update SBValues correctly as dynamic types change."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type synth clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ # Now run the bulk of the test
+ id_x = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable("x")
+ id_x.SetPreferDynamicValue(lldb.eDynamicCanRunTarget)
+ id_x.SetPreferSyntheticValue(True)
+
+ if self.TraceOn():
+ self.runCmd("expr --dynamic-type run-target --ptr-depth 1 -- x")
+
+ self.assertTrue(id_x.GetSummary() == '@"5 elements"', "array does not get correct summary")
+
+ self.runCmd("next")
+ self.runCmd("frame select 0")
+
+ id_x = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable("x")
+ id_x.SetPreferDynamicValue(lldb.eDynamicCanRunTarget)
+ id_x.SetPreferSyntheticValue(True)
+
+ if self.TraceOn():
+ self.runCmd("expr --dynamic-type run-target --ptr-depth 1 -- x")
+
+ self.assertTrue(id_x.GetNumChildren() == 7, "dictionary does not have 7 children")
+ id_x.SetPreferSyntheticValue(False)
+ self.assertFalse(id_x.GetNumChildren() == 7, "dictionary still looks synthetic")
+ id_x.SetPreferSyntheticValue(True)
+ self.assertTrue(id_x.GetSummary() == "7 key/value pairs", "dictionary does not get correct summary")
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/main.m b/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/main.m
new file mode 100644
index 000000000000..a7e94d29d469
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/synthupdate/main.m
@@ -0,0 +1,25 @@
+//===-- main.m ------------------------------------------------*- ObjC -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#import <Foundation/Foundation.h>
+
+int main (int argc, const char * argv[])
+{
+
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+
+ NSArray* foo = [NSArray arrayWithObjects:@1,@2,@3,@4,@5, nil];
+ NSDictionary *bar = @{@1 : @"one",@2 : @"two", @3 : @"three", @4 : @"four", @5 : @"five", @6 : @"six", @7 : @"seven"};
+ id x = foo;
+ x = bar; // Set break point at this line.
+
+ [pool drain];
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/Makefile
new file mode 100644
index 000000000000..3e2b0187b954
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/Makefile
@@ -0,0 +1,4 @@
+LEVEL = ../../../make
+CXX_SOURCES := main.cpp
+CXXFLAGS += -std=c++11
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/TestTypedefArray.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/TestTypedefArray.py
new file mode 100644
index 000000000000..30b66e062827
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/TestTypedefArray.py
@@ -0,0 +1,4 @@
+import lldbsuite.test.lldbinline as lldbinline
+import lldbsuite.test.lldbtest as lldbtest
+
+lldbinline.MakeInlineTest(__file__, globals(), [lldbtest.expectedFailureGcc])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/main.cpp
new file mode 100644
index 000000000000..649c1e09a6a5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/typedef_array/main.cpp
@@ -0,0 +1,14 @@
+//===-- main.cpp --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+typedef int Foo;
+
+int main() {
+ Foo array[3] = {1,2,3};
+ return 0; //% self.expect("frame variable array --show-types --", substrs = ['(Foo [3]) array = {','(Foo) [0] = 1','(Foo) [1] = 2','(Foo) [2] = 3'])
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/TestUserFormatVsSummary.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/TestUserFormatVsSummary.py
new file mode 100644
index 000000000000..dba2816d2647
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/TestUserFormatVsSummary.py
@@ -0,0 +1,59 @@
+"""
+Test that the user can input a format but it will not prevail over summary format's choices.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class UserFormatVSSummaryTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def test_with_run_command(self):
+ """Test that the user can input a format but it will not prevail over summary format's choices."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ self.expect("frame variable p1", substrs = ['(Pair) p1 = (x = 3, y = -3)']);
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.runCmd('type summary add Pair -s "x=${var.x%d},y=${var.y%u}"')
+
+ self.expect("frame variable p1", substrs = ['(Pair) p1 = x=3,y=4294967293']);
+ self.expect("frame variable -f x p1", substrs = ['(Pair) p1 = x=0x00000003,y=0xfffffffd'], matching=False);
+ self.expect("frame variable -f d p1", substrs = ['(Pair) p1 = x=3,y=-3'], matching=False);
+ self.expect("frame variable p1", substrs = ['(Pair) p1 = x=3,y=4294967293']);
+
+ self.runCmd('type summary add Pair -s "x=${var.x%x},y=${var.y%u}"')
+
+ self.expect("frame variable p1", substrs = ['(Pair) p1 = x=0x00000003,y=4294967293']);
+ self.expect("frame variable -f d p1", substrs = ['(Pair) p1 = x=3,y=-3'],matching=False);
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/main.cpp
new file mode 100644
index 000000000000..41c934aec0c3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/user-format-vs-summary/main.cpp
@@ -0,0 +1,20 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+struct Pair {
+ int x;
+ int y;
+
+ Pair(int _x, int _y) : x(_x), y(_y) {}
+};
+
+int main() {
+ Pair p1(3,-3);
+ return p1.x + p1.y; // Set break point at this line.
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/Makefile
new file mode 100644
index 000000000000..18c35a7d84a5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/Makefile
@@ -0,0 +1,11 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+# Workaround for llvm.org/pr16214: clang doesn't emit structure definition DWARF
+# information without the flag below.
+ifneq (,$(findstring clang,$(CC)))
+ CFLAGS_EXTRAS += -fno-limit-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/TestVarInAggregateMisuse.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/TestVarInAggregateMisuse.py
new file mode 100644
index 000000000000..5899469651d3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/TestVarInAggregateMisuse.py
@@ -0,0 +1,74 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class VarInAggregateMisuseTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def test_with_run_command(self):
+ """Test that that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type summary clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.runCmd("type summary add --summary-string \"SUMMARY SUCCESS ${var}\" Summarize")
+
+ self.expect('frame variable mine_ptr',
+ substrs = ['SUMMARY SUCCESS summarize_ptr_t @ '])
+
+ self.expect('frame variable *mine_ptr',
+ substrs = ['SUMMARY SUCCESS summarize_t @'])
+
+ self.runCmd("type summary add --summary-string \"SUMMARY SUCCESS ${var.first}\" Summarize")
+
+ self.expect('frame variable mine_ptr',
+ substrs = ['SUMMARY SUCCESS 10'])
+
+ self.expect('frame variable *mine_ptr',
+ substrs = ['SUMMARY SUCCESS 10'])
+
+ self.runCmd("type summary add --summary-string \"${var}\" Summarize")
+ self.runCmd("type summary add --summary-string \"${var}\" -e TwoSummarizes")
+
+ self.expect('frame variable',
+ substrs = ['(TwoSummarizes) twos = TwoSummarizes @ ',
+ 'first = summarize_t @ ',
+ 'second = summarize_t @ '])
+
+ self.runCmd("type summary add --summary-string \"SUMMARY SUCCESS ${var.first}\" Summarize")
+ self.expect('frame variable',
+ substrs = ['(TwoSummarizes) twos = TwoSummarizes @ ',
+ 'first = SUMMARY SUCCESS 1',
+ 'second = SUMMARY SUCCESS 3'])
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/main.cpp
new file mode 100644
index 000000000000..72c7e138205d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/var-in-aggregate-misuse/main.cpp
@@ -0,0 +1,41 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+struct Summarize
+{
+ int first;
+ int second;
+};
+
+typedef struct Summarize summarize_t;
+typedef summarize_t *summarize_ptr_t;
+
+summarize_t global_mine = {30, 40};
+
+struct TwoSummarizes
+{
+ summarize_t first;
+ summarize_t second;
+};
+
+int
+main()
+{
+ summarize_t mine = {10, 20};
+ summarize_ptr_t mine_ptr = &mine;
+
+ TwoSummarizes twos = { {1,2}, {3,4} };
+
+ printf ("Summarize: first: %d second: %d and address: 0x%p\n", mine.first, mine.second, mine_ptr); // Set break point at this line.
+ printf ("Global summarize: first: %d second: %d.\n", global_mine.first, global_mine.second);
+ return 0;
+}
+
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/TestDataFormatterVarScriptFormatting.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/TestDataFormatterVarScriptFormatting.py
new file mode 100644
index 000000000000..4d060c332f93
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/TestDataFormatterVarScriptFormatting.py
@@ -0,0 +1,56 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+import os.path
+
+class PythonSynthDataFormatterTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', ' // Set breakpoint here.')
+
+ @skipIfFreeBSD # llvm.org/pr20545 bogus output confuses buildbot parser
+ def test_with_run_command(self):
+ """Test using Python synthetic children provider."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synth clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.runCmd("command script import helperfunc.py")
+ self.runCmd('type summary add -x "^something<.*>$" -s "T is a ${script.var:helperfunc.f}"')
+
+ self.expect("frame variable x", substrs = ['T is a non-pointer type']);
+
+ self.expect("frame variable y", substrs = ['T is a pointer type']);
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/helperfunc.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/helperfunc.py
new file mode 100644
index 000000000000..01562c5baa8d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/helperfunc.py
@@ -0,0 +1,5 @@
+import lldb
+
+def f(value,d):
+ return "pointer type" if value.GetType().GetTemplateArgumentType(0).IsPointerType() else "non-pointer type"
+
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/main.cpp
new file mode 100644
index 000000000000..4dc94af3566c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/varscript_formatting/main.cpp
@@ -0,0 +1,8 @@
+template <typename T>
+struct something {};
+
+int main() {
+ something<int> x;
+ something<void*> y;
+ return 0; // Set breakpoint here.
+} \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/Makefile b/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/TestVectorTypesFormatting.py b/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/TestVectorTypesFormatting.py
new file mode 100644
index 000000000000..05899a24ad22
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/TestVectorTypesFormatting.py
@@ -0,0 +1,73 @@
+"""
+Check that vector types format properly
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class VectorTypesFormattingTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// break here')
+
+ # rdar://problem/14035604
+ @skipIf(compiler='gcc') # gcc don't have ext_vector_type extension
+ def test_with_run_command(self):
+ """Check that vector types format properly"""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ pass
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ pass # my code never fails
+
+ v = self.frame().FindVariable("v")
+ v.SetPreferSyntheticValue(True)
+ v.SetFormat(lldb.eFormatVectorOfFloat32)
+
+ if self.TraceOn(): print(v)
+
+ self.assertTrue(v.GetNumChildren() == 4, "v as float32[] has 4 children")
+ self.assertTrue(v.GetChildAtIndex(0).GetData().float[0] == 1.25, "child 0 == 1.25")
+ self.assertTrue(v.GetChildAtIndex(1).GetData().float[0] == 1.25, "child 1 == 1.25")
+ self.assertTrue(v.GetChildAtIndex(2).GetData().float[0] == 2.50, "child 2 == 2.50")
+ self.assertTrue(v.GetChildAtIndex(3).GetData().float[0] == 2.50, "child 3 == 2.50")
+
+ self.expect("expr -f int16_t[] -- v", substrs=['(0, 16288, 0, 16288, 0, 16416, 0, 16416)'])
+ self.expect("expr -f uint128_t[] -- v", substrs=['(85236745249553456609335044694184296448)'])
+ self.expect("expr -f float32[] -- v", substrs=['(1.25, 1.25, 2.5, 2.5)'])
+
+ oldValue = v.GetChildAtIndex(0).GetValue()
+ v.SetFormat(lldb.eFormatHex)
+ newValue = v.GetChildAtIndex(0).GetValue()
+ self.assertFalse(oldValue == newValue, "values did not change along with format")
+
+ v.SetFormat(lldb.eFormatVectorOfFloat32)
+ oldValueAgain = v.GetChildAtIndex(0).GetValue()
+ self.assertTrue(oldValue == oldValueAgain, "same format but different values")
diff --git a/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/main.cpp b/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/main.cpp
new file mode 100644
index 000000000000..b9d67ad20ab2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/data-formatter/vector-types/main.cpp
@@ -0,0 +1,17 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+typedef float float4 __attribute__((ext_vector_type(4)));
+typedef unsigned char vec __attribute__((ext_vector_type(16)));
+
+int main() {
+ float4 f4 = {1.25, 1.25, 2.50, 2.50};
+ vec v = (vec)f4;
+ return 0; // break here
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/dead-strip/Makefile b/packages/Python/lldbsuite/test/functionalities/dead-strip/Makefile
new file mode 100644
index 000000000000..c60ecd414635
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/dead-strip/Makefile
@@ -0,0 +1,18 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+ifeq "$(OS)" ""
+ OS = $(shell uname -s)
+endif
+
+ifeq "$(OS)" "Darwin"
+ LDFLAGS = $(CFLAGS) -Xlinker -dead_strip
+else
+ CFLAGS += -fdata-sections -ffunction-sections
+ LDFLAGS = $(CFLAGS) -Wl,--gc-sections
+endif
+
+MAKE_DSYM := NO
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/dead-strip/TestDeadStrip.py b/packages/Python/lldbsuite/test/functionalities/dead-strip/TestDeadStrip.py
new file mode 100644
index 000000000000..f10736bd75c0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/dead-strip/TestDeadStrip.py
@@ -0,0 +1,58 @@
+"""
+Test that breakpoint works correctly in the presence of dead-code stripping.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class DeadStripTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureWindows("llvm.org/pr24778")
+ @expectedFailureDwo("llvm.org/pr25087")
+ @skipIfFreeBSD # The -dead_strip linker option isn't supported on FreeBSD versions of ld.
+ def test(self):
+ """Test breakpoint works correctly with dead-code stripping."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break by function name f1 (live code).
+ lldbutil.run_break_set_by_symbol (self, "f1", num_expected_locations=1, module_name="a.out")
+
+ # Break by function name f2 (dead code).
+ lldbutil.run_break_set_by_symbol (self, "f2", num_expected_locations=0, module_name="a.out")
+
+ # Break by function name f3 (live code).
+ lldbutil.run_break_set_by_symbol (self, "f3", num_expected_locations=1, module_name="a.out")
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint (breakpoint #1).
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'a.out`f1',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f 1", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ self.runCmd("continue")
+
+ # The stop reason of the thread should be breakpoint (breakpoint #3).
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'a.out`f3',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f 3", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
diff --git a/packages/Python/lldbsuite/test/functionalities/dead-strip/cmds.txt b/packages/Python/lldbsuite/test/functionalities/dead-strip/cmds.txt
new file mode 100644
index 000000000000..f6fd04502888
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/dead-strip/cmds.txt
@@ -0,0 +1,4 @@
+b main.c:21
+b main.c:41
+lines -shlib a.out main.c
+c
diff --git a/packages/Python/lldbsuite/test/functionalities/dead-strip/main.c b/packages/Python/lldbsuite/test/functionalities/dead-strip/main.c
new file mode 100644
index 000000000000..fe8e7c7de582
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/dead-strip/main.c
@@ -0,0 +1,53 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+
+int f1 (char *s);
+int f2 (char *s);
+int f3 (char *s);
+
+
+// We want f1 to start on line 20
+int f1 (char *s)
+{
+ return printf("f1: %s\n", s);
+}
+
+
+
+
+
+// We want f2 to start on line 30, this should get stripped
+int f2 (char *s)
+{
+ return printf("f2: %s\n", s);
+}
+
+
+
+
+
+// We want f3 to start on line 40
+int f3 (char *s)
+{
+ return printf("f3: %s\n", s);
+}
+
+
+
+
+
+// We want main to start on line 50
+int main (int argc, const char * argv[])
+{
+ f1("carp");
+ f3("dong");
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/disassembly/Makefile b/packages/Python/lldbsuite/test/functionalities/disassembly/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/disassembly/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/disassembly/TestDisassembleBreakpoint.py b/packages/Python/lldbsuite/test/functionalities/disassembly/TestDisassembleBreakpoint.py
new file mode 100644
index 000000000000..df2308de7605
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/disassembly/TestDisassembleBreakpoint.py
@@ -0,0 +1,54 @@
+"""
+Test some lldb command abbreviations.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class DisassemblyTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureWindows # Function name prints fully demangled instead of name-only
+ def test(self):
+ self.build()
+ exe = os.path.join (os.getcwd(), "a.out")
+ self.expect("file " + exe,
+ patterns = [ "Current executable set to .*a.out.*" ])
+
+ match_object = lldbutil.run_break_set_command (self, "br s -n sum")
+ lldbutil.check_breakpoint_result (self, match_object, symbol_name='sum', symbol_match_exact=False, num_locations=1)
+
+ self.expect("run",
+ patterns = [ "Process .* launched: "])
+
+ self.runCmd("dis -f")
+ disassembly = self.res.GetOutput()
+
+ # ARCH, if not specified, defaults to x86_64.
+ arch = self.getArchitecture()
+ if arch in ["", 'x86_64', 'i386', 'i686']:
+ breakpoint_opcodes = ["int3"]
+ instructions = [' mov', ' addl ', 'ret']
+ elif arch in ["arm", "aarch64"]:
+ breakpoint_opcodes = ["brk", "udf"]
+ instructions = [' add ', ' ldr ', ' str ']
+ elif re.match("mips" , arch):
+ breakpoint_opcodes = ["break"]
+ instructions = ['lw', 'sw', 'jr']
+ else:
+ # TODO please add your arch here
+ self.fail('unimplemented for arch = "{arch}"'.format(arch=self.getArchitecture()))
+
+ # make sure that the software breakpoint has been removed
+ for op in breakpoint_opcodes:
+ self.assertFalse(op in disassembly)
+
+ # make sure a few reasonable assembly instructions are here
+ self.expect(disassembly, exe=False, startstr = "a.out`sum", substrs = instructions)
diff --git a/packages/Python/lldbsuite/test/functionalities/disassembly/main.cpp b/packages/Python/lldbsuite/test/functionalities/disassembly/main.cpp
new file mode 100644
index 000000000000..8813647f6b72
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/disassembly/main.cpp
@@ -0,0 +1,28 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+int
+sum (int a, int b)
+{
+ int result = a + b;
+ return result;
+}
+
+int
+main(int argc, char const *argv[])
+{
+
+ int array[3];
+
+ array[0] = sum (1238, 78392);
+ array[1] = sum (379265, 23674);
+ array[2] = sum (872934, 234);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/Makefile b/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/Makefile
new file mode 100644
index 000000000000..ceb406ee2eab
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := pass-to-base.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/TestDynamicValueChildCount.py b/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/TestDynamicValueChildCount.py
new file mode 100644
index 000000000000..ac039990b5bf
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/TestDynamicValueChildCount.py
@@ -0,0 +1,78 @@
+"""
+Test that dynamic values update their child count correctly
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class DynamicValueChildCountTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+
+ # Find the line number to break for main.c.
+
+ self.main_third_call_line = line_number('pass-to-base.cpp',
+ '// Break here and check b has 0 children')
+ self.main_fourth_call_line = line_number('pass-to-base.cpp',
+ '// Break here and check b still has 0 children')
+ self.main_fifth_call_line = line_number('pass-to-base.cpp',
+ '// Break here and check b has one child now')
+ self.main_sixth_call_line = line_number('pass-to-base.cpp',
+ '// Break here and check b has 0 children again')
+
+ @expectedFailureLinux("llvm.org/pr23039")
+ @expectedFailureFreeBSD("llvm.org/pr19311") # continue at a breakpoint does not work
+ @expectedFailureWindows("llvm.org/pr24663")
+ @expectedFailurei386("to be figured out")
+ @add_test_categories(['pyapi'])
+ def test_get_dynamic_vals(self):
+ """Test fetching C++ dynamic values from pointers & references."""
+ """Get argument vals for the call stack when stopped on a breakpoint."""
+ self.build(dictionary=self.getBuildFlags())
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target from the debugger.
+
+ target = self.dbg.CreateTarget (exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Set up our breakpoints:
+
+ third_call_bpt = target.BreakpointCreateByLocation('pass-to-base.cpp', self.main_third_call_line)
+ self.assertTrue(third_call_bpt,
+ VALID_BREAKPOINT)
+ fourth_call_bpt = target.BreakpointCreateByLocation('pass-to-base.cpp', self.main_fourth_call_line)
+ self.assertTrue(fourth_call_bpt,
+ VALID_BREAKPOINT)
+ fifth_call_bpt = target.BreakpointCreateByLocation('pass-to-base.cpp', self.main_fifth_call_line)
+ self.assertTrue(fifth_call_bpt,
+ VALID_BREAKPOINT)
+ sixth_call_bpt = target.BreakpointCreateByLocation('pass-to-base.cpp', self.main_sixth_call_line)
+ self.assertTrue(sixth_call_bpt,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+
+ b = self.frame().FindVariable("b").GetDynamicValue(lldb.eDynamicCanRunTarget)
+ self.assertTrue(b.GetNumChildren() == 0, "b has 0 children")
+ self.runCmd("continue")
+ self.assertTrue(b.GetNumChildren() == 0, "b still has 0 children")
+ self.runCmd("continue")
+ self.assertTrue(b.GetNumChildren() != 0, "b now has 1 child")
+ self.runCmd("continue")
+ self.assertTrue(b.GetNumChildren() == 0, "b didn't go back to 0 children")
diff --git a/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/pass-to-base.cpp b/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/pass-to-base.cpp
new file mode 100644
index 000000000000..d9dd3529821e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/dynamic_value_child_count/pass-to-base.cpp
@@ -0,0 +1,36 @@
+#include <stdio.h>
+#include <memory>
+
+class BaseClass
+{
+public:
+ BaseClass();
+ virtual ~BaseClass() { }
+};
+
+class DerivedClass : public BaseClass
+{
+public:
+ DerivedClass();
+ virtual ~DerivedClass() { }
+protected:
+ int mem;
+};
+
+BaseClass::BaseClass()
+{
+}
+
+DerivedClass::DerivedClass() : BaseClass()
+{
+ mem = 101;
+}
+
+int
+main (int argc, char **argv)
+{
+ BaseClass *b = nullptr; // Break here and check b has 0 children
+ b = new DerivedClass(); // Break here and check b still has 0 children
+ b = nullptr; // Break here and check b has one child now
+ return 0; // Break here and check b has 0 children again
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/embedded_interpreter/Makefile b/packages/Python/lldbsuite/test/functionalities/embedded_interpreter/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/embedded_interpreter/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/embedded_interpreter/TestConvenienceVariables.py b/packages/Python/lldbsuite/test/functionalities/embedded_interpreter/TestConvenienceVariables.py
new file mode 100644
index 000000000000..eddaa3cc9840
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/embedded_interpreter/TestConvenienceVariables.py
@@ -0,0 +1,78 @@
+"""Test convenience variables when you drop in from lldb prompt into an embedded interpreter."""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class ConvenienceVariablesCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break on inside main.cpp.
+ self.line = line_number('main.c', 'Hello world.')
+
+ @skipIfFreeBSD # llvm.org/pr17228
+ @skipIfRemote
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ def test_with_run_commands(self):
+ """Test convenience variables lldb.debugger, lldb.target, lldb.process, lldb.thread, and lldb.frame."""
+ self.build()
+ import pexpect
+ exe = os.path.join(os.getcwd(), "a.out")
+ prompt = "(lldb) "
+ python_prompt = ">>> "
+
+ # So that the child gets torn down after the test.
+ self.child = pexpect.spawn('%s %s %s' % (lldbtest_config.lldbExec, self.lldbOption, exe))
+ child = self.child
+ # Turn on logging for what the child sends back.
+ if self.TraceOn():
+ child.logfile_read = sys.stdout
+
+ # Set the breakpoint, run the inferior, when it breaks, issue print on
+ # the various convenience variables.
+ child.expect_exact(prompt)
+ child.sendline('breakpoint set -f main.c -l %d' % self.line)
+ child.expect_exact(prompt)
+ child.sendline('run')
+ child.expect_exact("stop reason = breakpoint 1.1")
+ child.expect_exact(prompt)
+ child.sendline('script')
+ child.expect_exact(python_prompt)
+
+ # Set a flag so that we know during teardown time, we need to exit the
+ # Python interpreter, then the lldb interpreter.
+ self.child_in_script_interpreter = True
+
+ child.sendline('print(lldb.debugger)')
+ child.expect_exact(python_prompt)
+ self.expect(child.before, exe=False,
+ patterns = ['Debugger \(instance: .*, id: \d\)'])
+
+ child.sendline('print(lldb.target)')
+ child.expect_exact(python_prompt)
+ self.expect(child.before, exe=False,
+ substrs = ['a.out'])
+
+ child.sendline('print(lldb.process)')
+ child.expect_exact(python_prompt)
+ self.expect(child.before, exe=False,
+ patterns = ['SBProcess: pid = \d+, state = stopped, threads = \d, executable = a.out'])
+
+ child.sendline('print(lldb.thread)')
+ child.expect_exact(python_prompt)
+ # Linux outputs decimal tid and 'name' instead of 'queue'
+ self.expect(child.before, exe=False,
+ patterns = ['thread #1: tid = (0x[0-9a-f]+|[0-9]+), 0x[0-9a-f]+ a\.out`main\(argc=1, argv=0x[0-9a-f]+\) \+ \d+ at main\.c:%d, (name|queue) = \'.+\', stop reason = breakpoint 1\.1' % self.line])
+
+ child.sendline('print(lldb.frame)')
+ child.expect_exact(python_prompt)
+ self.expect(child.before, exe=False,
+ patterns = ['frame #0: 0x[0-9a-f]+ a\.out`main\(argc=1, argv=0x[0-9a-f]+\) \+ \d+ at main\.c:%d' % self.line])
diff --git a/packages/Python/lldbsuite/test/functionalities/embedded_interpreter/main.c b/packages/Python/lldbsuite/test/functionalities/embedded_interpreter/main.c
new file mode 100644
index 000000000000..277aa54a4eea
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/embedded_interpreter/main.c
@@ -0,0 +1,6 @@
+#include <stdio.h>
+
+int main(int argc, char const *argv[]) {
+ printf("Hello world.\n");
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/exec/Makefile b/packages/Python/lldbsuite/test/functionalities/exec/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/exec/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/exec/TestExec.py b/packages/Python/lldbsuite/test/functionalities/exec/TestExec.py
new file mode 100644
index 000000000000..9321a308a83c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/exec/TestExec.py
@@ -0,0 +1,85 @@
+"""
+Test some lldb command abbreviations.
+"""
+from __future__ import print_function
+
+
+
+import lldb
+import os
+import time
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+import lldbsuite.support.seven as seven
+
+def execute_command (command):
+ #print('%% %s' % (command))
+ (exit_status, output) = seven.get_command_status_output(command)
+ #if output:
+ # print(output)
+ #print('status = %u' % (exit_status))
+ return exit_status
+
+class ExecTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipUnlessDarwin
+ def test(self):
+ if self.getArchitecture() == 'x86_64':
+ source = os.path.join (os.getcwd(), "main.cpp")
+ o_file = os.path.join (os.getcwd(), "main.o")
+ execute_command ("'%s' -g -O0 -arch i386 -arch x86_64 '%s' -c -o '%s'" % (os.environ["CC"], source, o_file))
+ execute_command ("'%s' -g -O0 -arch i386 -arch x86_64 '%s'" % (os.environ["CC"], o_file))
+ if self.debug_info != "dsym":
+ dsym_path = os.path.join (os.getcwd(), "a.out.dSYM")
+ execute_command ("rm -rf '%s'" % (dsym_path))
+ else:
+ self.build()
+
+ exe = os.path.join (os.getcwd(), "a.out")
+
+ # Create the target
+ target = self.dbg.CreateTarget(exe)
+
+ # Create any breakpoints we need
+ breakpoint = target.BreakpointCreateBySourceRegex ('Set breakpoint 1 here', lldb.SBFileSpec ("main.cpp", False))
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Launch the process
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ for i in range(6):
+ # The stop reason of the thread should be breakpoint.
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ STOPPED_DUE_TO_BREAKPOINT)
+
+ thread = process.GetThreadAtIndex (0)
+
+ self.assertTrue (thread.IsValid(),
+ "Process stopped at 'main' should have a valid thread");
+
+ stop_reason = thread.GetStopReason()
+
+ self.assertTrue (stop_reason == lldb.eStopReasonBreakpoint,
+ "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint");
+
+ # Run and we should stop due to exec
+ process.Continue()
+
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ "Process should be stopped at __dyld_start")
+
+ thread = process.GetThreadAtIndex (0)
+
+ self.assertTrue (thread.IsValid(),
+ "Process stopped at exec should have a valid thread");
+
+ stop_reason = thread.GetStopReason()
+
+ self.assertTrue (stop_reason == lldb.eStopReasonExec,
+ "Thread in process stopped on exec should have a stop reason of eStopReasonExec");
+
+ # Run and we should stop at breakpoint in main after exec
+ process.Continue()
diff --git a/packages/Python/lldbsuite/test/functionalities/exec/main.cpp b/packages/Python/lldbsuite/test/functionalities/exec/main.cpp
new file mode 100644
index 000000000000..700c5dd94b28
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/exec/main.cpp
@@ -0,0 +1,94 @@
+#include <errno.h>
+#include <mach/mach.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <spawn.h>
+#include <unistd.h>
+
+static void
+exit_with_errno (int err, const char *prefix)
+{
+ if (err)
+ {
+ fprintf (stderr,
+ "%s%s",
+ prefix ? prefix : "",
+ strerror(err));
+ exit (err);
+ }
+}
+
+static pid_t
+spawn_process (const char **argv,
+ const char **envp,
+ cpu_type_t cpu_type,
+ int &err)
+{
+ pid_t pid = 0;
+
+ const posix_spawn_file_actions_t *file_actions = NULL;
+ posix_spawnattr_t attr;
+ err = posix_spawnattr_init (&attr);
+ if (err)
+ return pid;
+
+ short flags = POSIX_SPAWN_SETEXEC | POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
+ err = posix_spawnattr_setflags (&attr, flags);
+ if (err == 0)
+ {
+ // Use the default signal masks
+ sigset_t no_signals;
+ sigset_t all_signals;
+ sigemptyset (&no_signals);
+ sigfillset (&all_signals);
+ posix_spawnattr_setsigmask(&attr, &no_signals);
+ posix_spawnattr_setsigdefault(&attr, &all_signals);
+
+ if (cpu_type != 0)
+ {
+ size_t ocount = 0;
+ err = posix_spawnattr_setbinpref_np (&attr, 1, &cpu_type, &ocount);
+ }
+
+ if (err == 0)
+ {
+ err = posix_spawn (&pid,
+ argv[0],
+ file_actions,
+ &attr,
+ (char * const *)argv,
+ (char * const *)envp);
+ }
+
+ posix_spawnattr_destroy(&attr);
+ }
+ return pid;
+}
+
+int
+main (int argc, char const **argv)
+{
+ printf ("pid %i: Pointer size is %zu.\n", getpid(), sizeof(void *));
+ int err = 0; // Set breakpoint 1 here
+#if defined (__x86_64__)
+ if (sizeof(void *) == 8)
+ {
+ spawn_process (argv, NULL, CPU_TYPE_I386, err);
+ if (err)
+ exit_with_errno (err, "posix_spawn i386 error");
+ }
+ else
+ {
+ spawn_process (argv, NULL, CPU_TYPE_X86_64, err);
+ if (err)
+ exit_with_errno (err, "posix_spawn x86_64 error");
+ }
+#else
+ spawn_process (argv, NULL, 0, err);
+ if (err)
+ exit_with_errno (err, "posix_spawn x86_64 error");
+#endif
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/expr-doesnt-deadlock/.categories b/packages/Python/lldbsuite/test/functionalities/expr-doesnt-deadlock/.categories
new file mode 100644
index 000000000000..897e40a99dda
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/expr-doesnt-deadlock/.categories
@@ -0,0 +1 @@
+expression
diff --git a/packages/Python/lldbsuite/test/functionalities/expr-doesnt-deadlock/Makefile b/packages/Python/lldbsuite/test/functionalities/expr-doesnt-deadlock/Makefile
new file mode 100644
index 000000000000..a10791d58907
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/expr-doesnt-deadlock/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../make
+
+C_SOURCES := locking.c
+ENABLE_THREADS := YES
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/expr-doesnt-deadlock/TestExprDoesntBlock.py b/packages/Python/lldbsuite/test/functionalities/expr-doesnt-deadlock/TestExprDoesntBlock.py
new file mode 100644
index 000000000000..a54b45822a6a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/expr-doesnt-deadlock/TestExprDoesntBlock.py
@@ -0,0 +1,57 @@
+"""
+Test that expr will time out and allow other threads to run if it blocks.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ExprDoesntDeadlockTestCase(TestBase):
+
+ def getCategories(self):
+ return ['basic_process']
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureFreeBSD('llvm.org/pr17946')
+ @expectedFlakeyLinux # failed 1/365 test runs, line 61, thread.IsValid()
+ @expectedFailureWindows # Windows doesn't have pthreads, need to port this test.
+ def test_with_run_command(self):
+ """Test that expr will time out and allow other threads to run if it blocks."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create a breakpoint at source line before call_me_to_get_lock gets called.
+
+ main_file_spec = lldb.SBFileSpec ("locking.c")
+ breakpoint = target.BreakpointCreateBySourceRegex('Break here', main_file_spec)
+ if self.TraceOn():
+ print("breakpoint:", breakpoint)
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Frame #0 should be on self.line1 and the break condition should hold.
+ from lldbsuite.test.lldbutil import get_stopped_thread
+ thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
+
+ frame0 = thread.GetFrameAtIndex(0)
+
+ var = frame0.EvaluateExpression ("call_me_to_get_lock()")
+ self.assertTrue (var.IsValid())
+ self.assertTrue (var.GetValueAsSigned (0) == 567)
diff --git a/packages/Python/lldbsuite/test/functionalities/expr-doesnt-deadlock/locking.c b/packages/Python/lldbsuite/test/functionalities/expr-doesnt-deadlock/locking.c
new file mode 100644
index 000000000000..fae9979611d5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/expr-doesnt-deadlock/locking.c
@@ -0,0 +1,80 @@
+#include <pthread.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <stdio.h>
+
+pthread_mutex_t contended_mutex = PTHREAD_MUTEX_INITIALIZER;
+
+pthread_mutex_t control_mutex = PTHREAD_MUTEX_INITIALIZER;
+pthread_cond_t control_condition;
+
+pthread_mutex_t thread_started_mutex = PTHREAD_MUTEX_INITIALIZER;
+pthread_cond_t thread_started_condition;
+
+// This function runs in a thread. The locking dance is to make sure that
+// by the time the main thread reaches the pthread_join below, this thread
+// has for sure acquired the contended_mutex. So then the call_me_to_get_lock
+// function will block trying to get the mutex, and only succeed once it
+// signals this thread, then lets it run to wake up from the cond_wait and
+// release the mutex.
+
+void *
+lock_acquirer_1 (void *input)
+{
+ pthread_mutex_lock (&contended_mutex);
+
+ // Grab this mutex, that will ensure that the main thread
+ // is in its cond_wait for it (since that's when it drops the mutex.
+
+ pthread_mutex_lock (&thread_started_mutex);
+ pthread_mutex_unlock(&thread_started_mutex);
+
+ // Now signal the main thread that it can continue, we have the contended lock
+ // so the call to call_me_to_get_lock won't make any progress till this
+ // thread gets a chance to run.
+
+ pthread_mutex_lock (&control_mutex);
+
+ pthread_cond_signal (&thread_started_condition);
+
+ pthread_cond_wait (&control_condition, &control_mutex);
+
+ pthread_mutex_unlock (&contended_mutex);
+ return NULL;
+}
+
+int
+call_me_to_get_lock ()
+{
+ pthread_cond_signal (&control_condition);
+ pthread_mutex_lock (&contended_mutex);
+ return 567;
+}
+
+int main ()
+{
+ pthread_t thread_1;
+
+ pthread_cond_init (&control_condition, NULL);
+ pthread_cond_init (&thread_started_condition, NULL);
+
+ pthread_mutex_lock (&thread_started_mutex);
+
+ pthread_create (&thread_1, NULL, lock_acquirer_1, NULL);
+
+ pthread_cond_wait (&thread_started_condition, &thread_started_mutex);
+
+ pthread_mutex_lock (&control_mutex);
+ pthread_mutex_unlock (&control_mutex);
+
+ // Break here. At this point the other thread will have the contended_mutex,
+ // and be sitting in its cond_wait for the control condition. So there is
+ // no way that our by-hand calling of call_me_to_get_lock will proceed
+ // without running the first thread at least somewhat.
+
+ call_me_to_get_lock();
+ pthread_join (thread_1, NULL);
+
+ return 0;
+
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/fat_archives/Makefile b/packages/Python/lldbsuite/test/functionalities/fat_archives/Makefile
new file mode 100644
index 000000000000..e1832fdefbee
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/fat_archives/Makefile
@@ -0,0 +1,14 @@
+all: clean
+ $(CC) -arch i386 -g -c a.c
+ ar -q liba-i386.a a.o
+ ranlib liba-i386.a
+ $(CC) -arch x86_64 -g -c a.c
+ ar -q liba-x86_64.a a.o
+ ranlib liba-x86_64.a
+ lipo -create -output liba.a liba-i386.a liba-x86_64.a
+ $(CC) -g -c main.c
+ $(CC) -o a.out main.o -L. -la
+
+clean:
+ rm -rf a.o a.out liba-i386.a liba-x86_64.a liba.a $(wildcard *un~ .*un~ main.o *.pyc)
+
diff --git a/packages/Python/lldbsuite/test/functionalities/fat_archives/TestFatArchives.py b/packages/Python/lldbsuite/test/functionalities/fat_archives/TestFatArchives.py
new file mode 100644
index 000000000000..19a2dba2109a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/fat_archives/TestFatArchives.py
@@ -0,0 +1,58 @@
+"""
+Test some lldb command abbreviations.
+"""
+from __future__ import print_function
+
+
+
+import lldb
+import os
+import time
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+import lldbsuite.support.seven as seven
+
+def execute_command (command):
+ # print('%% %s' % (command))
+ (exit_status, output) = seven.get_command_status_output(command)
+ # if output:
+ # print(output)
+ # print('status = %u' % (exit_status))
+ return exit_status
+
+class FatArchiveTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipUnlessDarwin
+ def test (self):
+ if self.getArchitecture() == 'x86_64':
+ execute_command ("make CC='%s'" % (os.environ["CC"]))
+ self.main ()
+ else:
+ self.skipTest("This test requires x86_64 as the architecture for the inferior")
+
+ def main (self):
+ '''This test compiles a quick example by making a fat file (universal) full of
+ skinny .o files and makes sure we can use them to resolve breakpoints when doing
+ DWARF in .o file debugging. The only thing this test needs to do is to compile and
+ set a breakpoint in the target and verify any breakpoint locations have valid debug
+ info for the function, and source file and line.'''
+ exe = os.path.join (os.getcwd(), "a.out")
+
+ # Create the target
+ target = self.dbg.CreateTarget(exe)
+
+ # Create a breakpoint by name
+ breakpoint = target.BreakpointCreateByName ('foo', exe)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Make sure the breakpoint resolves to a function, file and line
+ for bp_loc in breakpoint:
+ # Get a section offset address (lldb.SBAddress) from the breakpoint location
+ bp_loc_addr = bp_loc.GetAddress()
+ line_entry = bp_loc_addr.GetLineEntry()
+ function = bp_loc_addr.GetFunction()
+ self.assertTrue(function.IsValid(), "Verify breakpoint in fat BSD archive has valid function debug info")
+ self.assertTrue(line_entry.GetFileSpec(), "Verify breakpoint in fat BSD archive has source file information")
+ self.assertTrue(line_entry.GetLine() != 0, "Verify breakpoint in fat BSD archive has source line information")
diff --git a/packages/Python/lldbsuite/test/functionalities/fat_archives/a.c b/packages/Python/lldbsuite/test/functionalities/fat_archives/a.c
new file mode 100644
index 000000000000..c100f9a2c075
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/fat_archives/a.c
@@ -0,0 +1,4 @@
+int foo ()
+{
+ return 5;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/fat_archives/a.h b/packages/Python/lldbsuite/test/functionalities/fat_archives/a.h
new file mode 100644
index 000000000000..a4536647cfc9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/fat_archives/a.h
@@ -0,0 +1 @@
+int foo ();
diff --git a/packages/Python/lldbsuite/test/functionalities/fat_archives/main.c b/packages/Python/lldbsuite/test/functionalities/fat_archives/main.c
new file mode 100644
index 000000000000..328319d4fb8f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/fat_archives/main.c
@@ -0,0 +1,6 @@
+#include "a.h"
+#include <stdio.h>
+int main()
+{
+ printf ("%d\n", foo());
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/format/Makefile b/packages/Python/lldbsuite/test/functionalities/format/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/format/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/format/TestFormats.py b/packages/Python/lldbsuite/test/functionalities/format/TestFormats.py
new file mode 100644
index 000000000000..cc962150bc8c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/format/TestFormats.py
@@ -0,0 +1,59 @@
+"""
+Test the command history mechanism
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class TestFormats(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureHostWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ def test_formats(self):
+ """Test format string functionality."""
+ self.build()
+ import pexpect
+ prompt = "(lldb) "
+ child = pexpect.spawn('%s %s -x -o "b main" -o r a.out' % (lldbtest_config.lldbExec, self.lldbOption))
+ # Turn on logging for what the child sends back.
+ if self.TraceOn():
+ child.logfile_read = sys.stdout
+ # So that the spawned lldb session gets shutdown durng teardown.
+ self.child = child
+
+ # Substitute 'Help!' for 'help' using the 'commands regex' mechanism.
+ child.expect_exact(prompt + 'target create "a.out"')
+ child.expect_exact(prompt + 'b main')
+ child.expect_exact(prompt + 'r')
+ child.expect_exact(prompt)
+ child.sendline()
+ # child.expect_exact(prompt + "target create")
+ #
+ # child.sendline("command regex 'Help__'")
+ # child.expect_exact(regex_prompt)
+ # child.sendline('s/^$/help/')
+ # child.expect_exact(regex_prompt1)
+ # child.sendline('')
+ # child.expect_exact(prompt)
+ # # Help!
+ # child.sendline('Help__')
+ # # If we see the familiar 'help' output, the test is done.
+ # child.expect('Debugger commands:')
+ # # Try and incorrectly remove "Help__" using "command unalias" and verify we fail
+ # child.sendline('command unalias Help__')
+ # child.expect_exact("error: 'Help__' is not an alias, it is a debugger command which can be removed using the 'command delete' command")
+ # child.expect_exact(prompt)
+ #
+ # # Delete the regex command using "command delete"
+ # child.sendline('command delete Help__')
+ # child.expect_exact(prompt)
+ # # Verify the command was removed
+ # child.sendline('Help__')
+ # child.expect_exact("error: 'Help__' is not a valid command")
+ # child.expect_exact(prompt)
diff --git a/packages/Python/lldbsuite/test/functionalities/format/main.c b/packages/Python/lldbsuite/test/functionalities/format/main.c
new file mode 100644
index 000000000000..1dfc8ef1f3aa
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/format/main.c
@@ -0,0 +1,15 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+int main (int argc, char const *argv[])
+{
+ printf("testing\n");
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/inferior-assert/Makefile b/packages/Python/lldbsuite/test/functionalities/inferior-assert/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/inferior-assert/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/inferior-assert/TestInferiorAssert.py b/packages/Python/lldbsuite/test/functionalities/inferior-assert/TestInferiorAssert.py
new file mode 100644
index 000000000000..69e977e6343f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/inferior-assert/TestInferiorAssert.py
@@ -0,0 +1,253 @@
+"""Test that lldb functions correctly after the inferior has asserted."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+import lldbsuite.test.lldbplatformutil as lldbplatformutil
+from lldbsuite.test.lldbtest import *
+
+class AssertingInferiorTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureWindows("llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows")
+ @expectedFailurei386("llvm.org/pr25338")
+ def test_inferior_asserting(self):
+ """Test that lldb reliably catches the inferior asserting (command)."""
+ self.build()
+ self.inferior_asserting()
+
+ @expectedFailureWindows("llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows")
+ @expectedFailureAndroid(api_levels=list(range(16 + 1))) # b.android.com/179836
+ def test_inferior_asserting_register(self):
+ """Test that lldb reliably reads registers from the inferior after asserting (command)."""
+ self.build()
+ self.inferior_asserting_registers()
+
+ @expectedFailureWindows("llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows")
+ @expectedFailurei386("llvm.org/pr25338")
+ def test_inferior_asserting_disassemble(self):
+ """Test that lldb reliably disassembles frames after asserting (command)."""
+ self.build()
+ self.inferior_asserting_disassemble()
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureWindows("llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows")
+ def test_inferior_asserting_python(self):
+ """Test that lldb reliably catches the inferior asserting (Python API)."""
+ self.build()
+ self.inferior_asserting_python()
+
+ @expectedFailureWindows("llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows")
+ @expectedFailurei386("llvm.org/pr25338")
+ def test_inferior_asserting_expr(self):
+ """Test that the lldb expression interpreter can read from the inferior after asserting (command)."""
+ self.build()
+ self.inferior_asserting_expr()
+
+ @expectedFailureWindows("llvm.org/pr21793: need to implement support for detecting assertion / abort on Windows")
+ @expectedFailurei386("llvm.org/pr25338")
+ def test_inferior_asserting_step(self):
+ """Test that lldb functions correctly after stepping through a call to assert()."""
+ self.build()
+ self.inferior_asserting_step()
+
+ def set_breakpoint(self, line):
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", line, num_expected_locations=1, loc_exact=True)
+
+ def check_stop_reason(self):
+ if matchAndroid(api_levels=list(range(1, 16+1)))(self):
+ # On android until API-16 the abort() call ended in a sigsegv instead of in a sigabrt
+ stop_reason = 'stop reason = signal SIGSEGV'
+ else:
+ stop_reason = 'stop reason = signal SIGABRT'
+
+ # The stop reason of the thread should be an abort signal or exception.
+ self.expect("thread list", STOPPED_DUE_TO_ASSERT,
+ substrs = ['stopped',
+ stop_reason])
+
+ return stop_reason
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number of the call to assert.
+ self.line = line_number('main.c', '// Assert here.')
+
+ def inferior_asserting(self):
+ """Inferior asserts upon launching; lldb should catch the event and stop."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+ stop_reason = self.check_stop_reason()
+
+ # And it should report a backtrace that includes the assert site.
+ self.expect("thread backtrace all",
+ substrs = [stop_reason, 'main', 'argc', 'argv'])
+
+ # And it should report the correct line number.
+ self.expect("thread backtrace all",
+ substrs = [stop_reason,
+ 'main.c:%d' % self.line])
+
+ def inferior_asserting_python(self):
+ """Inferior asserts upon launching; lldb should catch the event and stop."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now launch the process, and do not stop at entry point.
+ # Both argv and envp are null.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ if process.GetState() != lldb.eStateStopped:
+ self.fail("Process should be in the 'stopped' state, "
+ "instead the actual state is: '%s'" %
+ lldbutil.state_type_to_str(process.GetState()))
+
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonSignal)
+ if not thread:
+ self.fail("Fail to stop the thread upon assert")
+
+ if self.TraceOn():
+ lldbutil.print_stacktrace(thread)
+
+ def inferior_asserting_registers(self):
+ """Test that lldb can read registers after asserting."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+ self.check_stop_reason()
+
+ # lldb should be able to read from registers from the inferior after asserting.
+ lldbplatformutil.check_first_register_readable(self)
+
+ def inferior_asserting_disassemble(self):
+ """Test that lldb can disassemble frames after asserting."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Launch the process, and do not stop at the entry point.
+ target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.check_stop_reason()
+
+ process = target.GetProcess()
+ self.assertTrue(process.IsValid(), "current process is valid")
+
+ thread = process.GetThreadAtIndex(0)
+ self.assertTrue(thread.IsValid(), "current thread is valid")
+
+ lastframeID = thread.GetFrameAtIndex(thread.GetNumFrames() - 1).GetFrameID()
+
+ isi386Arch = False
+ if "i386" in self.getArchitecture():
+ isi386Arch = True
+
+ # lldb should be able to disassemble frames from the inferior after asserting.
+ for frame in thread:
+ self.assertTrue(frame.IsValid(), "current frame is valid")
+
+ self.runCmd("frame select " + str(frame.GetFrameID()), RUN_SUCCEEDED)
+
+ # Don't expect the function name to be in the disassembly as the assert
+ # function might be a no-return function where the PC is past the end
+ # of the function and in the next function. We also can't back the PC up
+ # because we don't know how much to back it up by on targets with opcodes
+ # that have differing sizes
+ pc_backup_offset = 1
+ if frame.GetFrameID() == 0:
+ pc_backup_offset = 0
+ if isi386Arch == True:
+ if lastframeID == frame.GetFrameID():
+ pc_backup_offset = 0
+ self.expect("disassemble -a %s" % (frame.GetPC() - pc_backup_offset),
+ substrs = ['<+0>: '])
+
+ def check_expr_in_main(self, thread):
+ depth = thread.GetNumFrames()
+ for i in range(depth):
+ frame = thread.GetFrameAtIndex(i)
+ self.assertTrue(frame.IsValid(), "current frame is valid")
+ if self.TraceOn():
+ print("Checking if function %s is main" % frame.GetFunctionName())
+
+ if 'main' == frame.GetFunctionName():
+ frame_id = frame.GetFrameID()
+ self.runCmd("frame select " + str(frame_id), RUN_SUCCEEDED)
+ self.expect("p argc", substrs = ['(int)', ' = 1'])
+ self.expect("p hello_world", substrs = ['Hello'])
+ self.expect("p argv[0]", substrs = ['a.out'])
+ self.expect("p null_ptr", substrs = ['= 0x0'])
+ return True
+ return False
+
+ def inferior_asserting_expr(self):
+ """Test that the lldb expression interpreter can read symbols after asserting."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Launch the process, and do not stop at the entry point.
+ target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.check_stop_reason()
+
+ process = target.GetProcess()
+ self.assertTrue(process.IsValid(), "current process is valid")
+
+ thread = process.GetThreadAtIndex(0)
+ self.assertTrue(thread.IsValid(), "current thread is valid")
+
+ # The lldb expression interpreter should be able to read from addresses of the inferior after a call to assert().
+ self.assertTrue(self.check_expr_in_main(thread), "cannot find 'main' in the backtrace")
+
+ def inferior_asserting_step(self):
+ """Test that lldb functions correctly after stepping through a call to assert()."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Launch the process, and do not stop at the entry point.
+ self.set_breakpoint(self.line)
+ target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['main.c:%d' % self.line,
+ 'stop reason = breakpoint'])
+
+ self.runCmd("next")
+ stop_reason = self.check_stop_reason()
+
+ # lldb should be able to read from registers from the inferior after asserting.
+ if "x86_64" in self.getArchitecture():
+ self.expect("register read rbp", substrs = ['rbp = 0x'])
+ if "i386" in self.getArchitecture():
+ self.expect("register read ebp", substrs = ['ebp = 0x'])
+
+ process = target.GetProcess()
+ self.assertTrue(process.IsValid(), "current process is valid")
+
+ thread = process.GetThreadAtIndex(0)
+ self.assertTrue(thread.IsValid(), "current thread is valid")
+
+ # The lldb expression interpreter should be able to read from addresses of the inferior after a call to assert().
+ self.assertTrue(self.check_expr_in_main(thread), "cannot find 'main' in the backtrace")
+
+ # And it should report the correct line number.
+ self.expect("thread backtrace all",
+ substrs = [stop_reason,
+ 'main.c:%d' % self.line])
diff --git a/packages/Python/lldbsuite/test/functionalities/inferior-assert/main.c b/packages/Python/lldbsuite/test/functionalities/inferior-assert/main.c
new file mode 100644
index 000000000000..6aec4c1023a9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/inferior-assert/main.c
@@ -0,0 +1,19 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+#include <assert.h>
+
+const char *hello_world = "Hello, assertion!";
+
+int main(int argc, const char* argv[])
+{
+ int *null_ptr = 0;
+ printf("%s\n", hello_world);
+ assert(null_ptr); // Assert here.
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/inferior-changed/Makefile b/packages/Python/lldbsuite/test/functionalities/inferior-changed/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/inferior-changed/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/inferior-changed/TestInferiorChanged.py b/packages/Python/lldbsuite/test/functionalities/inferior-changed/TestInferiorChanged.py
new file mode 100644
index 000000000000..830c7f69355f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/inferior-changed/TestInferiorChanged.py
@@ -0,0 +1,80 @@
+"""Test lldb reloads the inferior after it was changed during the session."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test import configuration
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ChangedInferiorTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfHostWindows
+ def test_inferior_crashing(self):
+ """Test lldb reloads the inferior after it was changed during the session."""
+ self.build()
+ self.inferior_crashing()
+ self.cleanup()
+ # lldb needs to recognize the inferior has changed. If lldb needs to check the
+ # new module timestamp, make sure it is not the same as the old one, so add a
+ # 1 second delay.
+ time.sleep(1)
+ d = {'C_SOURCES': 'main2.c'}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ self.inferior_not_crashing()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number of the crash.
+ self.line1 = line_number('main.c', '// Crash here.')
+ self.line2 = line_number('main2.c', '// Not crash here.')
+
+ def inferior_crashing(self):
+ """Inferior crashes upon launching; lldb should catch the event and stop."""
+ self.exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + self.exe, CURRENT_EXECUTABLE_SET)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # We should have one crashing thread
+ self.assertEqual(
+ len(lldbutil.get_crashed_threads(self, self.dbg.GetSelectedTarget().GetProcess())),
+ 1,
+ STOPPED_DUE_TO_EXC_BAD_ACCESS)
+
+ # And it should report the correct line number.
+ self.expect("thread backtrace all", substrs = ['main.c:%d' % self.line1])
+
+ def inferior_not_crashing(self):
+ """Test lldb reloads the inferior after it was changed during the session."""
+ self.runCmd("process kill")
+ self.runCmd("run", RUN_SUCCEEDED)
+ self.runCmd("process status")
+
+ self.assertNotEqual(
+ len(lldbutil.get_crashed_threads(self, self.dbg.GetSelectedTarget().GetProcess())),
+ 1,
+ "Inferior changed, but lldb did not perform a reload")
+
+ # Break inside the main.
+ lldbutil.run_break_set_by_file_and_line (self, "main2.c", self.line2, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ self.runCmd("frame variable int_ptr")
+ self.expect("frame variable *int_ptr",
+ substrs = ['= 7'])
+ self.expect("expression *int_ptr",
+ substrs = ['= 7'])
diff --git a/packages/Python/lldbsuite/test/functionalities/inferior-changed/main.c b/packages/Python/lldbsuite/test/functionalities/inferior-changed/main.c
new file mode 100644
index 000000000000..9d0706a0862d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/inferior-changed/main.c
@@ -0,0 +1,16 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+int main(int argc, const char* argv[])
+{
+ int *null_ptr = 0;
+ printf("Hello, segfault!\n");
+ printf("Now crash %d\n", *null_ptr); // Crash here.
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/inferior-changed/main2.c b/packages/Python/lldbsuite/test/functionalities/inferior-changed/main2.c
new file mode 100644
index 000000000000..9173e8c30b59
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/inferior-changed/main2.c
@@ -0,0 +1,18 @@
+//===-- main2.c -------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+#include <stdlib.h>
+
+int main(int argc, const char* argv[])
+{
+ int *int_ptr = (int *)malloc(sizeof(int));
+ *int_ptr = 7;
+ printf("Hello, world!\n");
+ printf("Now not crash %d\n", *int_ptr); // Not crash here.
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/inferior-crashing/Makefile b/packages/Python/lldbsuite/test/functionalities/inferior-crashing/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/inferior-crashing/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/inferior-crashing/TestInferiorCrashing.py b/packages/Python/lldbsuite/test/functionalities/inferior-crashing/TestInferiorCrashing.py
new file mode 100644
index 000000000000..c547df116c16
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/inferior-crashing/TestInferiorCrashing.py
@@ -0,0 +1,220 @@
+"""Test that lldb functions correctly after the inferior has crashed."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+import lldbsuite.test.lldbplatformutil as lldbplatformutil
+from lldbsuite.test.lldbtest import *
+
+class CrashingInferiorTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureFreeBSD("llvm.org/pr23699 SIGSEGV is reported as exception, not signal")
+ @expectedFailureWindows("llvm.org/pr24778") # This actually works, but the test relies on the output format instead of the API
+ def test_inferior_crashing(self):
+ """Test that lldb reliably catches the inferior crashing (command)."""
+ self.build()
+ self.inferior_crashing()
+
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test_inferior_crashing_register(self):
+ """Test that lldb reliably reads registers from the inferior after crashing (command)."""
+ self.build()
+ self.inferior_crashing_registers()
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test_inferior_crashing_python(self):
+ """Test that lldb reliably catches the inferior crashing (Python API)."""
+ self.build()
+ self.inferior_crashing_python()
+
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test_inferior_crashing_expr(self):
+ """Test that the lldb expression interpreter can read from the inferior after crashing (command)."""
+ self.build()
+ self.inferior_crashing_expr()
+
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test_inferior_crashing_step(self):
+ """Test that stepping after a crash behaves correctly."""
+ self.build()
+ self.inferior_crashing_step()
+
+ @expectedFailureFreeBSD('llvm.org/pr24939')
+ @expectedFailureWindows("llvm.org/pr24778")
+ @expectedFailureAndroid(archs=['aarch64'], api_levels=list(range(21 + 1))) # No eh_frame for sa_restorer
+ def test_inferior_crashing_step_after_break(self):
+ """Test that lldb functions correctly after stepping through a crash."""
+ self.build()
+ self.inferior_crashing_step_after_break()
+
+ @expectedFailureWindows("llvm.org/pr24778")
+ @skipIfLinux # Inferior exits after stepping after a segfault. This is working as intended IMHO.
+ def test_inferior_crashing_expr_step_and_expr(self):
+ """Test that lldb expressions work before and after stepping after a crash."""
+ self.build()
+ self.inferior_crashing_expr_step_expr()
+
+ def set_breakpoint(self, line):
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", line, num_expected_locations=1, loc_exact=True)
+
+ def check_stop_reason(self):
+ # We should have one crashing thread
+ self.assertEqual(
+ len(lldbutil.get_crashed_threads(self, self.dbg.GetSelectedTarget().GetProcess())),
+ 1,
+ STOPPED_DUE_TO_EXC_BAD_ACCESS)
+
+ def get_api_stop_reason(self):
+ return lldb.eStopReasonException
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number of the crash.
+ self.line = line_number('main.c', '// Crash here.')
+
+ def inferior_crashing(self):
+ """Inferior crashes upon launching; lldb should catch the event and stop."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+ # The exact stop reason depends on the platform
+ if self.platformIsDarwin():
+ stop_reason = 'stop reason = EXC_BAD_ACCESS'
+ elif self.getPlatform() == "linux":
+ stop_reason = 'stop reason = signal SIGSEGV'
+ else:
+ stop_reason = 'stop reason = invalid address'
+ self.expect("thread list", STOPPED_DUE_TO_EXC_BAD_ACCESS,
+ substrs = ['stopped',
+ stop_reason])
+
+ # And it should report the correct line number.
+ self.expect("thread backtrace all",
+ substrs = [stop_reason,
+ 'main.c:%d' % self.line])
+
+ def inferior_crashing_python(self):
+ """Inferior crashes upon launching; lldb should catch the event and stop."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now launch the process, and do not stop at entry point.
+ # Both argv and envp are null.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ if process.GetState() != lldb.eStateStopped:
+ self.fail("Process should be in the 'stopped' state, "
+ "instead the actual state is: '%s'" %
+ lldbutil.state_type_to_str(process.GetState()))
+
+ threads = lldbutil.get_crashed_threads(self, process)
+ self.assertEqual(len(threads), 1, "Failed to stop the thread upon bad access exception")
+
+ if self.TraceOn():
+ lldbutil.print_stacktrace(threads[0])
+
+ def inferior_crashing_registers(self):
+ """Test that lldb can read registers after crashing."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+ self.check_stop_reason()
+
+ # lldb should be able to read from registers from the inferior after crashing.
+ lldbplatformutil.check_first_register_readable(self)
+
+ def inferior_crashing_expr(self):
+ """Test that the lldb expression interpreter can read symbols after crashing."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+ self.check_stop_reason()
+
+ # The lldb expression interpreter should be able to read from addresses of the inferior after a crash.
+ self.expect("p argc",
+ startstr = '(int) $0 = 1')
+
+ self.expect("p hello_world",
+ substrs = ['Hello'])
+
+ def inferior_crashing_step(self):
+ """Test that lldb functions correctly after stepping through a crash."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ self.set_breakpoint(self.line)
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['main.c:%d' % self.line,
+ 'stop reason = breakpoint'])
+
+ self.runCmd("next")
+ self.check_stop_reason()
+
+ # The lldb expression interpreter should be able to read from addresses of the inferior after a crash.
+ self.expect("p argv[0]",
+ substrs = ['a.out'])
+ self.expect("p null_ptr",
+ substrs = ['= 0x0'])
+
+ # lldb should be able to read from registers from the inferior after crashing.
+ lldbplatformutil.check_first_register_readable(self)
+
+ # And it should report the correct line number.
+ self.expect("thread backtrace all",
+ substrs = ['main.c:%d' % self.line])
+
+ def inferior_crashing_step_after_break(self):
+ """Test that lldb behaves correctly when stepping after a crash."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+ self.check_stop_reason()
+
+ expected_state = 'exited' # Provide the exit code.
+ if self.platformIsDarwin():
+ expected_state = 'stopped' # TODO: Determine why 'next' and 'continue' have no effect after a crash.
+ elif re.match(".*-.*-.*-android", self.dbg.GetSelectedPlatform().GetTriple()):
+ expected_state = 'stopped' # android has a default SEGV handler, which will re-raise the signal, so we come up stopped again
+
+ self.expect("next",
+ substrs = ['Process', expected_state])
+
+ if expected_state == 'exited':
+ self.expect("thread list", error=True,substrs = ['Process must be launched'])
+ else:
+ self.check_stop_reason()
+
+ def inferior_crashing_expr_step_expr(self):
+ """Test that lldb expressions work before and after stepping after a crash."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+ self.check_stop_reason()
+
+ # The lldb expression interpreter should be able to read from addresses of the inferior after a crash.
+ self.expect("p argv[0]",
+ substrs = ['a.out'])
+
+ self.runCmd("next")
+ self.check_stop_reason()
+
+ # The lldb expression interpreter should be able to read from addresses of the inferior after a crash.
+ self.expect("p argv[0]",
+ substrs = ['a.out'])
diff --git a/packages/Python/lldbsuite/test/functionalities/inferior-crashing/main.c b/packages/Python/lldbsuite/test/functionalities/inferior-crashing/main.c
new file mode 100644
index 000000000000..3b7cfe4012bd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/inferior-crashing/main.c
@@ -0,0 +1,18 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+const char *hello_world = "Hello, segfault!";
+
+int main(int argc, const char* argv[])
+{
+ int *null_ptr = 0;
+ printf("%s\n", hello_world);
+ printf("Now crash %d\n", *null_ptr); // Crash here.
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/Makefile b/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/Makefile
new file mode 100644
index 000000000000..0f8e92e9193c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+CFLAGS_EXTRAS += -fomit-frame-pointer
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/TestRecursiveInferior.py b/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/TestRecursiveInferior.py
new file mode 100644
index 000000000000..8afc81f6892a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/TestRecursiveInferior.py
@@ -0,0 +1,220 @@
+"""Test that lldb functions correctly after the inferior has crashed while in a recursive routine."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+import lldbsuite.test.lldbplatformutil as lldbplatformutil
+from lldbsuite.test.lldbtest import *
+
+class CrashingRecursiveInferiorTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureFreeBSD("llvm.org/pr23699 SIGSEGV is reported as exception, not signal")
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test_recursive_inferior_crashing(self):
+ """Test that lldb reliably catches the inferior crashing (command)."""
+ self.build()
+ self.recursive_inferior_crashing()
+
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test_recursive_inferior_crashing_register(self):
+ """Test that lldb reliably reads registers from the inferior after crashing (command)."""
+ self.build()
+ self.recursive_inferior_crashing_registers()
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test_recursive_inferior_crashing_python(self):
+ """Test that lldb reliably catches the inferior crashing (Python API)."""
+ self.build()
+ self.recursive_inferior_crashing_python()
+
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test_recursive_inferior_crashing_expr(self):
+ """Test that the lldb expression interpreter can read from the inferior after crashing (command)."""
+ self.build()
+ self.recursive_inferior_crashing_expr()
+
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test_recursive_inferior_crashing_step(self):
+ """Test that stepping after a crash behaves correctly."""
+ self.build()
+ self.recursive_inferior_crashing_step()
+
+ @expectedFailureFreeBSD('llvm.org/pr24939')
+ @expectedFailureWindows("llvm.org/pr24778")
+ @expectedFailureAndroid(archs=['aarch64'], api_levels=list(range(21 + 1))) # No eh_frame for sa_restorer
+ def test_recursive_inferior_crashing_step_after_break(self):
+ """Test that lldb functions correctly after stepping through a crash."""
+ self.build()
+ self.recursive_inferior_crashing_step_after_break()
+
+ @expectedFailureFreeBSD('llvm.org/pr15989') # Couldn't allocate space for the stack frame
+ @skipIfLinux # Inferior exits after stepping after a segfault. This is working as intended IMHO.
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test_recursive_inferior_crashing_expr_step_and_expr(self):
+ """Test that lldb expressions work before and after stepping after a crash."""
+ self.build()
+ self.recursive_inferior_crashing_expr_step_expr()
+
+ def set_breakpoint(self, line):
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", line, num_expected_locations=1, loc_exact=True)
+
+ def check_stop_reason(self):
+ # We should have one crashing thread
+ self.assertEqual(
+ len(lldbutil.get_crashed_threads(self, self.dbg.GetSelectedTarget().GetProcess())),
+ 1,
+ STOPPED_DUE_TO_EXC_BAD_ACCESS)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number of the crash.
+ self.line = line_number('main.c', '// Crash here.')
+
+ def recursive_inferior_crashing(self):
+ """Inferior crashes upon launching; lldb should catch the event and stop."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The exact stop reason depends on the platform
+ if self.platformIsDarwin():
+ stop_reason = 'stop reason = EXC_BAD_ACCESS'
+ elif self.getPlatform() == "linux":
+ stop_reason = 'stop reason = signal SIGSEGV'
+ else:
+ stop_reason = 'stop reason = invalid address'
+ self.expect("thread list", STOPPED_DUE_TO_EXC_BAD_ACCESS,
+ substrs = ['stopped',
+ stop_reason])
+
+ # And it should report a backtrace that includes main and the crash site.
+ self.expect("thread backtrace all",
+ substrs = [stop_reason, 'main', 'argc', 'argv', 'recursive_function'])
+
+ # And it should report the correct line number.
+ self.expect("thread backtrace all",
+ substrs = [stop_reason,
+ 'main.c:%d' % self.line])
+
+ def recursive_inferior_crashing_python(self):
+ """Inferior crashes upon launching; lldb should catch the event and stop."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now launch the process, and do not stop at entry point.
+ # Both argv and envp are null.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ if process.GetState() != lldb.eStateStopped:
+ self.fail("Process should be in the 'stopped' state, "
+ "instead the actual state is: '%s'" %
+ lldbutil.state_type_to_str(process.GetState()))
+
+ threads = lldbutil.get_crashed_threads(self, process)
+ self.assertEqual(len(threads), 1, "Failed to stop the thread upon bad access exception")
+
+ if self.TraceOn():
+ lldbutil.print_stacktrace(threads[0])
+
+ def recursive_inferior_crashing_registers(self):
+ """Test that lldb can read registers after crashing."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+ self.check_stop_reason()
+
+ # lldb should be able to read from registers from the inferior after crashing.
+ lldbplatformutil.check_first_register_readable(self)
+
+ def recursive_inferior_crashing_expr(self):
+ """Test that the lldb expression interpreter can read symbols after crashing."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+ self.check_stop_reason()
+
+ # The lldb expression interpreter should be able to read from addresses of the inferior after a crash.
+ self.expect("p i",
+ startstr = '(int) $0 =')
+
+ def recursive_inferior_crashing_step(self):
+ """Test that lldb functions correctly after stepping through a crash."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ self.set_breakpoint(self.line)
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['main.c:%d' % self.line,
+ 'stop reason = breakpoint'])
+
+ self.runCmd("next")
+ self.check_stop_reason()
+
+ # The lldb expression interpreter should be able to read from addresses of the inferior after a crash.
+ self.expect("p i",
+ substrs = ['(int) $0 ='])
+
+ # lldb should be able to read from registers from the inferior after crashing.
+ lldbplatformutil.check_first_register_readable(self)
+
+ # And it should report the correct line number.
+ self.expect("thread backtrace all",
+ substrs = ['main.c:%d' % self.line])
+
+ def recursive_inferior_crashing_step_after_break(self):
+ """Test that lldb behaves correctly when stepping after a crash."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+ self.check_stop_reason()
+
+ expected_state = 'exited' # Provide the exit code.
+ if self.platformIsDarwin():
+ expected_state = 'stopped' # TODO: Determine why 'next' and 'continue' have no effect after a crash.
+ elif re.match(".*-.*-.*-android", self.dbg.GetSelectedPlatform().GetTriple()):
+ expected_state = 'stopped' # android has a default SEGV handler, which will re-raise the signal, so we come up stopped again
+
+
+ self.expect("next",
+ substrs = ['Process', expected_state])
+
+ if expected_state == 'exited':
+ self.expect("thread list", error=True,substrs = ['Process must be launched'])
+ else:
+ self.check_stop_reason()
+
+ def recursive_inferior_crashing_expr_step_expr(self):
+ """Test that lldb expressions work before and after stepping after a crash."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+ self.check_stop_reason()
+
+ # The lldb expression interpreter should be able to read from addresses of the inferior after a crash.
+ self.expect("p null",
+ startstr = '(char *) $0 = 0x0')
+
+ self.runCmd("next")
+
+ # The lldb expression interpreter should be able to read from addresses of the inferior after a step.
+ self.expect("p null",
+ startstr = '(char *) $1 = 0x0')
+
+ self.check_stop_reason()
diff --git a/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/main.c b/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/main.c
new file mode 100644
index 000000000000..25e6e8df0b9b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/inferior-crashing/recursive-inferior/main.c
@@ -0,0 +1,19 @@
+void recursive_function(int i)
+{
+ if (i < 10)
+ {
+ recursive_function(i + 1);
+ }
+ else
+ {
+ char *null=0;
+ *null = 0; // Crash here.
+ }
+}
+
+int main(int argc, char *argv[])
+{
+ recursive_function(0);
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/inline-stepping/Makefile b/packages/Python/lldbsuite/test/functionalities/inline-stepping/Makefile
new file mode 100644
index 000000000000..532f49555e5f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/inline-stepping/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../make
+
+CXX_SOURCES := calling.cpp
+
+ifneq (,$(findstring icc,$(CC)))
+ CXXFLAGS += -debug inline-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/inline-stepping/TestInlineStepping.py b/packages/Python/lldbsuite/test/functionalities/inline-stepping/TestInlineStepping.py
new file mode 100644
index 000000000000..3bdf6ec70e34
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/inline-stepping/TestInlineStepping.py
@@ -0,0 +1,270 @@
+"""Test stepping over and into inlined functions."""
+
+from __future__ import print_function
+
+
+
+import os, time, sys
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TestInlineStepping(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureFreeBSD('llvm.org/pr17214')
+ @expectedFailureIcc # Not really a bug. ICC combines two inlined functions.
+ @expectedFailureWindows("llvm.org/pr24778")
+ # failed 1/365 dosep runs, (i386-clang), TestInlineStepping.py:237 failed to stop at first breakpoint in main
+ @expectedFailureAll(oslist=["linux"], archs=["i386"])
+ def test_with_python_api(self):
+ """Test stepping over and into inlined functions."""
+ self.build()
+ self.inline_stepping()
+
+ @add_test_categories(['pyapi'])
+ def test_step_over_with_python_api(self):
+ """Test stepping over and into inlined functions."""
+ self.build()
+ self.inline_stepping_step_over()
+
+ @add_test_categories(['pyapi'])
+ def test_step_in_template_with_python_api(self):
+ """Test stepping in to templated functions."""
+ self.build()
+ self.step_in_template()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers that we will step to in main:
+ self.main_source = "calling.cpp"
+ self.source_lines = {}
+ functions = ['caller_ref_1', 'caller_ref_2', 'inline_ref_1', 'inline_ref_2', 'called_by_inline_ref', 'caller_trivial_1', 'caller_trivial_2', 'inline_trivial_1', 'inline_trivial_2', 'called_by_inline_trivial' ]
+ for name in functions:
+ self.source_lines[name] = line_number(self.main_source, "// In " + name + ".")
+ self.main_source_spec = lldb.SBFileSpec (self.main_source)
+
+ def do_step(self, step_type, destination_line_entry, test_stack_depth):
+ expected_stack_depth = self.thread.GetNumFrames()
+ if step_type == "into":
+ expected_stack_depth += 1
+ self.thread.StepInto()
+ elif step_type == "out":
+ expected_stack_depth -= 1
+ self.thread.StepOut()
+ elif step_type == "over":
+ self.thread.StepOver()
+ else:
+ self.fail ("Unrecognized step type: " + step_type)
+
+ threads = lldbutil.get_stopped_threads (self.process, lldb.eStopReasonPlanComplete)
+ if len(threads) != 1:
+ destination_description = lldb.SBStream()
+ destination_line_entry.GetDescription(destination_description)
+ self.fail ("Failed to stop due to step " + step_type + " operation stepping to: " + destination_description.GetData())
+
+ self.thread = threads[0]
+
+ stop_line_entry = self.thread.GetFrameAtIndex(0).GetLineEntry()
+ self.assertTrue (stop_line_entry.IsValid(), "Stop line entry was not valid.")
+
+ # Don't use the line entry equal operator because we don't care about the column number.
+ stop_at_right_place = (stop_line_entry.GetFileSpec() == destination_line_entry.GetFileSpec() and stop_line_entry.GetLine() == destination_line_entry.GetLine())
+ if stop_at_right_place == False:
+ destination_description = lldb.SBStream()
+ destination_line_entry.GetDescription(destination_description)
+
+ actual_description = lldb.SBStream()
+ stop_line_entry.GetDescription(actual_description)
+
+ self.fail ("Step " + step_type + " stopped at wrong place: expected: " + destination_description.GetData() + " got: " + actual_description.GetData() + ".")
+
+ real_stack_depth = self.thread.GetNumFrames()
+
+ if test_stack_depth and real_stack_depth != expected_stack_depth:
+ destination_description = lldb.SBStream()
+ destination_line_entry.GetDescription(destination_description)
+ self.fail ("Step %s to %s got wrong number of frames, should be: %d was: %d."%(step_type, destination_description.GetData(), expected_stack_depth, real_stack_depth))
+
+ def run_step_sequence(self, step_sequence):
+ """This function takes a list of duples instructing how to run the program. The first element in each duple is
+ a source pattern for the target location, and the second is the operation that will take you from the current
+ source location to the target location. It will then run all the steps in the sequence.
+ It will check that you arrived at the expected source location at each step, and that the stack depth changed
+ correctly for the operation in the sequence."""
+
+ target_line_entry = lldb.SBLineEntry()
+ target_line_entry.SetFileSpec(self.main_source_spec)
+
+ test_stack_depth = True
+ # Work around for <rdar://problem/16363195>, the darwin unwinder seems flakey about whether it duplicates the first frame
+ # or not, which makes counting stack depth unreliable.
+ if self.platformIsDarwin():
+ test_stack_depth = False
+
+ for step_pattern in step_sequence:
+ step_stop_line = line_number (self.main_source, step_pattern[0])
+ target_line_entry.SetLine(step_stop_line)
+ self.do_step (step_pattern[1], target_line_entry, test_stack_depth)
+
+ def inline_stepping(self):
+ """Use Python APIs to test stepping over and hitting breakpoints."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ break_1_in_main = target.BreakpointCreateBySourceRegex ('// Stop here and step over to set up stepping over.', self.main_source_spec)
+ self.assertTrue(break_1_in_main, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ self.process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(self.process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ threads = lldbutil.get_threads_stopped_at_breakpoint (self.process, break_1_in_main)
+
+ if len(threads) != 1:
+ self.fail ("Failed to stop at first breakpoint in main.")
+
+ self.thread = threads[0]
+
+ # Step over the inline_value = 0 line to get us to inline_trivial_1 called from main. Doing it this way works
+ # around a bug in lldb where the breakpoint on the containing line of an inlined function with no return value
+ # gets set past the insertion line in the function.
+ # Then test stepping over a simple inlined function. Note, to test all the parts of the inlined stepping
+ # the calls inline_stepping_1 and inline_stepping_2 should line up at the same address, that way we will test
+ # the "virtual" stepping.
+ # FIXME: Put in a check to see if that is true and warn if it is not.
+
+ step_sequence = [["// At inline_trivial_1 called from main.", "over"],
+ ["// At first call of caller_trivial_1 in main.", "over"]]
+ self.run_step_sequence(step_sequence)
+
+ # Now step from caller_ref_1 all the way into called_by_inline_trivial
+
+ step_sequence = [["// In caller_trivial_1.", "into"],
+ ["// In caller_trivial_2.", "into"],
+ ["// In inline_trivial_1.", "into"],
+ ["// In inline_trivial_2.", "into"],
+ ["// At caller_by_inline_trivial in inline_trivial_2.", "over"],
+ ["// In called_by_inline_trivial.", "into"]]
+ self.run_step_sequence(step_sequence)
+
+ # Now run to the inline_trivial_1 just before the immediate step into inline_trivial_2:
+
+ break_2_in_main = target.BreakpointCreateBySourceRegex ('// At second call of caller_trivial_1 in main.', self.main_source_spec)
+ self.assertTrue(break_2_in_main, VALID_BREAKPOINT)
+
+ threads = lldbutil.continue_to_breakpoint (self.process, break_2_in_main)
+ self.assertTrue (len(threads) == 1, "Successfully ran to call site of second caller_trivial_1 call.")
+ self.thread = threads[0]
+
+ step_sequence = [["// In caller_trivial_1.", "into"],
+ ["// In caller_trivial_2.", "into"],
+ ["// In inline_trivial_1.", "into"]]
+ self.run_step_sequence(step_sequence)
+
+ # Then call some trivial function, and make sure we end up back where we were in the inlined call stack:
+
+ frame = self.thread.GetFrameAtIndex(0)
+ before_line_entry = frame.GetLineEntry()
+ value = frame.EvaluateExpression ("function_to_call()")
+ after_line_entry = frame.GetLineEntry()
+
+ self.assertTrue (before_line_entry.GetLine() == after_line_entry.GetLine(), "Line entry before and after function calls are the same.")
+
+ # Now make sure stepping OVER in the middle of the stack works, and then check finish from the inlined frame:
+
+ step_sequence = [["// At increment in inline_trivial_1.", "over"],
+ ["// At increment in caller_trivial_2.", "out"]]
+ self.run_step_sequence(step_sequence)
+
+
+ # Now run to the place in main just before the first call to caller_ref_1:
+
+ break_3_in_main = target.BreakpointCreateBySourceRegex ('// At first call of caller_ref_1 in main.', self.main_source_spec)
+ self.assertTrue(break_3_in_main, VALID_BREAKPOINT)
+
+ threads = lldbutil.continue_to_breakpoint (self.process, break_3_in_main)
+ self.assertTrue (len(threads) == 1, "Successfully ran to call site of first caller_ref_1 call.")
+ self.thread = threads[0]
+
+ step_sequence = [["// In caller_ref_1.", "into"],
+ ["// In caller_ref_2.", "into"],
+ ["// In inline_ref_1.", "into"],
+ ["// In inline_ref_2.", "into"],
+ ["// In called_by_inline_ref.", "into"],
+ ["// In inline_ref_2.", "out"],
+ ["// In inline_ref_1.", "out"],
+ ["// At increment in inline_ref_1.", "over"],
+ ["// In caller_ref_2.", "out"],
+ ["// At increment in caller_ref_2.", "over"]]
+ self.run_step_sequence (step_sequence)
+
+ def inline_stepping_step_over(self):
+ """Use Python APIs to test stepping over and hitting breakpoints."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ break_1_in_main = target.BreakpointCreateBySourceRegex ('// At second call of caller_ref_1 in main.', self.main_source_spec)
+ self.assertTrue(break_1_in_main, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ self.process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(self.process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ threads = lldbutil.get_threads_stopped_at_breakpoint (self.process, break_1_in_main)
+
+ if len(threads) != 1:
+ self.fail ("Failed to stop at first breakpoint in main.")
+
+ self.thread = threads[0]
+
+ step_sequence = [["// In caller_ref_1.", "into"],
+ ["// In caller_ref_2.", "into"],
+ ["// At increment in caller_ref_2.", "over"]]
+ self.run_step_sequence (step_sequence)
+
+ def step_in_template(self):
+ """Use Python APIs to test stepping in to templated functions."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ break_1_in_main = target.BreakpointCreateBySourceRegex ('// Call max_value template', self.main_source_spec)
+ self.assertTrue(break_1_in_main, VALID_BREAKPOINT)
+
+ break_2_in_main = target.BreakpointCreateBySourceRegex ('// Call max_value specialized', self.main_source_spec)
+ self.assertTrue(break_2_in_main, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ self.process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(self.process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ threads = lldbutil.get_threads_stopped_at_breakpoint (self.process, break_1_in_main)
+
+ if len(threads) != 1:
+ self.fail ("Failed to stop at first breakpoint in main.")
+
+ self.thread = threads[0]
+
+ step_sequence = [["// In max_value template", "into"]]
+ self.run_step_sequence(step_sequence)
+
+ threads = lldbutil.continue_to_breakpoint (self.process, break_2_in_main)
+ self.assertEqual(len(threads), 1, "Successfully ran to call site of second caller_trivial_1 call.")
+ self.thread = threads[0]
+
+ step_sequence = [["// In max_value specialized", "into"]]
+ self.run_step_sequence(step_sequence)
diff --git a/packages/Python/lldbsuite/test/functionalities/inline-stepping/calling.cpp b/packages/Python/lldbsuite/test/functionalities/inline-stepping/calling.cpp
new file mode 100644
index 000000000000..9982fbf42734
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/inline-stepping/calling.cpp
@@ -0,0 +1,136 @@
+#include <algorithm>
+#include <cstdio>
+#include <string>
+
+inline int inline_ref_1 (int &value) __attribute__((always_inline));
+inline int inline_ref_2 (int &value) __attribute__((always_inline));
+
+int caller_ref_1 (int &value);
+int caller_ref_2 (int &value);
+
+int called_by_inline_ref (int &value);
+
+inline void inline_trivial_1 () __attribute__((always_inline));
+inline void inline_trivial_2 () __attribute__((always_inline));
+
+void caller_trivial_1 ();
+void caller_trivial_2 ();
+
+void called_by_inline_trivial ();
+
+static int inline_value;
+
+int
+function_to_call ()
+{
+ return inline_value;
+}
+
+int
+caller_ref_1 (int &value)
+{
+ int increment = caller_ref_2(value); // In caller_ref_1.
+ value += increment; // At increment in caller_ref_1.
+ return value;
+}
+
+int
+caller_ref_2 (int &value)
+{
+ int increment = inline_ref_1 (value); // In caller_ref_2.
+ value += increment; // At increment in caller_ref_2.
+ return value;
+}
+
+int
+called_by_inline_ref (int &value)
+{
+ value += 1; // In called_by_inline_ref.
+ return value;
+}
+
+int
+inline_ref_1 (int &value)
+{
+ int increment = inline_ref_2(value); // In inline_ref_1.
+ value += increment; // At increment in inline_ref_1.
+ return value;
+}
+
+int
+inline_ref_2 (int &value)
+{
+ int increment = called_by_inline_ref (value); // In inline_ref_2.
+ value += 1; // At increment in inline_ref_2.
+ return value;
+}
+
+void
+caller_trivial_1 ()
+{
+ caller_trivial_2(); // In caller_trivial_1.
+ inline_value += 1;
+}
+
+void
+caller_trivial_2 ()
+{
+ inline_trivial_1 (); // In caller_trivial_2.
+ inline_value += 1; // At increment in caller_trivial_2.
+}
+
+void
+called_by_inline_trivial ()
+{
+ inline_value += 1; // In called_by_inline_trivial.
+}
+
+void
+inline_trivial_1 ()
+{
+ inline_trivial_2(); // In inline_trivial_1.
+ inline_value += 1; // At increment in inline_trivial_1.
+}
+
+void
+inline_trivial_2 ()
+{
+ inline_value += 1; // In inline_trivial_2.
+ called_by_inline_trivial (); // At caller_by_inline_trivial in inline_trivial_2.
+}
+
+template<typename T> T
+max_value(const T& lhs, const T& rhs)
+{
+ return std::max(lhs, rhs); // In max_value template
+}
+
+template<> std::string
+max_value(const std::string& lhs, const std::string& rhs)
+{
+ return (lhs.size() > rhs.size()) ? lhs : rhs; // In max_value specialized
+}
+
+int
+main (int argc, char **argv)
+{
+
+ inline_value = 0; // Stop here and step over to set up stepping over.
+
+ inline_trivial_1 (); // At inline_trivial_1 called from main.
+
+ caller_trivial_1(); // At first call of caller_trivial_1 in main.
+
+ caller_trivial_1(); // At second call of caller_trivial_1 in main.
+
+ caller_ref_1 (argc); // At first call of caller_ref_1 in main.
+
+ caller_ref_1 (argc); // At second call of caller_ref_1 in main.
+
+ function_to_call (); // Make sure debug info for this function gets generated.
+
+ max_value(123, 456); // Call max_value template
+ max_value(std::string("abc"), std::string("0022")); // Call max_value specialized
+
+ return 0; // About to return from main.
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/Makefile b/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/TestJITLoaderGDB.py b/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/TestJITLoaderGDB.py
new file mode 100644
index 000000000000..c7abf3464412
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/TestJITLoaderGDB.py
@@ -0,0 +1,37 @@
+"""Test for the JITLoaderGDB interface"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+import re
+
+
+class JITLoaderGDBTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipTestIfFn(lambda x: True, "llvm.org/pr24702", "Skipped because the test crashes the test runner")
+ @unittest2.expectedFailure("llvm.org/pr24702")
+ def test_bogus_values(self):
+ """Test that we handle inferior misusing the GDB JIT interface"""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # launch the process, do not stop at entry point.
+ process = target.LaunchSimple(None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The inferior will now pass bogus values over the interface. Make sure we don't crash.
+
+ self.assertEqual(process.GetState(), lldb.eStateExited)
+ self.assertEqual(process.GetExitStatus(), 0)
diff --git a/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/main.c b/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/main.c
new file mode 100644
index 000000000000..6a8ec50e6637
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/jitloader_gdb/main.c
@@ -0,0 +1,44 @@
+#include <inttypes.h>
+
+// GDB JIT interface
+enum JITAction { JIT_NOACTION, JIT_REGISTER_FN, JIT_UNREGISTER_FN };
+
+struct JITCodeEntry
+{
+ struct JITCodeEntry* next;
+ struct JITCodeEntry* prev;
+ const char *symfile_addr;
+ uint64_t symfile_size;
+};
+
+struct JITDescriptor
+{
+ uint32_t version;
+ uint32_t action_flag;
+ struct JITCodeEntry* relevant_entry;
+ struct JITCodeEntry* first_entry;
+};
+
+struct JITDescriptor __jit_debug_descriptor = { 1, JIT_NOACTION, 0, 0 };
+
+void __jit_debug_register_code()
+{
+}
+// end GDB JIT interface
+
+struct JITCodeEntry entry;
+
+int main()
+{
+ // Create a code entry with a bogus size
+ entry.next = entry.prev = 0;
+ entry.symfile_addr = (char *)&entry;
+ entry.symfile_size = (uint64_t)47<<32;
+
+ __jit_debug_descriptor.relevant_entry = __jit_debug_descriptor.first_entry = &entry;
+ __jit_debug_descriptor.action_flag = JIT_REGISTER_FN;
+
+ __jit_debug_register_code();
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/Makefile b/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/TestLaunchWithShellExpand.py b/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/TestLaunchWithShellExpand.py
new file mode 100644
index 000000000000..8f712dc21110
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/TestLaunchWithShellExpand.py
@@ -0,0 +1,97 @@
+"""
+Test that argdumper is a viable launching strategy.
+"""
+from __future__ import print_function
+
+
+
+import lldb
+import os
+import time
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class LaunchWithShellExpandTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureFreeBSD("llvm.org/pr22627 process launch w/ shell expansion not working")
+ @expectedFailureLinux("llvm.org/pr22627 process launch w/ shell expansion not working")
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test(self):
+ self.build()
+ exe = os.path.join (os.getcwd(), "a.out")
+
+ self.runCmd("target create %s" % exe)
+
+ # Create the target
+ target = self.dbg.CreateTarget(exe)
+
+ # Create any breakpoints we need
+ breakpoint = target.BreakpointCreateBySourceRegex ('break here', lldb.SBFileSpec ("main.cpp", False))
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ self.runCmd("process launch -X true -w %s -- fi*.tx?" % (os.getcwd()))
+
+ process = self.process()
+
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ STOPPED_DUE_TO_BREAKPOINT)
+
+ thread = process.GetThreadAtIndex (0)
+
+ self.assertTrue (thread.IsValid(),
+ "Process stopped at 'main' should have a valid thread");
+
+ stop_reason = thread.GetStopReason()
+
+ self.assertTrue (stop_reason == lldb.eStopReasonBreakpoint,
+ "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint");
+
+ self.expect("frame variable argv[1]", substrs=['file1.txt'])
+ self.expect("frame variable argv[2]", substrs=['file2.txt'])
+ self.expect("frame variable argv[3]", substrs=['file3.txt'])
+ self.expect("frame variable argv[4]", substrs=['file4.txy'])
+ self.expect("frame variable argv[5]", substrs=['file5.tyx'], matching=False)
+
+ self.runCmd("process kill")
+
+ self.runCmd('process launch -X true -w %s -- "foo bar"' % (os.getcwd()))
+
+ process = self.process()
+
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ STOPPED_DUE_TO_BREAKPOINT)
+
+ thread = process.GetThreadAtIndex (0)
+
+ self.assertTrue (thread.IsValid(),
+ "Process stopped at 'main' should have a valid thread");
+
+ stop_reason = thread.GetStopReason()
+
+ self.assertTrue (stop_reason == lldb.eStopReasonBreakpoint,
+ "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint");
+
+ self.expect("frame variable argv[1]", substrs=['foo bar'])
+
+ self.runCmd("process kill")
+
+ self.runCmd('process launch -X true -w %s -- foo\ bar' % (os.getcwd()))
+
+ process = self.process()
+
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ STOPPED_DUE_TO_BREAKPOINT)
+
+ thread = process.GetThreadAtIndex (0)
+
+ self.assertTrue (thread.IsValid(),
+ "Process stopped at 'main' should have a valid thread");
+
+ stop_reason = thread.GetStopReason()
+
+ self.assertTrue (stop_reason == lldb.eStopReasonBreakpoint,
+ "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint");
+
+ self.expect("frame variable argv[1]", substrs=['foo bar'])
diff --git a/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/file1.txt b/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/file1.txt
new file mode 100644
index 000000000000..e69de29bb2d1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/file1.txt
diff --git a/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/file2.txt b/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/file2.txt
new file mode 100644
index 000000000000..e69de29bb2d1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/file2.txt
diff --git a/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/file3.txt b/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/file3.txt
new file mode 100644
index 000000000000..e69de29bb2d1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/file3.txt
diff --git a/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/file4.txy b/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/file4.txy
new file mode 100644
index 000000000000..e69de29bb2d1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/file4.txy
diff --git a/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/file5.tyx b/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/file5.tyx
new file mode 100644
index 000000000000..e69de29bb2d1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/file5.tyx
diff --git a/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/foo bar b/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/foo bar
new file mode 100644
index 000000000000..e69de29bb2d1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/foo bar
diff --git a/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/main.cpp b/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/main.cpp
new file mode 100644
index 000000000000..cbef8d1e6da1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/launch_with_shellexpand/main.cpp
@@ -0,0 +1,5 @@
+int
+main (int argc, char const **argv)
+{
+ return 0; // break here
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/load_unload/Makefile b/packages/Python/lldbsuite/test/functionalities/load_unload/Makefile
new file mode 100644
index 000000000000..779745c4d26c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/load_unload/Makefile
@@ -0,0 +1,24 @@
+LEVEL := ../../make
+
+LIB_PREFIX := loadunload_
+
+LD_EXTRAS := -L. -l$(LIB_PREFIX)d -ldl
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
+
+.PHONY:
+a.out: lib_a lib_b lib_c lib_d hidden_lib_d
+
+lib_%:
+ $(MAKE) -f $*.mk
+
+hidden_lib_d:
+ $(MAKE) -C hidden
+
+clean::
+ $(MAKE) -f a.mk clean
+ $(MAKE) -f b.mk clean
+ $(MAKE) -f c.mk clean
+ $(MAKE) -f d.mk clean
+ $(MAKE) -C hidden clean
diff --git a/packages/Python/lldbsuite/test/functionalities/load_unload/TestLoadUnload.py b/packages/Python/lldbsuite/test/functionalities/load_unload/TestLoadUnload.py
new file mode 100644
index 000000000000..481e7c887bd0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/load_unload/TestLoadUnload.py
@@ -0,0 +1,357 @@
+"""
+Test that breakpoint by symbol name works correctly with dynamic libs.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+@skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently
+class LoadUnloadTestCase(TestBase):
+
+ def getCategories (self):
+ return ['basic_process']
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break for main.cpp.
+ self.line = line_number('main.cpp',
+ '// Set break point at this line for test_lldb_process_load_and_unload_commands().')
+ self.line_d_function = line_number('d.cpp',
+ '// Find this line number within d_dunction().')
+ if not self.platformIsDarwin():
+ if not lldb.remote_platform and "LD_LIBRARY_PATH" in os.environ:
+ self.runCmd("settings set target.env-vars " + self.dylibPath + "=" + os.environ["LD_LIBRARY_PATH"] + ":" + os.getcwd())
+ else:
+ if lldb.remote_platform:
+ wd = lldb.remote_platform.GetWorkingDirectory()
+ else:
+ wd = os.getcwd()
+ self.runCmd("settings set target.env-vars " + self.dylibPath + "=" + wd)
+
+ def copy_shlibs_to_remote(self, hidden_dir=False):
+ """ Copies the shared libs required by this test suite to remote.
+ Does nothing in case of non-remote platforms.
+ """
+ if lldb.remote_platform:
+ cwd = os.getcwd()
+ shlibs = ['libloadunload_a.so', 'libloadunload_b.so',
+ 'libloadunload_c.so', 'libloadunload_d.so']
+ wd = lldb.remote_platform.GetWorkingDirectory()
+ for f in shlibs:
+ err = lldb.remote_platform.Put(
+ lldb.SBFileSpec(os.path.join(cwd, f)),
+ lldb.SBFileSpec(os.path.join(wd, f)))
+ if err.Fail():
+ raise RuntimeError(
+ "Unable copy '%s' to '%s'.\n>>> %s" %
+ (f, wd, err.GetCString()))
+ if hidden_dir:
+ shlib = 'libloadunload_d.so'
+ hidden_dir = os.path.join(wd, 'hidden')
+ hidden_file = os.path.join(hidden_dir, shlib)
+ err = lldb.remote_platform.MakeDirectory(hidden_dir)
+ if err.Fail():
+ raise RuntimeError(
+ "Unable to create a directory '%s'." % hidden_dir)
+ err = lldb.remote_platform.Put(
+ lldb.SBFileSpec(os.path.join(cwd, 'hidden', shlib)),
+ lldb.SBFileSpec(hidden_file))
+ if err.Fail():
+ raise RuntimeError(
+ "Unable copy 'libloadunload_d.so' to '%s'.\n>>> %s" %
+ (wd, err.GetCString()))
+
+ @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support
+ @not_remote_testsuite_ready
+ @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently
+ def test_modules_search_paths(self):
+ """Test target modules list after loading a different copy of the library libd.dylib, and verifies that it works with 'target modules search-paths add'."""
+
+ # Invoke the default build rule.
+ self.build()
+
+ if self.platformIsDarwin():
+ dylibName = 'libloadunload_d.dylib'
+ else:
+ dylibName = 'libloadunload_d.so'
+
+ # The directory with the dynamic library we did not link to.
+ new_dir = os.path.join(os.getcwd(), "hidden")
+
+ old_dylib = os.path.join(os.getcwd(), dylibName)
+ new_dylib = os.path.join(new_dir, dylibName)
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ self.expect("target modules list",
+ substrs = [old_dylib])
+ #self.expect("target modules list -t 3",
+ # patterns = ["%s-[^-]*-[^-]*" % self.getArchitecture()])
+ # Add an image search path substitution pair.
+ self.runCmd("target modules search-paths add %s %s" % (os.getcwd(), new_dir))
+
+ self.expect("target modules search-paths list",
+ substrs = [os.getcwd(), new_dir])
+
+ self.expect("target modules search-paths query %s" % os.getcwd(), "Image search path successfully transformed",
+ substrs = [new_dir])
+
+ # Obliterate traces of libd from the old location.
+ os.remove(old_dylib)
+ # Inform (DY)LD_LIBRARY_PATH of the new path, too.
+ env_cmd_string = "settings set target.env-vars " + self.dylibPath + "=" + new_dir
+ if self.TraceOn():
+ print("Set environment to: ", env_cmd_string)
+ self.runCmd(env_cmd_string)
+ self.runCmd("settings show target.env-vars")
+
+ remove_dyld_path_cmd = "settings remove target.env-vars " + self.dylibPath
+ self.addTearDownHook(lambda: self.dbg.HandleCommand(remove_dyld_path_cmd))
+
+ self.runCmd("run")
+
+ self.expect("target modules list", "LLDB successfully locates the relocated dynamic library",
+ substrs = [new_dylib])
+
+ @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support
+ @skipUnlessListedRemote(['android'])
+ @expectedFailureAndroid # wrong source file shows up for hidden library
+ @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently
+ def test_dyld_library_path(self):
+ """Test (DY)LD_LIBRARY_PATH after moving libd.dylib, which defines d_function, somewhere else."""
+
+ # Invoke the default build rule.
+ self.build()
+ self.copy_shlibs_to_remote(hidden_dir=True)
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ if self.platformIsDarwin():
+ dylibName = 'libloadunload_d.dylib'
+ dsymName = 'libloadunload_d.dylib.dSYM'
+ else:
+ dylibName = 'libloadunload_d.so'
+
+ # The directory to relocate the dynamic library and its debugging info.
+ special_dir = "hidden"
+ if lldb.remote_platform:
+ wd = lldb.remote_platform.GetWorkingDirectory()
+ else:
+ wd = os.getcwd()
+
+ old_dir = wd
+ new_dir = os.path.join(wd, special_dir)
+ old_dylib = os.path.join(old_dir, dylibName)
+
+ remove_dyld_path_cmd = "settings remove target.env-vars " + self.dylibPath
+ self.addTearDownHook(lambda: self.dbg.HandleCommand(remove_dyld_path_cmd))
+
+ # For now we don't track (DY)LD_LIBRARY_PATH, so the old library will be in
+ # the modules list.
+ self.expect("target modules list",
+ substrs = [os.path.basename(old_dylib)],
+ matching=True)
+
+ lldbutil.run_break_set_by_file_and_line (self, "d.cpp", self.line_d_function, num_expected_locations=1)
+ # After run, make sure the non-hidden library is picked up.
+ self.expect("run", substrs=["return", "700"])
+
+ self.runCmd("continue")
+
+ # Add the hidden directory first in the search path.
+ env_cmd_string = ("settings set target.env-vars %s=%s" %
+ (self.dylibPath, new_dir))
+ if not self.platformIsDarwin():
+ env_cmd_string += ":" + wd
+ self.runCmd(env_cmd_string)
+
+ # This time, the hidden library should be picked up.
+ self.expect("run", substrs=["return", "12345"])
+
+ @expectedFailureAll(bugnumber="llvm.org/pr25805", hostoslist=["windows"], compiler="gcc", archs=["i386"], triple='.*-android')
+ @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support
+ @skipUnlessListedRemote(['android'])
+ @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently
+ def test_lldb_process_load_and_unload_commands(self):
+ """Test that lldb process load/unload command work correctly."""
+
+ # Invoke the default build rule.
+ self.build()
+ self.copy_shlibs_to_remote()
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break at main.cpp before the call to dlopen().
+ # Use lldb's process load command to load the dylib, instead.
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ if lldb.remote_platform:
+ shlib_dir = lldb.remote_platform.GetWorkingDirectory()
+ else:
+ shlib_dir = self.mydir
+
+ if self.platformIsDarwin():
+ dylibName = 'libloadunload_a.dylib'
+ else:
+ dylibName = 'libloadunload_a.so'
+
+ # Make sure that a_function does not exist at this point.
+ self.expect("image lookup -n a_function", "a_function should not exist yet",
+ error=True, matching=False, patterns = ["1 match found"])
+
+ # Use lldb 'process load' to load the dylib.
+ self.expect("process load %s --install" % dylibName, "%s loaded correctly" % dylibName,
+ patterns = ['Loading "%s".*ok' % dylibName,
+ 'Image [0-9]+ loaded'])
+
+ # Search for and match the "Image ([0-9]+) loaded" pattern.
+ output = self.res.GetOutput()
+ pattern = re.compile("Image ([0-9]+) loaded")
+ for l in output.split(os.linesep):
+ #print("l:", l)
+ match = pattern.search(l)
+ if match:
+ break
+ index = match.group(1)
+
+ # Now we should have an entry for a_function.
+ self.expect("image lookup -n a_function", "a_function should now exist",
+ patterns = ["1 match found .*%s" % dylibName])
+
+ # Use lldb 'process unload' to unload the dylib.
+ self.expect("process unload %s" % index, "%s unloaded correctly" % dylibName,
+ patterns = ["Unloading .* with index %s.*ok" % index])
+
+ self.runCmd("process continue")
+
+ @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support
+ @skipUnlessListedRemote(['android'])
+ def test_load_unload(self):
+ """Test breakpoint by name works correctly with dlopen'ing."""
+
+ # Invoke the default build rule.
+ self.build()
+ self.copy_shlibs_to_remote()
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break by function name a_function (not yet loaded).
+ lldbutil.run_break_set_by_symbol (self, "a_function", num_expected_locations=0)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint and at a_function.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'a_function',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ # Issue the 'contnue' command. We should stop agaian at a_function.
+ # The stop reason of the thread should be breakpoint and at a_function.
+ self.runCmd("continue")
+
+ # rdar://problem/8508987
+ # The a_function breakpoint should be encountered twice.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'a_function',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 2.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 2'])
+
+ @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support
+ @skipUnlessListedRemote(['android'])
+ @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently
+ def test_step_over_load (self):
+ """Test stepping over code that loads a shared library works correctly."""
+
+ # Invoke the default build rule.
+ self.build()
+ self.copy_shlibs_to_remote()
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break by function name a_function (not yet loaded).
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint and at a_function.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ self.runCmd("thread step-over", "Stepping over function that loads library")
+
+ # The stop reason should be step end.
+ self.expect("thread list", "step over succeeded.",
+ substrs = ['stopped',
+ 'stop reason = step over'])
+
+ @skipIfFreeBSD # llvm.org/pr14424 - missing FreeBSD Makefiles/testcase support
+ @skipUnlessListedRemote(['android'])
+ @skipIfWindows # Windows doesn't have dlopen and friends, dynamic libraries work differently
+ @unittest2.expectedFailure("llvm.org/pr25806")
+ def test_static_init_during_load (self):
+ """Test that we can set breakpoints correctly in static initializers"""
+
+ self.build()
+ self.copy_shlibs_to_remote()
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ a_init_bp_num = lldbutil.run_break_set_by_symbol(self, "a_init", num_expected_locations=0)
+ b_init_bp_num = lldbutil.run_break_set_by_symbol(self, "b_init", num_expected_locations=0)
+ d_init_bp_num = lldbutil.run_break_set_by_symbol(self, "d_init", num_expected_locations=1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'd_init',
+ 'stop reason = breakpoint %d' % d_init_bp_num])
+
+ self.runCmd("continue")
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'a_init',
+ 'stop reason = breakpoint %d' % a_init_bp_num])
+ self.expect("thread backtrace",
+ substrs = ['a_init',
+ 'dlopen',
+ 'main'])
+
+ self.runCmd("continue")
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'b_init',
+ 'stop reason = breakpoint %d' % b_init_bp_num])
+ self.expect("thread backtrace",
+ substrs = ['b_init',
+ 'dlopen',
+ 'main'])
diff --git a/packages/Python/lldbsuite/test/functionalities/load_unload/a.cpp b/packages/Python/lldbsuite/test/functionalities/load_unload/a.cpp
new file mode 100644
index 000000000000..235749aef74a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/load_unload/a.cpp
@@ -0,0 +1,22 @@
+//===-- a.c -----------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+extern int b_function ();
+
+int a_init()
+{
+ return 234;
+}
+
+int a_global = a_init();
+
+extern "C" int
+a_function ()
+{
+ return b_function ();
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/load_unload/a.mk b/packages/Python/lldbsuite/test/functionalities/load_unload/a.mk
new file mode 100644
index 000000000000..0eb810e21787
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/load_unload/a.mk
@@ -0,0 +1,23 @@
+LEVEL := ../../make
+
+LIB_PREFIX := loadunload_
+
+CFLAGS_EXTRAS := -fPIC
+LD_EXTRAS := -L. -l$(LIB_PREFIX)b
+
+DYLIB_NAME := $(LIB_PREFIX)a
+DYLIB_CXX_SOURCES := a.cpp
+DYLIB_ONLY := YES
+
+CXXFLAGS += -fPIC
+
+include $(LEVEL)/Makefile.rules
+
+.PHONY:
+$(DYLIB_FILENAME): lib_b
+
+lib_b:
+ "$(MAKE)" -f b.mk
+
+clean::
+ "$(MAKE)" -f b.mk clean
diff --git a/packages/Python/lldbsuite/test/functionalities/load_unload/b.cpp b/packages/Python/lldbsuite/test/functionalities/load_unload/b.cpp
new file mode 100644
index 000000000000..4d383169b79c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/load_unload/b.cpp
@@ -0,0 +1,21 @@
+//===-- b.c -----------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+int b_init()
+{
+ return 345;
+}
+
+int b_global = b_init();
+
+int
+b_function ()
+{
+ return 500;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/load_unload/b.mk b/packages/Python/lldbsuite/test/functionalities/load_unload/b.mk
new file mode 100644
index 000000000000..c1b0877d72a4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/load_unload/b.mk
@@ -0,0 +1,11 @@
+LEVEL := ../../make
+
+LIB_PREFIX := loadunload_
+
+DYLIB_NAME := $(LIB_PREFIX)b
+DYLIB_CXX_SOURCES := b.cpp
+DYLIB_ONLY := YES
+
+CXXFLAGS += -fPIC
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/load_unload/c.cpp b/packages/Python/lldbsuite/test/functionalities/load_unload/c.cpp
new file mode 100644
index 000000000000..f0dfb4ec0d38
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/load_unload/c.cpp
@@ -0,0 +1,13 @@
+//===-- c.c -----------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+extern "C" int
+c_function ()
+{
+ return 600;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/load_unload/c.mk b/packages/Python/lldbsuite/test/functionalities/load_unload/c.mk
new file mode 100644
index 000000000000..5b5691efeef4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/load_unload/c.mk
@@ -0,0 +1,11 @@
+LEVEL := ../../make
+
+LIB_PREFIX := loadunload_
+
+DYLIB_NAME := $(LIB_PREFIX)c
+DYLIB_CXX_SOURCES := c.cpp
+DYLIB_ONLY := YES
+
+CXXFLAGS += -fPIC
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/load_unload/cmds.txt b/packages/Python/lldbsuite/test/functionalities/load_unload/cmds.txt
new file mode 100644
index 000000000000..1e4b198dc0d3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/load_unload/cmds.txt
@@ -0,0 +1,2 @@
+breakpoint set -n a_function
+run
diff --git a/packages/Python/lldbsuite/test/functionalities/load_unload/d.cpp b/packages/Python/lldbsuite/test/functionalities/load_unload/d.cpp
new file mode 100644
index 000000000000..55f2a6b404b3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/load_unload/d.cpp
@@ -0,0 +1,21 @@
+//===-- c.c -----------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+int d_init()
+{
+ return 123;
+}
+
+int d_global = d_init();
+
+int
+d_function ()
+{ // Find this line number within d_dunction().
+ return 700;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/load_unload/d.mk b/packages/Python/lldbsuite/test/functionalities/load_unload/d.mk
new file mode 100644
index 000000000000..b6b6eeacba26
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/load_unload/d.mk
@@ -0,0 +1,13 @@
+LEVEL := ../../make
+
+LIB_PREFIX := loadunload_
+
+DYLIB_EXECUTABLE_PATH := $(CURDIR)
+
+DYLIB_NAME := $(LIB_PREFIX)d
+DYLIB_CXX_SOURCES := d.cpp
+DYLIB_ONLY := YES
+
+CXXFLAGS += -fPIC
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/load_unload/hidden/Makefile b/packages/Python/lldbsuite/test/functionalities/load_unload/hidden/Makefile
new file mode 100644
index 000000000000..f84d8300843f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/load_unload/hidden/Makefile
@@ -0,0 +1,11 @@
+LEVEL := ../../../make
+
+LIB_PREFIX := loadunload_
+
+DYLIB_NAME := $(LIB_PREFIX)d
+DYLIB_CXX_SOURCES := d.cpp
+DYLIB_ONLY := YES
+
+CXXFLAGS += -fPIC
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/load_unload/hidden/d.cpp b/packages/Python/lldbsuite/test/functionalities/load_unload/hidden/d.cpp
new file mode 100644
index 000000000000..6a7642c08b93
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/load_unload/hidden/d.cpp
@@ -0,0 +1,21 @@
+//===-- c.c -----------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+int d_init()
+{
+ return 456;
+}
+
+int d_global = d_init();
+
+int
+d_function ()
+{ // Find this line number within d_dunction().
+ return 12345;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/load_unload/main.cpp b/packages/Python/lldbsuite/test/functionalities/load_unload/main.cpp
new file mode 100644
index 000000000000..bff9a3176060
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/load_unload/main.cpp
@@ -0,0 +1,80 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+#include <dlfcn.h>
+#include <limits.h>
+#include <string.h>
+#include <unistd.h>
+#include <libgen.h>
+#include <stdlib.h>
+
+int
+main (int argc, char const *argv[])
+{
+#if defined (__APPLE__)
+ const char *a_name = "@executable_path/libloadunload_a.dylib";
+ const char *c_name = "@executable_path/libloadunload_c.dylib";
+#else
+ const char *a_name = "libloadunload_a.so";
+ const char *c_name = "libloadunload_c.so";
+#endif
+ void *a_dylib_handle = NULL;
+ void *c_dylib_handle = NULL;
+ int (*a_function) (void);
+
+ a_dylib_handle = dlopen (a_name, RTLD_NOW); // Set break point at this line for test_lldb_process_load_and_unload_commands().
+ if (a_dylib_handle == NULL)
+ {
+ fprintf (stderr, "%s\n", dlerror());
+ exit (1);
+ }
+
+ a_function = (int (*) ()) dlsym (a_dylib_handle, "a_function");
+ if (a_function == NULL)
+ {
+ fprintf (stderr, "%s\n", dlerror());
+ exit (2);
+ }
+ printf ("First time around, got: %d\n", a_function ());
+ dlclose (a_dylib_handle);
+
+ c_dylib_handle = dlopen (c_name, RTLD_NOW);
+ if (c_dylib_handle == NULL)
+ {
+ fprintf (stderr, "%s\n", dlerror());
+ exit (3);
+ }
+ a_function = (int (*) ()) dlsym (c_dylib_handle, "c_function");
+ if (a_function == NULL)
+ {
+ fprintf (stderr, "%s\n", dlerror());
+ exit (4);
+ }
+
+ a_dylib_handle = dlopen (a_name, RTLD_NOW);
+ if (a_dylib_handle == NULL)
+ {
+ fprintf (stderr, "%s\n", dlerror());
+ exit (5);
+ }
+
+ a_function = (int (*) ()) dlsym (a_dylib_handle, "a_function");
+ if (a_function == NULL)
+ {
+ fprintf (stderr, "%s\n", dlerror());
+ exit (6);
+ }
+ printf ("Second time around, got: %d\n", a_function ());
+ dlclose (a_dylib_handle);
+
+ int d_function(void);
+ printf ("d_function returns: %d\n", d_function());
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/longjmp/Makefile b/packages/Python/lldbsuite/test/functionalities/longjmp/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/longjmp/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/longjmp/TestLongjmp.py b/packages/Python/lldbsuite/test/functionalities/longjmp/TestLongjmp.py
new file mode 100644
index 000000000000..1316a01c924c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/longjmp/TestLongjmp.py
@@ -0,0 +1,85 @@
+"""
+Test the use of setjmp/longjmp for non-local goto operations in a single-threaded inferior.
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class LongjmpTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ TestBase.setUp(self)
+
+ @skipIfDarwin # llvm.org/pr16769: LLDB on Mac OS X dies in function ReadRegisterBytes in GDBRemoteRegisterContext.cpp
+ @skipIfFreeBSD # llvm.org/pr17214
+ @expectedFailureLinux("llvm.org/pr20231")
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test_step_out(self):
+ """Test stepping when the inferior calls setjmp/longjmp, in particular, thread step-out."""
+ self.build()
+ self.step_out()
+
+ @skipIfDarwin # llvm.org/pr16769: LLDB on Mac OS X dies in function ReadRegisterBytes in GDBRemoteRegisterContext.cpp
+ @skipIfFreeBSD # llvm.org/pr17214
+ @expectedFailureLinux("llvm.org/pr20231")
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test_step_over(self):
+ """Test stepping when the inferior calls setjmp/longjmp, in particular, thread step-over a longjmp."""
+ self.build()
+ self.step_over()
+
+ @skipIfDarwin # llvm.org/pr16769: LLDB on Mac OS X dies in function ReadRegisterBytes in GDBRemoteRegisterContext.cpp
+ @skipIfFreeBSD # llvm.org/pr17214
+ @expectedFailureLinux("llvm.org/pr20231")
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test_step_back_out(self):
+ """Test stepping when the inferior calls setjmp/longjmp, in particular, thread step-out after thread step-in."""
+ self.build()
+ self.step_back_out()
+
+ def start_test(self, symbol):
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break in main().
+ lldbutil.run_break_set_by_symbol (self, symbol, num_expected_locations=-1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped', 'stop reason = breakpoint'])
+
+ def check_status(self):
+ # Note: Depending on the generated mapping of DWARF to assembly,
+ # the process may have stopped or exited.
+ self.expect("process status", PROCESS_STOPPED,
+ patterns = ['Process .* exited with status = 0'])
+
+ def step_out(self):
+ self.start_test("do_jump")
+ self.runCmd("thread step-out", RUN_SUCCEEDED)
+ self.check_status()
+
+ def step_over(self):
+ self.start_test("do_jump")
+ self.runCmd("thread step-over", RUN_SUCCEEDED)
+ self.runCmd("thread step-over", RUN_SUCCEEDED)
+ self.check_status()
+
+ def step_back_out(self):
+ self.start_test("main")
+
+ self.runCmd("thread step-over", RUN_SUCCEEDED)
+ self.runCmd("thread step-in", RUN_SUCCEEDED)
+ self.runCmd("thread step-out", RUN_SUCCEEDED)
+ self.check_status()
diff --git a/packages/Python/lldbsuite/test/functionalities/longjmp/main.c b/packages/Python/lldbsuite/test/functionalities/longjmp/main.c
new file mode 100644
index 000000000000..3879311eb452
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/longjmp/main.c
@@ -0,0 +1,31 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <setjmp.h>
+#include <stdio.h>
+#include <time.h>
+
+jmp_buf j;
+
+void do_jump(void)
+{
+ // We can't let the compiler know this will always happen or it might make
+ // optimizations that break our test.
+ if (!clock())
+ longjmp(j, 1); // non-local goto
+}
+
+int main (void)
+{
+ if (setjmp(j) == 0)
+ do_jump();
+ else
+ return 0; // destination of longjmp
+
+ return 1;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/memory/read/Makefile b/packages/Python/lldbsuite/test/functionalities/memory/read/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/memory/read/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/memory/read/TestMemoryRead.py b/packages/Python/lldbsuite/test/functionalities/memory/read/TestMemoryRead.py
new file mode 100644
index 000000000000..7410650ad652
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/memory/read/TestMemoryRead.py
@@ -0,0 +1,99 @@
+"""
+Test the 'memory read' command.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class MemoryReadTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def test_memory_read(self):
+ """Test the 'memory read' command with plain and vector formats."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break in main() aftre the variables are assigned values.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped', 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ # Test the memory read commands.
+
+ # (lldb) memory read -f d -c 1 `&argc`
+ # 0x7fff5fbff9a0: 1
+ self.runCmd("memory read -f d -c 1 `&argc`")
+
+ # Find the starting address for variable 'argc' to verify later that the
+ # '--format uint32_t[] --size 4 --count 4' option increments the address
+ # correctly.
+ line = self.res.GetOutput().splitlines()[0]
+ items = line.split(':')
+ address = int(items[0], 0)
+ argc = int(items[1], 0)
+ self.assertTrue(address > 0 and argc == 1)
+
+ # (lldb) memory read --format uint32_t[] --size 4 --count 4 `&argc`
+ # 0x7fff5fbff9a0: {0x00000001}
+ # 0x7fff5fbff9a4: {0x00000000}
+ # 0x7fff5fbff9a8: {0x0ec0bf27}
+ # 0x7fff5fbff9ac: {0x215db505}
+ self.runCmd("memory read --format uint32_t[] --size 4 --count 4 `&argc`")
+ lines = self.res.GetOutput().splitlines()
+ for i in range(4):
+ if i == 0:
+ # Verify that the printout for argc is correct.
+ self.assertTrue(argc == int(lines[i].split(':')[1].strip(' {}'), 0))
+ addr = int(lines[i].split(':')[0], 0)
+ # Verify that the printout for addr is incremented correctly.
+ self.assertTrue(addr == (address + i*4))
+
+ # (lldb) memory read --format char[] --size 7 --count 1 `&my_string`
+ # 0x7fff5fbff990: {abcdefg}
+ self.expect("memory read --format char[] --size 7 --count 1 `&my_string`",
+ substrs = ['abcdefg'])
+
+ # (lldb) memory read --format 'hex float' --size 16 `&argc`
+ # 0x7fff5fbff5b0: error: unsupported byte size (16) for hex float format
+ self.expect("memory read --format 'hex float' --size 16 `&argc`",
+ substrs = ['unsupported byte size (16) for hex float format'])
+
+ self.expect("memory read --format 'float' --count 1 --size 8 `&my_double`",
+ substrs = ['1234.'])
+
+ # (lldb) memory read --format 'float' --count 1 --size 20 `&my_double`
+ # 0x7fff5fbff598: error: unsupported byte size (20) for float format
+ self.expect("memory read --format 'float' --count 1 --size 20 `&my_double`",
+ substrs = ['unsupported byte size (20) for float format'])
+
+ self.expect('memory read --type int --count 5 `&my_ints[0]`',
+ substrs=['(int) 0x', '2','4','6','8','10'])
+
+ self.expect('memory read --type int --count 5 --format hex `&my_ints[0]`',
+ substrs=['(int) 0x', '0x','0a'])
+
+ self.expect('memory read --type int --count 5 --offset 5 `&my_ints[0]`',
+ substrs=['(int) 0x', '12', '14','16','18', '20'])
diff --git a/packages/Python/lldbsuite/test/functionalities/memory/read/main.cpp b/packages/Python/lldbsuite/test/functionalities/memory/read/main.cpp
new file mode 100644
index 000000000000..cd367ff318ab
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/memory/read/main.cpp
@@ -0,0 +1,19 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+int main (int argc, char const *argv[])
+{
+ char my_string[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 0};
+ double my_double = 1234.5678;
+ int my_ints[] = {2,4,6,8,10,12,14,16,18,20,22};
+ printf("my_string=%s\n", my_string); // Set break point at this line.
+ printf("my_double=%g\n", my_double);
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/Makefile b/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/TestIndexVariable.py b/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/TestIndexVariable.py
new file mode 100644
index 000000000000..5c53cfaf9120
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/TestIndexVariable.py
@@ -0,0 +1,43 @@
+"""Test evaluating expressions which ref. index variable 'i' which just goes
+from out of scope to in scope when stopped at the breakpoint."""
+
+from __future__ import print_function
+
+
+
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class NonOverlappingIndexVariableCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ TestBase.setUp(self)
+ self.source = 'main.cpp'
+ self.line_to_break = line_number(self.source, '// Set breakpoint here.')
+
+ # rdar://problem/9890530
+ def test_eval_index_variable(self):
+ """Test expressions of variable 'i' which appears in two for loops."""
+ self.build()
+ self.exe_name = 'a.out'
+ exe = os.path.join(os.getcwd(), self.exe_name)
+ self.runCmd("file %s" % exe, CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, self.source, self.line_to_break, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ self.runCmd('frame variable i')
+ self.runCmd('expr i')
+ self.runCmd('expr ptr[0]->point.x')
+ self.runCmd('expr ptr[0]->point.y')
+ self.runCmd('expr ptr[i]->point.x')
+ self.runCmd('expr ptr[i]->point.y')
diff --git a/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/main.cpp b/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/main.cpp
new file mode 100644
index 000000000000..b4f519cd25a8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/non-overlapping-index-variable-i/main.cpp
@@ -0,0 +1,51 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+class Point {
+public:
+ int x;
+ int y;
+ Point(int a, int b):
+ x(a),
+ y(b)
+ {}
+};
+
+class Data {
+public:
+ int id;
+ Point point;
+ Data(int i):
+ id(i),
+ point(0, 0)
+ {}
+};
+
+int main(int argc, char const *argv[]) {
+ Data *data[1000];
+ Data **ptr = data;
+ for (int i = 0; i < 1000; ++i) {
+ ptr[i] = new Data(i);
+ ptr[i]->point.x = i;
+ ptr[i]->point.y = i+1;
+ }
+
+ printf("Finished populating data.\n");
+ for (int i = 0; i < 1000; ++i) {
+ bool dump = argc > 1; // Set breakpoint here.
+ // Evaluate a couple of expressions (2*1000 = 2000 exprs):
+ // expr ptr[i]->point.x
+ // expr ptr[i]->point.y
+ if (dump) {
+ printf("data[%d] = %d (%d, %d)\n", i, ptr[i]->id, ptr[i]->point.x, ptr[i]->point.y);
+ }
+ }
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/nosucharch/Makefile b/packages/Python/lldbsuite/test/functionalities/nosucharch/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/nosucharch/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/nosucharch/TestNoSuchArch.py b/packages/Python/lldbsuite/test/functionalities/nosucharch/TestNoSuchArch.py
new file mode 100644
index 000000000000..7a6c98d92c3e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/nosucharch/TestNoSuchArch.py
@@ -0,0 +1,29 @@
+"""
+Test that using a non-existent architecture name does not crash LLDB.
+"""
+from __future__ import print_function
+
+
+
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class NoSuchArchTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test (self):
+ self.build()
+ exe = os.path.join (os.getcwd(), "a.out")
+
+ # Check that passing an invalid arch via the command-line fails but doesn't crash
+ self.expect("target crete --arch nothingtoseehere %s" % (exe), error=True)
+
+ # Check that passing an invalid arch via the SB API fails but doesn't crash
+ target = self.dbg.CreateTargetWithFileAndArch(exe,"nothingtoseehere")
+ self.assertFalse(target.IsValid(), "This target should not be valid")
+
+ # Now just create the target with the default arch and check it's fine
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target.IsValid(), "This target should now be valid")
diff --git a/packages/Python/lldbsuite/test/functionalities/nosucharch/main.cpp b/packages/Python/lldbsuite/test/functionalities/nosucharch/main.cpp
new file mode 100644
index 000000000000..4cce7f667ff7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/nosucharch/main.cpp
@@ -0,0 +1,3 @@
+int main() {
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/object-file/TestImageListMultiArchitecture.py b/packages/Python/lldbsuite/test/functionalities/object-file/TestImageListMultiArchitecture.py
new file mode 100644
index 000000000000..4f4a22ed6067
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/object-file/TestImageListMultiArchitecture.py
@@ -0,0 +1,41 @@
+"""
+Test lldb 'image list' on object files across multiple architectures.
+This exercises classes like ObjectFileELF and their support for opening
+foreign-architecture object files.
+"""
+
+from __future__ import print_function
+
+
+
+import os.path
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+import re
+
+class TestImageListMultiArchitecture(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @no_debug_info_test
+ def test_image_list_shows_multiple_architectures(self):
+ """Test that image list properly shows the correct architecture for a set of different architecture object files."""
+ images = {
+ "hello-freebsd-10.0-x86_64-clang-3.3": re.compile(r"x86_64-(\*)?-freebsd10.0(-unknown)? x86_64"),
+ "hello-freebsd-10.0-x86_64-gcc-4.7.3": re.compile(r"x86_64-(\*)?-freebsd10.0(-unknown)? x86_64"),
+ "hello-netbsd-6.1-x86_64-gcc-4.5.3": re.compile(r"x86_64-(\*)?-netbsd(-unknown)? x86_64"),
+ "hello-ubuntu-14.04-x86_64-gcc-4.8.2": re.compile(r"x86_64-(\*)?-linux(-unknown)? x86_64"),
+ "hello-ubuntu-14.04-x86_64-clang-3.5pre": re.compile(r"x86_64-(\*)?-linux(-unknown)? x86_64"),
+ "hello-unknown-kalimba_arch4-kcc-36": re.compile(r"kalimba4-csr-(unknown|\*)(-unknown)? kalimba"),
+ "hello-unknown-kalimba_arch5-kcc-39": re.compile(r"kalimba5-csr-(unknown|\*)(-unknown)? kalimba"),
+ }
+
+ for image_name in images:
+ file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), "bin", image_name))
+ expected_triple_and_arch_regex = images[image_name]
+
+ self.runCmd("file {}".format(file_name))
+ self.match("image list -t -A", [expected_triple_and_arch_regex])
+ # Revert to the host platform after all of this is done
+ self.runCmd("platform select host")
diff --git a/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-freebsd-10.0-x86_64-clang-3.3 b/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-freebsd-10.0-x86_64-clang-3.3
new file mode 100644
index 000000000000..cea323639b46
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-freebsd-10.0-x86_64-clang-3.3
Binary files differ
diff --git a/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-freebsd-10.0-x86_64-gcc-4.7.3 b/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-freebsd-10.0-x86_64-gcc-4.7.3
new file mode 100644
index 000000000000..38f43f8acb9d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-freebsd-10.0-x86_64-gcc-4.7.3
Binary files differ
diff --git a/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-netbsd-6.1-x86_64-gcc-4.5.3 b/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-netbsd-6.1-x86_64-gcc-4.5.3
new file mode 100644
index 000000000000..6d531320ae96
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-netbsd-6.1-x86_64-gcc-4.5.3
Binary files differ
diff --git a/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-ubuntu-14.04-x86_64-clang-3.5pre b/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-ubuntu-14.04-x86_64-clang-3.5pre
new file mode 100644
index 000000000000..8bdcf4d5b59e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-ubuntu-14.04-x86_64-clang-3.5pre
Binary files differ
diff --git a/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-ubuntu-14.04-x86_64-gcc-4.8.2 b/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-ubuntu-14.04-x86_64-gcc-4.8.2
new file mode 100644
index 000000000000..01efbb061b73
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-ubuntu-14.04-x86_64-gcc-4.8.2
Binary files differ
diff --git a/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-unknown-kalimba_arch4-kcc-36 b/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-unknown-kalimba_arch4-kcc-36
new file mode 100644
index 000000000000..8e4dd8c883c9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-unknown-kalimba_arch4-kcc-36
Binary files differ
diff --git a/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-unknown-kalimba_arch5-kcc-39 b/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-unknown-kalimba_arch5-kcc-39
new file mode 100644
index 000000000000..f80268a08e5e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello-unknown-kalimba_arch5-kcc-39
Binary files differ
diff --git a/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello.c b/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello.c
new file mode 100644
index 000000000000..8c804005afe3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello.c
@@ -0,0 +1,8 @@
+#include <stdio.h>
+
+int main(int argc, char **argv)
+{
+ printf("Hello, world\n");
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello.cpp b/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello.cpp
new file mode 100644
index 000000000000..8c804005afe3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/object-file/bin/hello.cpp
@@ -0,0 +1,8 @@
+#include <stdio.h>
+
+int main(int argc, char **argv)
+{
+ printf("Hello, world\n");
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/paths/TestPaths.py b/packages/Python/lldbsuite/test/functionalities/paths/TestPaths.py
new file mode 100644
index 000000000000..f718b62f95ea
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/paths/TestPaths.py
@@ -0,0 +1,48 @@
+"""
+Test some lldb command abbreviations.
+"""
+from __future__ import print_function
+
+
+
+import lldb
+import os
+import time
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TestPaths(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @no_debug_info_test
+ def test_paths (self):
+ '''Test to make sure no file names are set in the lldb.SBFileSpec objects returned by lldb.SBHostOS.GetLLDBPath() for paths that are directories'''
+ dir_path_types = [lldb.ePathTypeLLDBShlibDir,
+ lldb.ePathTypeSupportExecutableDir,
+ lldb.ePathTypeHeaderDir,
+ lldb.ePathTypePythonDir,
+ lldb.ePathTypeLLDBSystemPlugins,
+ lldb.ePathTypeLLDBUserPlugins,
+ lldb.ePathTypeLLDBTempSystemDir]
+
+ for path_type in dir_path_types:
+ f = lldb.SBHostOS.GetLLDBPath(path_type);
+ # No directory path types should have the filename set
+ self.assertTrue (f.GetFilename() == None);
+
+ @no_debug_info_test
+ def test_directory_doesnt_end_with_slash(self):
+ current_directory_spec = lldb.SBFileSpec(os.path.curdir)
+ current_directory_string = current_directory_spec.GetDirectory()
+ self.assertNotEqual(current_directory_string[-1:], '/')
+ pass
+
+ @skipUnlessPlatform(["windows"])
+ @no_debug_info_test
+ def test_windows_double_slash (self):
+ '''Test to check the path with double slash is handled correctly '''
+ # Create a path and see if lldb gets the directory and file right
+ fspec = lldb.SBFileSpec("C:\\dummy1\\dummy2//unknown_file", True);
+ self.assertEqual(os.path.normpath(fspec.GetDirectory()), os.path.normpath("C:/dummy1/dummy2"));
+ self.assertEqual(fspec.GetFilename(), "unknown_file");
diff --git a/packages/Python/lldbsuite/test/functionalities/platform/TestPlatformCommand.py b/packages/Python/lldbsuite/test/functionalities/platform/TestPlatformCommand.py
new file mode 100644
index 000000000000..6b3eedaf603a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/platform/TestPlatformCommand.py
@@ -0,0 +1,65 @@
+"""
+Test some lldb platform commands.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class PlatformCommandTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @no_debug_info_test
+ def test_help_platform(self):
+ self.runCmd("help platform")
+
+ @no_debug_info_test
+ def test_list(self):
+ self.expect("platform list",
+ patterns = ['^Available platforms:'])
+
+ @no_debug_info_test
+ def test_process_list(self):
+ self.expect("platform process list",
+ substrs = ['PID', 'TRIPLE', 'NAME'])
+
+ @no_debug_info_test
+ def test_process_info_with_no_arg(self):
+ """This is expected to fail and to return a proper error message."""
+ self.expect("platform process info", error=True,
+ substrs = ['one or more process id(s) must be specified'])
+
+ @no_debug_info_test
+ def test_status(self):
+ self.expect("platform status",
+ substrs = ['Platform', 'Triple', 'OS Version', 'Kernel', 'Hostname'])
+
+ @no_debug_info_test
+ def test_shell(self):
+ """ Test that the platform shell command can invoke ls. """
+ triple = self.dbg.GetSelectedPlatform().GetTriple()
+ if re.match(".*-.*-windows", triple):
+ self.expect("platform shell dir c:\\", substrs = ["Windows", "Program Files"])
+ elif re.match(".*-.*-.*-android", triple):
+ self.expect("platform shell ls /", substrs = ["cache", "dev", "system"])
+ else:
+ self.expect("platform shell ls /", substrs = ["dev", "tmp", "usr"])
+
+ @no_debug_info_test
+ def test_shell_builtin(self):
+ """ Test a shell built-in command (echo) """
+ self.expect("platform shell echo hello lldb",
+ substrs = ["hello lldb"])
+
+ #FIXME: re-enable once platform shell -t can specify the desired timeout
+ @no_debug_info_test
+ def test_shell_timeout(self):
+ """ Test a shell built-in command (sleep) that times out """
+ self.skipTest("due to taking too long to complete.")
+ self.expect("platform shell sleep 15", error=True,
+ substrs = ["error: timed out waiting for shell command to complete"])
diff --git a/packages/Python/lldbsuite/test/functionalities/plugins/commands/Makefile b/packages/Python/lldbsuite/test/functionalities/plugins/commands/Makefile
new file mode 100644
index 000000000000..8af06446ecef
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/plugins/commands/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../../make
+
+DYLIB_CXX_SOURCES := plugin.cpp
+DYLIB_NAME := plugin
+DYLIB_ONLY := YES
+MAKE_DSYM := NO
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/plugins/commands/TestPluginCommands.py b/packages/Python/lldbsuite/test/functionalities/plugins/commands/TestPluginCommands.py
new file mode 100644
index 000000000000..b62c30bcf4e7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/plugins/commands/TestPluginCommands.py
@@ -0,0 +1,58 @@
+"""
+Test that plugins that load commands work correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class PluginCommandTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfNoSBHeaders
+ @skipIfHostIncompatibleWithRemote # Requires a compatible arch and platform to link against the host's built lldb lib.
+ @expectedFailureWindows("llvm.org/pr24778")
+ @no_debug_info_test
+ def test_load_plugin(self):
+ """Test that plugins that load commands work correctly."""
+
+ plugin_name = "plugin"
+ if sys.platform.startswith("darwin"):
+ plugin_lib_name = "lib%s.dylib" % plugin_name
+ else:
+ plugin_lib_name = "lib%s.so" % plugin_name
+
+ # Invoke the library build rule.
+ self.buildLibrary("plugin.cpp", plugin_name)
+
+ debugger = lldb.SBDebugger.Create()
+
+ retobj = lldb.SBCommandReturnObject()
+
+ retval = debugger.GetCommandInterpreter().HandleCommand("plugin load %s" % plugin_lib_name, retobj)
+
+ retobj.Clear()
+
+ retval = debugger.GetCommandInterpreter().HandleCommand("plugin_loaded_command child abc def ghi",retobj)
+
+ if self.TraceOn():
+ print(retobj.GetOutput())
+
+ self.expect(retobj,substrs = ['abc def ghi'], exe=False)
+
+ retobj.Clear()
+
+ # check that abbreviations work correctly in plugin commands.
+ retval = debugger.GetCommandInterpreter().HandleCommand("plugin_loaded_ ch abc def ghi",retobj)
+
+ if self.TraceOn():
+ print(retobj.GetOutput())
+
+ self.expect(retobj,substrs = ['abc def ghi'], exe=False)
diff --git a/packages/Python/lldbsuite/test/functionalities/plugins/commands/plugin.cpp b/packages/Python/lldbsuite/test/functionalities/plugins/commands/plugin.cpp
new file mode 100644
index 000000000000..be3d29325de1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/plugins/commands/plugin.cpp
@@ -0,0 +1,62 @@
+//===-- plugin.cpp -------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+/*
+An example plugin for LLDB that provides a new foo command with a child subcommand
+Compile this into a dylib foo.dylib and load by placing in appropriate locations on disk or
+by typing plugin load foo.dylib at the LLDB command line
+*/
+
+#if defined (__APPLE__)
+#include <LLDB/SBCommandInterpreter.h>
+#include <LLDB/SBCommandReturnObject.h>
+#include <LLDB/SBDebugger.h>
+#else
+#include <lldb/API/SBCommandInterpreter.h>
+#include <lldb/API/SBCommandReturnObject.h>
+#include <lldb/API/SBDebugger.h>
+#endif
+
+namespace lldb {
+ bool
+ PluginInitialize (lldb::SBDebugger debugger);
+}
+
+class ChildCommand : public lldb::SBCommandPluginInterface
+{
+public:
+ virtual bool
+ DoExecute (lldb::SBDebugger debugger,
+ char** command,
+ lldb::SBCommandReturnObject &result)
+ {
+ if (command)
+ {
+ const char* arg = *command;
+ while (arg)
+ {
+ result.Printf("%s ",arg);
+ arg = *(++command);
+ }
+ result.Printf("\n");
+ return true;
+ }
+ return false;
+ }
+
+};
+
+bool
+lldb::PluginInitialize (lldb::SBDebugger debugger)
+{
+ lldb::SBCommandInterpreter interpreter = debugger.GetCommandInterpreter();
+ lldb::SBCommand foo = interpreter.AddMultiwordCommand("plugin_loaded_command",NULL);
+ foo.AddCommand("child",new ChildCommand(),"a child of plugin_loaded_command");
+ return true;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/Makefile b/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/Makefile
new file mode 100644
index 000000000000..cd9ca5c86d84
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/Makefile
@@ -0,0 +1,3 @@
+LEVEL = ../../../make
+C_SOURCES := main.c
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/TestPythonOSPlugin.py b/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/TestPythonOSPlugin.py
new file mode 100644
index 000000000000..ebd96d9d4c02
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/TestPythonOSPlugin.py
@@ -0,0 +1,150 @@
+"""
+Test that the Python operating system plugin works correctly
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class PluginPythonOSPlugin(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test_python_os_plugin(self):
+ """Test that the Python operating system plugin works correctly"""
+ self.build()
+ self.run_python_os_funcionality()
+
+ def run_python_os_step(self):
+ """Test that the Python operating system plugin works correctly when single stepping a virtual thread"""
+ self.build()
+ self.run_python_os_step()
+
+ def verify_os_thread_registers(self, thread):
+ frame = thread.GetFrameAtIndex(0)
+ registers = frame.GetRegisters().GetValueAtIndex(0)
+ reg_value = thread.GetThreadID() + 1
+ for reg in registers:
+ self.assertTrue(reg.GetValueAsUnsigned() == reg_value, "Verify the registers contains the correct value")
+ reg_value = reg_value + 1
+
+ def run_python_os_funcionality(self):
+ """Test that the Python operating system plugin works correctly"""
+
+ # Set debugger into synchronous mode
+ self.dbg.SetAsync(False)
+
+ # Create a target by the debugger.
+ cwd = os.getcwd()
+ exe = os.path.join(cwd, "a.out")
+ python_os_plugin_path = os.path.join(cwd, "operating_system.py")
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Set breakpoints inside and outside methods that take pointers to the containing struct.
+ lldbutil.run_break_set_by_source_regexp (self, "// Set breakpoint here")
+
+ # Register our shared libraries for remote targets so they get automatically uploaded
+ arguments = None
+ environment = None
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (arguments, environment, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Make sure there are no OS plug-in created thread when we first stop at our breakpoint in main
+ thread = process.GetThreadByID(0x111111111);
+ self.assertFalse (thread.IsValid(), "Make sure there is no thread 0x111111111 before we load the python OS plug-in");
+ thread = process.GetThreadByID(0x222222222);
+ self.assertFalse (thread.IsValid(), "Make sure there is no thread 0x222222222 before we load the python OS plug-in");
+ thread = process.GetThreadByID(0x333333333);
+ self.assertFalse (thread.IsValid(), "Make sure there is no thread 0x333333333 before we load the python OS plug-in");
+
+
+ # Now load the python OS plug-in which should update the thread list and we should have
+ # OS plug-in created threads with the IDs: 0x111111111, 0x222222222, 0x333333333
+ command = "settings set target.process.python-os-plugin-path '%s'" % python_os_plugin_path
+ self.dbg.HandleCommand(command)
+
+ # Verify our OS plug-in threads showed up
+ thread = process.GetThreadByID(0x111111111);
+ self.assertTrue (thread.IsValid(), "Make sure there is a thread 0x111111111 after we load the python OS plug-in");
+ self.verify_os_thread_registers(thread)
+ thread = process.GetThreadByID(0x222222222);
+ self.assertTrue (thread.IsValid(), "Make sure there is a thread 0x222222222 after we load the python OS plug-in");
+ self.verify_os_thread_registers(thread)
+ thread = process.GetThreadByID(0x333333333);
+ self.assertTrue (thread.IsValid(), "Make sure there is a thread 0x333333333 after we load the python OS plug-in");
+ self.verify_os_thread_registers(thread)
+
+ # Now clear the OS plug-in path to make the OS plug-in created threads dissappear
+ self.dbg.HandleCommand("settings clear target.process.python-os-plugin-path")
+
+ # Verify the threads are gone after unloading the python OS plug-in
+ thread = process.GetThreadByID(0x111111111);
+ self.assertFalse (thread.IsValid(), "Make sure there is no thread 0x111111111 after we unload the python OS plug-in");
+ thread = process.GetThreadByID(0x222222222);
+ self.assertFalse (thread.IsValid(), "Make sure there is no thread 0x222222222 after we unload the python OS plug-in");
+ thread = process.GetThreadByID(0x333333333);
+ self.assertFalse (thread.IsValid(), "Make sure there is no thread 0x333333333 after we unload the python OS plug-in");
+
+ def run_python_os_step(self):
+ """Test that the Python operating system plugin works correctly and allows single stepping of a virtual thread that is backed by a real thread"""
+
+ # Set debugger into synchronous mode
+ self.dbg.SetAsync(False)
+
+ # Create a target by the debugger.
+ cwd = os.getcwd()
+ exe = os.path.join(cwd, "a.out")
+ python_os_plugin_path = os.path.join(cwd, "operating_system2.py")
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Set breakpoints inside and outside methods that take pointers to the containing struct.
+ lldbutil.run_break_set_by_source_regexp (self, "// Set breakpoint here")
+
+ # Register our shared libraries for remote targets so they get automatically uploaded
+ arguments = None
+ environment = None
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (arguments, environment, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Make sure there are no OS plug-in created thread when we first stop at our breakpoint in main
+ thread = process.GetThreadByID(0x111111111);
+ self.assertFalse (thread.IsValid(), "Make sure there is no thread 0x111111111 before we load the python OS plug-in");
+
+
+ # Now load the python OS plug-in which should update the thread list and we should have
+ # OS plug-in created threads with the IDs: 0x111111111, 0x222222222, 0x333333333
+ command = "settings set target.process.python-os-plugin-path '%s'" % python_os_plugin_path
+ self.dbg.HandleCommand(command)
+
+ # Verify our OS plug-in threads showed up
+ thread = process.GetThreadByID(0x111111111);
+ self.assertTrue (thread.IsValid(), "Make sure there is a thread 0x111111111 after we load the python OS plug-in");
+
+ frame = thread.GetFrameAtIndex(0)
+ self.assertTrue(frame.IsValid(), "Make sure we get a frame from thread 0x111111111")
+ line_entry = frame.GetLineEntry()
+
+ self.assertTrue(line_entry.GetFileSpec().GetFilename() == 'main.c', "Make sure we stopped on line 5 in main.c")
+ self.assertTrue(line_entry.GetLine() == 5, "Make sure we stopped on line 5 in main.c")
+
+ # Now single step thread 0x111111111 and make sure it does what we need it to
+ thread.StepOver()
+
+ frame = thread.GetFrameAtIndex(0)
+ self.assertTrue(frame.IsValid(), "Make sure we get a frame from thread 0x111111111")
+ line_entry = frame.GetLineEntry()
+
+ self.assertTrue(line_entry.GetFileSpec().GetFilename() == 'main.c', "Make sure we stepped from line 5 to line 6 in main.c")
+ self.assertTrue(line_entry.GetLine() == 6, "Make sure we stepped from line 5 to line 6 in main.c")
diff --git a/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/main.c b/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/main.c
new file mode 100644
index 000000000000..faa6dd58ecd6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/main.c
@@ -0,0 +1,7 @@
+#include <stdio.h>
+
+int main (int argc, char const *argv[], char const *envp[])
+{
+ puts("stop here"); // Set breakpoint here
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system.py b/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system.py
new file mode 100644
index 000000000000..536092e40b38
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system.py
@@ -0,0 +1,90 @@
+#!/usr/bin/python
+
+import lldb
+import struct
+
+class OperatingSystemPlugIn(object):
+ """Class that provides data for an instance of a LLDB 'OperatingSystemPython' plug-in class"""
+
+ def __init__(self, process):
+ '''Initialization needs a valid.SBProcess object.
+
+ This plug-in will get created after a live process is valid and has stopped for the
+ first time.'''
+ self.process = None
+ self.registers = None
+ self.threads = None
+ if type(process) is lldb.SBProcess and process.IsValid():
+ self.process = process
+ self.threads = None # Will be an dictionary containing info for each thread
+
+ def get_target(self):
+ # NOTE: Don't use "lldb.target" when trying to get your target as the "lldb.target"
+ # tracks the current target in the LLDB command interpreter which isn't the
+ # correct thing to use for this plug-in.
+ return self.process.target
+
+ def create_thread(self, tid, context):
+ if tid == 0x444444444:
+ thread_info = { 'tid' : tid, 'name' : 'four' , 'queue' : 'queue4', 'state' : 'stopped', 'stop_reason' : 'none' }
+ self.threads.append(thread_info)
+ return thread_info
+ return None
+
+ def get_thread_info(self):
+ if not self.threads:
+ # The sample dictionary below shows the values that can be returned for a thread
+ # tid => thread ID (mandatory)
+ # name => thread name (optional key/value pair)
+ # queue => thread dispatch queue name (optional key/value pair)
+ # state => thred state (mandatory, set to 'stopped' for now)
+ # stop_reason => thread stop reason. (mandatory, usually set to 'none')
+ # Possible values include:
+ # 'breakpoint' if the thread is stopped at a breakpoint
+ # 'none' thread is just stopped because the process is stopped
+ # 'trace' the thread just single stepped
+ # The usual value for this while threads are in memory is 'none'
+ # register_data_addr => the address of the register data in memory (optional key/value pair)
+ # Specifying this key/value pair for a thread will avoid a call to get_register_data()
+ # and can be used when your registers are in a thread context structure that is contiguous
+ # in memory. Don't specify this if your register layout in memory doesn't match the layout
+ # described by the dictionary returned from a call to the get_register_info() method.
+ self.threads = [
+ { 'tid' : 0x111111111, 'name' : 'one' , 'queue' : 'queue1', 'state' : 'stopped', 'stop_reason' : 'breakpoint'},
+ { 'tid' : 0x222222222, 'name' : 'two' , 'queue' : 'queue2', 'state' : 'stopped', 'stop_reason' : 'none' },
+ { 'tid' : 0x333333333, 'name' : 'three', 'queue' : 'queue3', 'state' : 'stopped', 'stop_reason' : 'trace' }
+ ]
+ return self.threads
+
+ def get_register_info(self):
+ if self.registers == None:
+ self.registers = dict()
+ self.registers['sets'] = ['GPR']
+ self.registers['registers'] = [
+ { 'name':'rax' , 'bitsize' : 64, 'offset' : 0, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 0, 'dwarf' : 0},
+ { 'name':'rbx' , 'bitsize' : 64, 'offset' : 8, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 3, 'dwarf' : 3},
+ { 'name':'rcx' , 'bitsize' : 64, 'offset' : 16, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 2, 'dwarf' : 2, 'generic':'arg4', 'alt-name':'arg4', },
+ { 'name':'rdx' , 'bitsize' : 64, 'offset' : 24, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 1, 'dwarf' : 1, 'generic':'arg3', 'alt-name':'arg3', },
+ { 'name':'rdi' , 'bitsize' : 64, 'offset' : 32, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 5, 'dwarf' : 5, 'generic':'arg1', 'alt-name':'arg1', },
+ { 'name':'rsi' , 'bitsize' : 64, 'offset' : 40, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 4, 'dwarf' : 4, 'generic':'arg2', 'alt-name':'arg2', },
+ { 'name':'rbp' , 'bitsize' : 64, 'offset' : 48, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 6, 'dwarf' : 6, 'generic':'fp' , 'alt-name':'fp', },
+ { 'name':'rsp' , 'bitsize' : 64, 'offset' : 56, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 7, 'dwarf' : 7, 'generic':'sp' , 'alt-name':'sp', },
+ { 'name':'r8' , 'bitsize' : 64, 'offset' : 64, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 8, 'dwarf' : 8, 'generic':'arg5', 'alt-name':'arg5', },
+ { 'name':'r9' , 'bitsize' : 64, 'offset' : 72, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 9, 'dwarf' : 9, 'generic':'arg6', 'alt-name':'arg6', },
+ { 'name':'r10' , 'bitsize' : 64, 'offset' : 80, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 10, 'dwarf' : 10},
+ { 'name':'r11' , 'bitsize' : 64, 'offset' : 88, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 11, 'dwarf' : 11},
+ { 'name':'r12' , 'bitsize' : 64, 'offset' : 96, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 12, 'dwarf' : 12},
+ { 'name':'r13' , 'bitsize' : 64, 'offset' : 104, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 13, 'dwarf' : 13},
+ { 'name':'r14' , 'bitsize' : 64, 'offset' : 112, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 14, 'dwarf' : 14},
+ { 'name':'r15' , 'bitsize' : 64, 'offset' : 120, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 15, 'dwarf' : 15},
+ { 'name':'rip' , 'bitsize' : 64, 'offset' : 128, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 16, 'dwarf' : 16, 'generic':'pc', 'alt-name':'pc' },
+ { 'name':'rflags' , 'bitsize' : 64, 'offset' : 136, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'generic':'flags', 'alt-name':'flags' },
+ { 'name':'cs' , 'bitsize' : 64, 'offset' : 144, 'encoding':'uint' , 'format':'hex' , 'set': 0 },
+ { 'name':'fs' , 'bitsize' : 64, 'offset' : 152, 'encoding':'uint' , 'format':'hex' , 'set': 0 },
+ { 'name':'gs' , 'bitsize' : 64, 'offset' : 160, 'encoding':'uint' , 'format':'hex' , 'set': 0 },
+ ]
+ return self.registers
+
+ def get_register_data(self, tid):
+ return struct.pack('21Q',tid + 1,tid + 2,tid + 3,tid + 4,tid + 5,tid + 6,tid + 7,tid + 8,tid + 9,tid + 10,tid + 11,tid + 12,tid + 13,tid + 14,tid + 15,tid + 16,tid + 17,tid + 18,tid + 19,tid + 20,tid + 21);
+
diff --git a/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system2.py b/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system2.py
new file mode 100644
index 000000000000..7a9435d44ed4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/plugins/python_os_plugin/operating_system2.py
@@ -0,0 +1,88 @@
+#!/usr/bin/python
+
+import lldb
+import struct
+
+class OperatingSystemPlugIn(object):
+ """Class that provides data for an instance of a LLDB 'OperatingSystemPython' plug-in class"""
+
+ def __init__(self, process):
+ '''Initialization needs a valid.SBProcess object.
+
+ This plug-in will get created after a live process is valid and has stopped for the
+ first time.'''
+ self.process = None
+ self.registers = None
+ self.threads = None
+ if type(process) is lldb.SBProcess and process.IsValid():
+ self.process = process
+ self.threads = None # Will be an dictionary containing info for each thread
+
+ def get_target(self):
+ # NOTE: Don't use "lldb.target" when trying to get your target as the "lldb.target"
+ # tracks the current target in the LLDB command interpreter which isn't the
+ # correct thing to use for this plug-in.
+ return self.process.target
+
+ def create_thread(self, tid, context):
+ if tid == 0x444444444:
+ thread_info = { 'tid' : tid, 'name' : 'four' , 'queue' : 'queue4', 'state' : 'stopped', 'stop_reason' : 'none' }
+ self.threads.append(thread_info)
+ return thread_info
+ return None
+
+ def get_thread_info(self):
+ if not self.threads:
+ # The sample dictionary below shows the values that can be returned for a thread
+ # tid => thread ID (mandatory)
+ # name => thread name (optional key/value pair)
+ # queue => thread dispatch queue name (optional key/value pair)
+ # state => thred state (mandatory, set to 'stopped' for now)
+ # stop_reason => thread stop reason. (mandatory, usually set to 'none')
+ # Possible values include:
+ # 'breakpoint' if the thread is stopped at a breakpoint
+ # 'none' thread is just stopped because the process is stopped
+ # 'trace' the thread just single stepped
+ # The usual value for this while threads are in memory is 'none'
+ # register_data_addr => the address of the register data in memory (optional key/value pair)
+ # Specifying this key/value pair for a thread will avoid a call to get_register_data()
+ # and can be used when your registers are in a thread context structure that is contiguous
+ # in memory. Don't specify this if your register layout in memory doesn't match the layout
+ # described by the dictionary returned from a call to the get_register_info() method.
+ self.threads = [
+ { 'tid' : 0x111111111, 'core' : 0 }
+ ]
+ return self.threads
+
+ def get_register_info(self):
+ if self.registers == None:
+ self.registers = dict()
+ self.registers['sets'] = ['GPR']
+ self.registers['registers'] = [
+ { 'name':'rax' , 'bitsize' : 64, 'offset' : 0, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 0, 'dwarf' : 0},
+ { 'name':'rbx' , 'bitsize' : 64, 'offset' : 8, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 3, 'dwarf' : 3},
+ { 'name':'rcx' , 'bitsize' : 64, 'offset' : 16, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 2, 'dwarf' : 2, 'generic':'arg4', 'alt-name':'arg4', },
+ { 'name':'rdx' , 'bitsize' : 64, 'offset' : 24, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 1, 'dwarf' : 1, 'generic':'arg3', 'alt-name':'arg3', },
+ { 'name':'rdi' , 'bitsize' : 64, 'offset' : 32, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 5, 'dwarf' : 5, 'generic':'arg1', 'alt-name':'arg1', },
+ { 'name':'rsi' , 'bitsize' : 64, 'offset' : 40, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 4, 'dwarf' : 4, 'generic':'arg2', 'alt-name':'arg2', },
+ { 'name':'rbp' , 'bitsize' : 64, 'offset' : 48, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 6, 'dwarf' : 6, 'generic':'fp' , 'alt-name':'fp', },
+ { 'name':'rsp' , 'bitsize' : 64, 'offset' : 56, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 7, 'dwarf' : 7, 'generic':'sp' , 'alt-name':'sp', },
+ { 'name':'r8' , 'bitsize' : 64, 'offset' : 64, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 8, 'dwarf' : 8, 'generic':'arg5', 'alt-name':'arg5', },
+ { 'name':'r9' , 'bitsize' : 64, 'offset' : 72, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 9, 'dwarf' : 9, 'generic':'arg6', 'alt-name':'arg6', },
+ { 'name':'r10' , 'bitsize' : 64, 'offset' : 80, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 10, 'dwarf' : 10},
+ { 'name':'r11' , 'bitsize' : 64, 'offset' : 88, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 11, 'dwarf' : 11},
+ { 'name':'r12' , 'bitsize' : 64, 'offset' : 96, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 12, 'dwarf' : 12},
+ { 'name':'r13' , 'bitsize' : 64, 'offset' : 104, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 13, 'dwarf' : 13},
+ { 'name':'r14' , 'bitsize' : 64, 'offset' : 112, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 14, 'dwarf' : 14},
+ { 'name':'r15' , 'bitsize' : 64, 'offset' : 120, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 15, 'dwarf' : 15},
+ { 'name':'rip' , 'bitsize' : 64, 'offset' : 128, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'gcc' : 16, 'dwarf' : 16, 'generic':'pc', 'alt-name':'pc' },
+ { 'name':'rflags' , 'bitsize' : 64, 'offset' : 136, 'encoding':'uint' , 'format':'hex' , 'set': 0, 'generic':'flags', 'alt-name':'flags' },
+ { 'name':'cs' , 'bitsize' : 64, 'offset' : 144, 'encoding':'uint' , 'format':'hex' , 'set': 0 },
+ { 'name':'fs' , 'bitsize' : 64, 'offset' : 152, 'encoding':'uint' , 'format':'hex' , 'set': 0 },
+ { 'name':'gs' , 'bitsize' : 64, 'offset' : 160, 'encoding':'uint' , 'format':'hex' , 'set': 0 },
+ ]
+ return self.registers
+
+ def get_register_data(self, tid):
+ return struct.pack('21Q',tid + 1,tid + 2,tid + 3,tid + 4,tid + 5,tid + 6,tid + 7,tid + 8,tid + 9,tid + 10,tid + 11,tid + 12,tid + 13,tid + 14,tid + 15,tid + 16,tid + 17,tid + 18,tid + 19,tid + 20,tid + 21);
+
diff --git a/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/Makefile b/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/Makefile
new file mode 100644
index 000000000000..b3034c12abd9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
+
diff --git a/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/TestMiniDump.py b/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/TestMiniDump.py
new file mode 100644
index 000000000000..53888502a3aa
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/TestMiniDump.py
@@ -0,0 +1,128 @@
+"""
+Test basics of mini dump debugging.
+"""
+
+from __future__ import print_function
+
+
+
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class MiniDumpTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipUnlessWindows # for now mini-dump debugging is limited to Windows hosts
+ @no_debug_info_test
+ def test_process_info_in_mini_dump(self):
+ """Test that lldb can read the process information from the minidump."""
+ # target create -c fizzbuzz_no_heap.dmp
+ self.dbg.CreateTarget("")
+ self.target = self.dbg.GetSelectedTarget()
+ self.process = self.target.LoadCore("fizzbuzz_no_heap.dmp")
+ self.assertTrue(self.process, PROCESS_IS_VALID)
+ self.assertEqual(self.process.GetNumThreads(), 1)
+ self.assertEqual(self.process.GetProcessID(), 4440)
+
+ @skipUnlessWindows # for now mini-dump debugging is limited to Windows hosts
+ @no_debug_info_test
+ def test_thread_info_in_mini_dump(self):
+ """Test that lldb can read the thread information from the minidump."""
+ # target create -c fizzbuzz_no_heap.dmp
+ self.dbg.CreateTarget("")
+ self.target = self.dbg.GetSelectedTarget()
+ self.process = self.target.LoadCore("fizzbuzz_no_heap.dmp")
+ # This process crashed due to an access violation (0xc0000005) in its one and only thread.
+ self.assertEqual(self.process.GetNumThreads(), 1)
+ thread = self.process.GetThreadAtIndex(0)
+ self.assertEqual(thread.GetStopReason(), lldb.eStopReasonException)
+ stop_description = thread.GetStopDescription(256);
+ self.assertTrue("0xc0000005" in stop_description);
+
+ @skipUnlessWindows # for now mini-dump debugging is limited to Windows hosts
+ @no_debug_info_test
+ def test_stack_info_in_mini_dump(self):
+ """Test that we can see a trivial stack in a VS-generate mini dump."""
+ # target create -c fizzbuzz_no_heap.dmp
+ self.dbg.CreateTarget("")
+ self.target = self.dbg.GetSelectedTarget()
+ self.process = self.target.LoadCore("fizzbuzz_no_heap.dmp")
+ self.assertEqual(self.process.GetNumThreads(), 1)
+ thread = self.process.GetThreadAtIndex(0)
+ # The crash is in main, so there should be one frame on the stack.
+ self.assertEqual(thread.GetNumFrames(), 1)
+ frame = thread.GetFrameAtIndex(0)
+ self.assertTrue(frame.IsValid())
+ pc = frame.GetPC()
+ eip = frame.FindRegister("pc")
+ self.assertTrue(eip.IsValid())
+ self.assertEqual(pc, eip.GetValueAsUnsigned())
+
+ @skipUnlessWindows
+ @not_remote_testsuite_ready
+ def test_deeper_stack_in_mini_dump(self):
+ """Test that we can examine a more interesting stack in a mini dump."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ core = os.path.join(os.getcwd(), "core.dmp")
+ try:
+ # Set a breakpoint and capture a mini dump.
+ target = self.dbg.CreateTarget(exe)
+ breakpoint = target.BreakpointCreateByName("bar")
+ process = target.LaunchSimple(None, None, self.get_process_working_directory())
+ self.assertEqual(process.GetState(), lldb.eStateStopped)
+ self.assertTrue(process.SaveCore(core))
+ self.assertTrue(os.path.isfile(core))
+ self.assertTrue(process.Kill().Success())
+
+ # Launch with the mini dump, and inspect the stack.
+ target = self.dbg.CreateTarget(None)
+ process = target.LoadCore(core)
+ thread = process.GetThreadAtIndex(0)
+
+ expected_stack = { 0: 'bar', 1: 'foo', 2: 'main' }
+ self.assertEqual(thread.GetNumFrames(), len(expected_stack))
+ for index, name in expected_stack.iteritems():
+ frame = thread.GetFrameAtIndex(index)
+ self.assertTrue(frame.IsValid())
+ function_name = frame.GetFunctionName()
+ self.assertTrue(name in function_name)
+
+ finally:
+ # Clean up the mini dump file.
+ self.assertTrue(self.dbg.DeleteTarget(target))
+ if (os.path.isfile(core)):
+ os.unlink(core)
+
+ @skipUnlessWindows
+ @not_remote_testsuite_ready
+ def test_local_variables_in_mini_dump(self):
+ """Test that we can examine local variables in a mini dump."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ core = os.path.join(os.getcwd(), "core.dmp")
+ try:
+ # Set a breakpoint and capture a mini dump.
+ target = self.dbg.CreateTarget(exe)
+ breakpoint = target.BreakpointCreateByName("bar")
+ process = target.LaunchSimple(None, None, self.get_process_working_directory())
+ self.assertEqual(process.GetState(), lldb.eStateStopped)
+ self.assertTrue(process.SaveCore(core))
+ self.assertTrue(os.path.isfile(core))
+ self.assertTrue(process.Kill().Success())
+
+ # Launch with the mini dump, and inspect a local variable.
+ target = self.dbg.CreateTarget(None)
+ process = target.LoadCore(core)
+ thread = process.GetThreadAtIndex(0)
+ frame = thread.GetFrameAtIndex(0)
+ value = frame.EvaluateExpression('x')
+ self.assertEqual(value.GetValueAsSigned(), 3)
+
+ finally:
+ # Clean up the mini dump file.
+ self.assertTrue(self.dbg.DeleteTarget(target))
+ if (os.path.isfile(core)):
+ os.unlink(core)
diff --git a/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/fizzbuzz.cpp b/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/fizzbuzz.cpp
new file mode 100644
index 000000000000..eb6476bfd9a9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/fizzbuzz.cpp
@@ -0,0 +1,31 @@
+// A sample program for getting minidumps on Windows.
+
+#include <iostream>
+
+bool
+fizz(int x)
+{
+ return x % 3 == 0;
+}
+
+bool
+buzz(int x)
+{
+ return x % 5 == 0;
+}
+
+int
+main()
+{
+ int *buggy = 0;
+
+ for (int i = 1; i <= 100; ++i)
+ {
+ if (fizz(i)) std::cout << "fizz";
+ if (buzz(i)) std::cout << "buzz";
+ if (!fizz(i) && !buzz(i)) std::cout << i;
+ std::cout << '\n';
+ }
+
+ return *buggy;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/fizzbuzz_no_heap.dmp b/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/fizzbuzz_no_heap.dmp
new file mode 100644
index 000000000000..19008c91fc3e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/fizzbuzz_no_heap.dmp
Binary files differ
diff --git a/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/main.cpp b/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/main.cpp
new file mode 100644
index 000000000000..4037ea522cac
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/postmortem/minidump/main.cpp
@@ -0,0 +1,21 @@
+int global = 42;
+
+int
+bar(int x)
+{
+ int y = 4*x + global;
+ return y;
+}
+
+int
+foo(int x)
+{
+ int y = 2*bar(3*x);
+ return y;
+}
+
+int
+main()
+{
+ return 0 * foo(1);
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/process_attach/Makefile b/packages/Python/lldbsuite/test/functionalities/process_attach/Makefile
new file mode 100644
index 000000000000..a964853f534b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/process_attach/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+EXE := ProcessAttach
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/process_attach/TestProcessAttach.py b/packages/Python/lldbsuite/test/functionalities/process_attach/TestProcessAttach.py
new file mode 100644
index 000000000000..83906b546300
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/process_attach/TestProcessAttach.py
@@ -0,0 +1,58 @@
+"""
+Test process attach.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+exe_name = "ProcessAttach" # Must match Makefile
+
+class ProcessAttachTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfiOSSimulator
+ def test_attach_to_process_by_id(self):
+ """Test attach by process id"""
+ self.build()
+ exe = os.path.join(os.getcwd(), exe_name)
+
+ # Spawn a new process
+ popen = self.spawnSubprocess(exe)
+ self.addTearDownHook(self.cleanupSubprocesses)
+
+ self.runCmd("process attach -p " + str(popen.pid))
+
+ target = self.dbg.GetSelectedTarget()
+
+ process = target.GetProcess()
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ def test_attach_to_process_by_name(self):
+ """Test attach by process name"""
+ self.build()
+ exe = os.path.join(os.getcwd(), exe_name)
+
+ # Spawn a new process
+ popen = self.spawnSubprocess(exe)
+ self.addTearDownHook(self.cleanupSubprocesses)
+
+ self.runCmd("process attach -n " + exe_name)
+
+ target = self.dbg.GetSelectedTarget()
+
+ process = target.GetProcess()
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ def tearDown(self):
+ # Destroy process before TestBase.tearDown()
+ self.dbg.GetSelectedTarget().GetProcess().Destroy()
+
+ # Call super's tearDown().
+ TestBase.tearDown(self)
diff --git a/packages/Python/lldbsuite/test/functionalities/process_attach/attach_denied/Makefile b/packages/Python/lldbsuite/test/functionalities/process_attach/attach_denied/Makefile
new file mode 100644
index 000000000000..87600bbccf9d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/process_attach/attach_denied/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+EXE := AttachDenied
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/process_attach/attach_denied/TestAttachDenied.py b/packages/Python/lldbsuite/test/functionalities/process_attach/attach_denied/TestAttachDenied.py
new file mode 100644
index 000000000000..ed9d58f90888
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/process_attach/attach_denied/TestAttachDenied.py
@@ -0,0 +1,60 @@
+"""
+Test denied process attach.
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import time
+import lldb
+from lldbsuite.test.lldbtest import *
+
+exe_name = 'AttachDenied' # Must match Makefile
+
+class AttachDeniedTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def run_platform_command(self, cmd):
+ platform = self.dbg.GetSelectedPlatform()
+ shell_command = lldb.SBPlatformShellCommand(cmd)
+ err = platform.Run(shell_command)
+ return (err, shell_command.GetStatus(), shell_command.GetOutput())
+
+ @skipIfWindows
+ @skipIfiOSSimulator
+ def test_attach_to_process_by_id_denied(self):
+ """Test attach by process id denied"""
+ self.build()
+ exe = os.path.join(os.getcwd(), exe_name)
+
+ # Use a file as a synchronization point between test and inferior.
+ pid_file_path = lldbutil.append_to_process_working_directory(
+ "pid_file_%d" % (int(time.time())))
+ self.addTearDownHook(lambda: self.run_platform_command("rm %s" % (pid_file_path)))
+
+ # Spawn a new process
+ popen = self.spawnSubprocess(exe, [pid_file_path])
+ self.addTearDownHook(self.cleanupSubprocesses)
+
+ max_attempts = 5
+ for i in range(max_attempts):
+ err, retcode, msg = self.run_platform_command("ls %s" % pid_file_path)
+ if err.Success() and retcode == 0:
+ break
+ else:
+ print(msg)
+ if i < max_attempts:
+ # Exponential backoff!
+ time.sleep(pow(2, i) * 0.25)
+ else:
+ self.fail("Child PID file %s not found even after %d attempts." % (pid_file_path, max_attempts))
+ err, retcode, pid = self.run_platform_command("cat %s" % (pid_file_path))
+ self.assertTrue(err.Success() and retcode == 0,
+ "Failed to read file %s: %s, retcode: %d" % (pid_file_path, err.GetCString(), retcode))
+
+ self.expect('process attach -p ' + pid,
+ startstr = 'error: attach failed:',
+ error = True)
diff --git a/packages/Python/lldbsuite/test/functionalities/process_attach/attach_denied/main.cpp b/packages/Python/lldbsuite/test/functionalities/process_attach/attach_denied/main.cpp
new file mode 100644
index 000000000000..ff1fccae4b1c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/process_attach/attach_denied/main.cpp
@@ -0,0 +1,108 @@
+#include <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <sys/types.h>
+#include <sys/ptrace.h>
+#include <sys/stat.h>
+#include <sys/wait.h>
+
+#if defined(PTRACE_ATTACH)
+#define ATTACH_REQUEST PTRACE_ATTACH
+#define DETACH_REQUEST PTRACE_DETACH
+#elif defined(PT_ATTACH)
+#define ATTACH_REQUEST PT_ATTACH
+#define DETACH_REQUEST PT_DETACH
+#else
+#error "Unsupported platform"
+#endif
+
+bool writePid (const char* file_name, const pid_t pid)
+{
+ char *tmp_file_name = (char *)malloc(strlen(file_name) + 16);
+ strcpy(tmp_file_name, file_name);
+ strcat(tmp_file_name, "_tmp");
+ int fd = open (tmp_file_name, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR);
+ if (fd == -1)
+ {
+ fprintf (stderr, "open(%s) failed: %s\n", tmp_file_name, strerror (errno));
+ free(tmp_file_name);
+ return false;
+ }
+ char buffer[64];
+ snprintf (buffer, sizeof(buffer), "%ld", (long)pid);
+
+ bool res = true;
+ if (write (fd, buffer, strlen (buffer)) == -1)
+ {
+ fprintf (stderr, "write(%s) failed: %s\n", buffer, strerror (errno));
+ res = false;
+ }
+ close (fd);
+
+ if (rename (tmp_file_name, file_name) == -1)
+ {
+ fprintf (stderr, "rename(%s, %s) failed: %s\n", tmp_file_name, file_name, strerror (errno));
+ res = false;
+ }
+ free(tmp_file_name);
+
+ return res;
+}
+
+void signal_handler (int)
+{
+}
+
+int main (int argc, char const *argv[])
+{
+ if (argc < 2)
+ {
+ fprintf (stderr, "invalid number of command line arguments\n");
+ return 1;
+ }
+
+ const pid_t pid = fork ();
+ if (pid == -1)
+ {
+ fprintf (stderr, "fork failed: %s\n", strerror (errno));
+ return 1;
+ }
+
+ if (pid > 0)
+ {
+ // Make pause call to return when a signal is received. Normally this happens when the
+ // test runner tries to terminate us.
+ signal (SIGHUP, signal_handler);
+ signal (SIGTERM, signal_handler);
+ if (ptrace (ATTACH_REQUEST, pid, NULL, 0) == -1)
+ {
+ fprintf (stderr, "ptrace(ATTACH) failed: %s\n", strerror (errno));
+ }
+ else
+ {
+ if (writePid (argv[1], pid))
+ pause (); // Waiting for the debugger trying attach to the child.
+
+ if (ptrace (DETACH_REQUEST, pid, NULL, 0) != 0)
+ fprintf (stderr, "ptrace(DETACH) failed: %s\n", strerror (errno));
+ }
+
+ kill (pid, SIGTERM);
+ int status = 0;
+ if (waitpid (pid, &status, 0) == -1)
+ fprintf (stderr, "waitpid failed: %s\n", strerror (errno));
+ }
+ else
+ {
+ // child inferior.
+ pause ();
+ }
+
+ printf ("Exiting now\n");
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/process_attach/main.cpp b/packages/Python/lldbsuite/test/functionalities/process_attach/main.cpp
new file mode 100644
index 000000000000..8021feac5c71
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/process_attach/main.cpp
@@ -0,0 +1,37 @@
+#include <stdio.h>
+
+#if defined(__linux__)
+#include <sys/prctl.h>
+#endif
+
+#include <chrono>
+#include <thread>
+
+int main(int argc, char const *argv[]) {
+ int temp;
+#if defined(__linux__)
+ // Immediately enable any ptracer so that we can allow the stub attach
+ // operation to succeed. Some Linux kernels are locked down so that
+ // only an ancestor process can be a ptracer of a process. This disables that
+ // restriction. Without it, attach-related stub tests will fail.
+#if defined(PR_SET_PTRACER) && defined(PR_SET_PTRACER_ANY)
+ int prctl_result;
+
+ // For now we execute on best effort basis. If this fails for
+ // some reason, so be it.
+ prctl_result = prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
+ (void) prctl_result;
+#endif
+#endif
+
+ // Waiting to be attached by the debugger.
+ temp = 0;
+
+ while (temp < 30) // Waiting to be attached...
+ {
+ std::this_thread::sleep_for(std::chrono::seconds(2));
+ temp++;
+ }
+
+ printf("Exiting now\n");
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/process_group/Makefile b/packages/Python/lldbsuite/test/functionalities/process_group/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/process_group/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/process_group/TestChangeProcessGroup.py b/packages/Python/lldbsuite/test/functionalities/process_group/TestChangeProcessGroup.py
new file mode 100644
index 000000000000..25be37b2b12d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/process_group/TestChangeProcessGroup.py
@@ -0,0 +1,107 @@
+"""Test that we handle inferiors which change their process group"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+
+class ChangeProcessGroupTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break for main.c.
+ self.line = line_number('main.c', '// Set breakpoint here')
+
+ @skipIfFreeBSD # Times out on FreeBSD llvm.org/pr23731
+ @skipIfWindows # setpgid call does not exist on Windows
+ @expectedFailureAndroid("http://llvm.org/pr23762", api_levels=[16])
+ def test_setpgid(self):
+ self.build()
+ exe = os.path.join(os.getcwd(), 'a.out')
+
+ # Use a file as a synchronization point between test and inferior.
+ pid_file_path = lldbutil.append_to_process_working_directory(
+ "pid_file_%d" % (int(time.time())))
+ self.addTearDownHook(lambda: self.run_platform_command("rm %s" % (pid_file_path)))
+
+ popen = self.spawnSubprocess(exe, [pid_file_path])
+ self.addTearDownHook(self.cleanupSubprocesses)
+
+ max_attempts = 5
+ for i in range(max_attempts):
+ err, retcode, msg = self.run_platform_command("ls %s" % pid_file_path)
+ if err.Success() and retcode == 0:
+ break
+ else:
+ print(msg)
+ if i < max_attempts:
+ # Exponential backoff!
+ time.sleep(pow(2, i) * 0.25)
+ else:
+ self.fail("Child PID file %s not found even after %d attempts." % (pid_file_path, max_attempts))
+
+ err, retcode, pid = self.run_platform_command("cat %s" % (pid_file_path))
+
+ self.assertTrue(err.Success() and retcode == 0,
+ "Failed to read file %s: %s, retcode: %d" % (pid_file_path, err.GetCString(), retcode))
+
+ # make sure we cleanup the forked child also
+ def cleanupChild():
+ if lldb.remote_platform:
+ lldb.remote_platform.Kill(int(pid))
+ else:
+ if os.path.exists("/proc/" + pid):
+ os.kill(int(pid), signal.SIGKILL)
+ self.addTearDownHook(cleanupChild)
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ listener = lldb.SBListener("my.attach.listener")
+ error = lldb.SBError()
+ process = target.AttachToProcessWithID(listener, int(pid), error)
+ self.assertTrue(error.Success() and process, PROCESS_IS_VALID)
+
+ # set a breakpoint just before the setpgid() call
+ lldbutil.run_break_set_by_file_and_line(self, 'main.c', self.line, num_expected_locations=-1)
+
+ thread = process.GetSelectedThread()
+
+ # release the child from its loop
+ value = thread.GetSelectedFrame().EvaluateExpression("release_child_flag = 1")
+ self.assertTrue(value.IsValid() and value.GetValueAsUnsigned(0) == 1);
+ process.Continue()
+
+ # make sure the child's process group id is different from its pid
+ value = thread.GetSelectedFrame().EvaluateExpression("(int)getpgid(0)")
+ self.assertTrue(value.IsValid())
+ self.assertNotEqual(value.GetValueAsUnsigned(0), int(pid));
+
+ # step over the setpgid() call
+ thread.StepOver()
+ self.assertEqual(thread.GetStopReason(), lldb.eStopReasonPlanComplete)
+
+ # verify that the process group has been set correctly
+ # this also checks that we are still in full control of the child
+ value = thread.GetSelectedFrame().EvaluateExpression("(int)getpgid(0)")
+ self.assertTrue(value.IsValid())
+ self.assertEqual(value.GetValueAsUnsigned(0), int(pid));
+
+ # run to completion
+ process.Continue()
+ self.assertEqual(process.GetState(), lldb.eStateExited)
+
+ def run_platform_command(self, cmd):
+ platform = self.dbg.GetSelectedPlatform()
+ shell_command = lldb.SBPlatformShellCommand(cmd)
+ err = platform.Run(shell_command)
+ return (err, shell_command.GetStatus(), shell_command.GetOutput())
diff --git a/packages/Python/lldbsuite/test/functionalities/process_group/main.c b/packages/Python/lldbsuite/test/functionalities/process_group/main.c
new file mode 100644
index 000000000000..c730c629e8b0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/process_group/main.c
@@ -0,0 +1,86 @@
+#include <stdio.h>
+#include <unistd.h>
+#include <sys/wait.h>
+
+#if defined(__linux__)
+#include <sys/prctl.h>
+#endif
+
+volatile int release_child_flag = 0;
+
+int main(int argc, char const *argv[])
+{
+ pid_t child = fork();
+ if (child == -1)
+ {
+ perror("fork");
+ return 1;
+ }
+
+ if (child > 0)
+ { // parent
+ if (argc < 2)
+ {
+ fprintf(stderr, "Need pid filename.\n");
+ return 2;
+ }
+
+ // Let the test suite know the child's pid.
+ FILE *pid_file = fopen(argv[1], "w");
+ if (pid_file == NULL)
+ {
+ perror("fopen");
+ return 3;
+ }
+
+ fprintf(pid_file, "%d\n", child);
+ if (fclose(pid_file) == EOF)
+ {
+ perror("fclose");
+ return 4;
+ }
+
+ // And wait for the child to finish it's work.
+ int status = 0;
+ pid_t wpid = wait(&status);
+ if (wpid == -1)
+ {
+ perror("wait");
+ return 5;
+ }
+ if (wpid != child)
+ {
+ fprintf(stderr, "wait() waited for wrong child\n");
+ return 6;
+ }
+ if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
+ {
+ fprintf(stderr, "child did not exit correctly\n");
+ return 7;
+ }
+ }
+ else
+ { // child
+#if defined(__linux__)
+ // Immediately enable any ptracer so that we can allow the stub attach
+ // operation to succeed. Some Linux kernels are locked down so that
+ // only an ancestor process can be a ptracer of a process. This disables that
+ // restriction. Without it, attach-related stub tests will fail.
+#if defined(PR_SET_PTRACER) && defined(PR_SET_PTRACER_ANY)
+ // For now we execute on best effort basis. If this fails for
+ // some reason, so be it.
+ const int prctl_result = prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
+ (void) prctl_result;
+#endif
+#endif
+
+ while (! release_child_flag) // Wait for debugger to attach
+ sleep(1);
+
+ printf("Child's previous process group is: %d\n", getpgid(0));
+ setpgid(0, 0); // Set breakpoint here
+ printf("Child's process group set to: %d\n", getpgid(0));
+ }
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/process_launch/Makefile b/packages/Python/lldbsuite/test/functionalities/process_launch/Makefile
new file mode 100644
index 000000000000..313da706b4a2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/process_launch/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+#CXX_SOURCES := print-cwd.cpp
+
+include $(LEVEL)/Makefile.rules
+
diff --git a/packages/Python/lldbsuite/test/functionalities/process_launch/TestProcessLaunch.py b/packages/Python/lldbsuite/test/functionalities/process_launch/TestProcessLaunch.py
new file mode 100644
index 000000000000..3131000be428
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/process_launch/TestProcessLaunch.py
@@ -0,0 +1,207 @@
+"""
+Test lldb process launch flags.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class ProcessLaunchTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # disable "There is a running process, kill it and restart?" prompt
+ self.runCmd("settings set auto-confirm true")
+ self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm"))
+
+ @not_remote_testsuite_ready
+ def test_io (self):
+ """Test that process launch I/O redirection flags work properly."""
+ self.build ()
+ exe = os.path.join (os.getcwd(), "a.out")
+ self.expect("file " + exe,
+ patterns = [ "Current executable set to .*a.out" ])
+
+ in_file = "input-file.txt"
+ out_file = "output-test.out"
+ err_file = "output-test.err"
+
+ # Make sure the output files do not exist before launching the process
+ try:
+ os.remove (out_file)
+ except OSError:
+ pass
+
+ try:
+ os.remove (err_file)
+ except OSError:
+ pass
+
+ launch_command = "process launch -i " + in_file + " -o " + out_file + " -e " + err_file
+
+ if lldb.remote_platform:
+ self.runCmd('platform put-file "{local}" "{remote}"'.format(
+ local=in_file, remote=in_file))
+
+ self.expect (launch_command,
+ patterns = [ "Process .* launched: .*a.out" ])
+
+ if lldb.remote_platform:
+ self.runCmd('platform get-file "{remote}" "{local}"'.format(
+ remote=out_file, local=out_file))
+ self.runCmd('platform get-file "{remote}" "{local}"'.format(
+ remote=err_file, local=err_file))
+
+ success = True
+ err_msg = ""
+
+ # Check to see if the 'stdout' file was created
+ try:
+ out_f = open (out_file)
+ except IOError:
+ success = False
+ err_msg = err_msg + " ERROR: stdout file was not created.\n"
+ else:
+ # Check to see if the 'stdout' file contains the right output
+ line = out_f.readline ();
+ if line != "This should go to stdout.\n":
+ success = False
+ err_msg = err_msg + " ERROR: stdout file does not contain correct output.\n"
+ out_f.close();
+
+ # Try to delete the 'stdout' file
+ try:
+ os.remove (out_file)
+ except OSError:
+ pass
+
+ # Check to see if the 'stderr' file was created
+ try:
+ err_f = open (err_file)
+ except IOError:
+ success = False
+ err_msg = err_msg + " ERROR: stderr file was not created.\n"
+ else:
+ # Check to see if the 'stderr' file contains the right output
+ line = err_f.readline ()
+ if line != "This should go to stderr.\n":
+ success = False
+ err_msg = err_msg + " ERROR: stderr file does not contain correct output.\n\
+"
+ err_f.close()
+
+ # Try to delete the 'stderr' file
+ try:
+ os.remove (err_file)
+ except OSError:
+ pass
+
+ if not success:
+ self.fail (err_msg)
+
+ # rdar://problem/9056462
+ # The process launch flag '-w' for setting the current working directory not working?
+ @not_remote_testsuite_ready
+ @expectedFailureLinux("llvm.org/pr20265")
+ def test_set_working_dir (self):
+ """Test that '-w dir' sets the working dir when running the inferior."""
+ d = {'CXX_SOURCES' : 'print_cwd.cpp'}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(d)
+ exe = os.path.join (os.getcwd(), "a.out")
+ self.runCmd("file " + exe)
+
+ mywd = 'my_working_dir'
+ out_file_name = "my_working_dir_test.out"
+ err_file_name = "my_working_dir_test.err"
+
+ my_working_dir_path = os.path.join(os.getcwd(), mywd)
+ out_file_path = os.path.join(my_working_dir_path, out_file_name)
+ err_file_path = os.path.join(my_working_dir_path, err_file_name)
+
+ # Make sure the output files do not exist before launching the process
+ try:
+ os.remove (out_file_path)
+ os.remove (err_file_path)
+ except OSError:
+ pass
+
+ # Check that we get an error when we have a nonexisting path
+ launch_command = "process launch -w %s -o %s -e %s" % (my_working_dir_path + 'z',
+ out_file_path,
+ err_file_path)
+
+ self.expect(launch_command, error=True,
+ patterns = ["error:.* No such file or directory: %sz" % my_working_dir_path])
+
+ # Really launch the process
+ launch_command = "process launch -w %s -o %s -e %s" % (my_working_dir_path,
+ out_file_path,
+ err_file_path)
+
+ self.expect(launch_command,
+ patterns = [ "Process .* launched: .*a.out" ])
+
+ success = True
+ err_msg = ""
+
+ # Check to see if the 'stdout' file was created
+ try:
+ out_f = open(out_file_path)
+ except IOError:
+ success = False
+ err_msg = err_msg + "ERROR: stdout file was not created.\n"
+ else:
+ # Check to see if the 'stdout' file contains the right output
+ line = out_f.readline();
+ if self.TraceOn():
+ print("line:", line)
+ if not re.search(mywd, line):
+ success = False
+ err_msg = err_msg + "The current working directory was not set correctly.\n"
+ out_f.close();
+
+ # Try to delete the 'stdout' and 'stderr' files
+ try:
+ os.remove(out_file_path)
+ os.remove(err_file_path)
+ pass
+ except OSError:
+ pass
+
+ if not success:
+ self.fail(err_msg)
+
+ def test_environment_with_special_char (self):
+ """Test that environment variables containing '*' and '}' are communicated correctly to the lldb-server."""
+ d = {'CXX_SOURCES' : 'print_env.cpp'}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(d)
+ exe = os.path.join (os.getcwd(), "a.out")
+
+ evil_var = 'INIT*MIDDLE}TAIL'
+
+ target = self.dbg.CreateTarget(exe)
+ process = target.LaunchSimple(None, ['EVIL=' + evil_var], self.get_process_working_directory())
+ self.assertEqual(process.GetState(), lldb.eStateExited, PROCESS_EXITED)
+
+ out = process.GetSTDOUT(len(evil_var))
+ self.assertIsNotNone(out, "Encountered an error reading the process's output")
+
+ out = out[:len(evil_var)]
+ if out != evil_var:
+ self.fail('The environment variable was mis-coded: %s\n' % repr(out))
+
+ newline = process.GetSTDOUT(1)
+ self.assertIsNotNone(newline, "Encountered an error reading the process's output")
+
+ newline = newline[0]
+ if newline != '\r' and newline != '\n':
+ self.fail('Garbage at end of environment variable')
diff --git a/packages/Python/lldbsuite/test/functionalities/process_launch/input-file.txt b/packages/Python/lldbsuite/test/functionalities/process_launch/input-file.txt
new file mode 100644
index 000000000000..cc269ba0ff8c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/process_launch/input-file.txt
@@ -0,0 +1,2 @@
+This should go to stdout.
+This should go to stderr.
diff --git a/packages/Python/lldbsuite/test/functionalities/process_launch/main.cpp b/packages/Python/lldbsuite/test/functionalities/process_launch/main.cpp
new file mode 100644
index 000000000000..f2035d551679
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/process_launch/main.cpp
@@ -0,0 +1,17 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+int
+main (int argc, char **argv)
+{
+ char buffer[1024];
+
+ fgets (buffer, sizeof (buffer), stdin);
+ fprintf (stdout, "%s", buffer);
+
+
+ fgets (buffer, sizeof (buffer), stdin);
+ fprintf (stderr, "%s", buffer);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/process_launch/my_working_dir/.keep b/packages/Python/lldbsuite/test/functionalities/process_launch/my_working_dir/.keep
new file mode 100644
index 000000000000..e69de29bb2d1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/process_launch/my_working_dir/.keep
diff --git a/packages/Python/lldbsuite/test/functionalities/process_launch/print_cwd.cpp b/packages/Python/lldbsuite/test/functionalities/process_launch/print_cwd.cpp
new file mode 100644
index 000000000000..b4b073fbcb8d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/process_launch/print_cwd.cpp
@@ -0,0 +1,21 @@
+#include <stdio.h>
+
+#ifdef _MSC_VER
+#define _CRT_NONSTDC_NO_WARNINGS
+#include <direct.h>
+#undef getcwd
+#define getcwd(buffer, length) _getcwd(buffer, length)
+#else
+#include <unistd.h>
+#endif
+
+int
+main (int argc, char **argv)
+{
+ char buffer[1024];
+
+ fprintf(stdout, "stdout: %s\n", getcwd(buffer, 1024));
+ fprintf(stderr, "stderr: %s\n", getcwd(buffer, 1024));
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/process_launch/print_env.cpp b/packages/Python/lldbsuite/test/functionalities/process_launch/print_env.cpp
new file mode 100644
index 000000000000..cbb9b2175916
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/process_launch/print_env.cpp
@@ -0,0 +1,11 @@
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+int main (int argc, char **argv)
+{
+ char *evil = getenv("EVIL");
+ puts(evil);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/process_save_core/Makefile b/packages/Python/lldbsuite/test/functionalities/process_save_core/Makefile
new file mode 100644
index 000000000000..b76d2cdb93f1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/process_save_core/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
+
diff --git a/packages/Python/lldbsuite/test/functionalities/process_save_core/TestProcessSaveCore.py b/packages/Python/lldbsuite/test/functionalities/process_save_core/TestProcessSaveCore.py
new file mode 100644
index 000000000000..0578bcf44b4c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/process_save_core/TestProcessSaveCore.py
@@ -0,0 +1,58 @@
+"""
+Test saving a core file (or mini dump).
+"""
+
+from __future__ import print_function
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class ProcessSaveCoreTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @not_remote_testsuite_ready
+ @skipUnlessWindows
+ def test_cannot_save_core_unless_process_stopped(self):
+ """Test that SaveCore fails if the process isn't stopped."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ core = os.path.join(os.getcwd(), "core.dmp")
+ target = self.dbg.CreateTarget(exe)
+ process = target.LaunchSimple(None, None, self.get_process_working_directory())
+ self.assertNotEqual(process.GetState(), lldb.eStateStopped)
+ error = process.SaveCore(core)
+ self.assertTrue(error.Fail())
+
+ @not_remote_testsuite_ready
+ @skipUnlessWindows
+ def test_save_windows_mini_dump(self):
+ """Test that we can save a Windows mini dump."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ core = os.path.join(os.getcwd(), "core.dmp")
+ try:
+ target = self.dbg.CreateTarget(exe)
+ breakpoint = target.BreakpointCreateByName("bar")
+ process = target.LaunchSimple(None, None, self.get_process_working_directory())
+ self.assertEqual(process.GetState(), lldb.eStateStopped)
+ self.assertTrue(process.SaveCore(core))
+ self.assertTrue(os.path.isfile(core))
+ self.assertTrue(process.Kill().Success())
+
+ # To verify, we'll launch with the mini dump, and ensure that we see
+ # the executable in the module list.
+ target = self.dbg.CreateTarget(None)
+ process = target.LoadCore(core)
+ files = [target.GetModuleAtIndex(i).GetFileSpec() for i in range(0, target.GetNumModules())]
+ paths = [os.path.join(f.GetDirectory(), f.GetFilename()) for f in files]
+ self.assertTrue(exe in paths)
+
+ finally:
+ # Clean up the mini dump file.
+ self.assertTrue(self.dbg.DeleteTarget(target))
+ if (os.path.isfile(core)):
+ os.unlink(core)
+
+
diff --git a/packages/Python/lldbsuite/test/functionalities/process_save_core/main.cpp b/packages/Python/lldbsuite/test/functionalities/process_save_core/main.cpp
new file mode 100644
index 000000000000..4037ea522cac
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/process_save_core/main.cpp
@@ -0,0 +1,21 @@
+int global = 42;
+
+int
+bar(int x)
+{
+ int y = 4*x + global;
+ return y;
+}
+
+int
+foo(int x)
+{
+ int y = 2*bar(3*x);
+ return y;
+}
+
+int
+main()
+{
+ return 0 * foo(1);
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/recursion/Makefile b/packages/Python/lldbsuite/test/functionalities/recursion/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/recursion/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/recursion/TestValueObjectRecursion.py b/packages/Python/lldbsuite/test/functionalities/recursion/TestValueObjectRecursion.py
new file mode 100644
index 000000000000..fcb493bc9d95
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/recursion/TestValueObjectRecursion.py
@@ -0,0 +1,59 @@
+"""
+Test lldb data formatter subsystem.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ValueObjectRecursionTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def test_with_run_command(self):
+ """Test that deeply nested ValueObjects still work."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ root = self.frame().FindVariable("root")
+ child = root.GetChildAtIndex(1)
+ if self.TraceOn():
+ print(root)
+ print(child)
+ for i in range(0,15000):
+ child = child.GetChildAtIndex(1)
+ if self.TraceOn():
+ print(child)
+ self.assertTrue(child.IsValid(),"could not retrieve the deep ValueObject")
+ self.assertTrue(child.GetChildAtIndex(0).IsValid(),"the deep ValueObject has no value")
+ self.assertTrue(child.GetChildAtIndex(0).GetValueAsUnsigned() != 0,"the deep ValueObject has a zero value")
+ self.assertTrue(child.GetChildAtIndex(1).GetValueAsUnsigned() != 0, "the deep ValueObject has no next")
diff --git a/packages/Python/lldbsuite/test/functionalities/recursion/main.cpp b/packages/Python/lldbsuite/test/functionalities/recursion/main.cpp
new file mode 100644
index 000000000000..f75a7f8698bb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/recursion/main.cpp
@@ -0,0 +1,41 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+
+struct node;
+struct node {
+ int value;
+ node* next;
+ node () : value(1),next(NULL) {}
+ node (int v) : value(v), next(NULL) {}
+};
+
+void make_tree(node* root, int count)
+{
+ int countdown=1;
+ if (!root)
+ return;
+ root->value = countdown;
+ while (count > 0)
+ {
+ root->next = new node(++countdown);
+ root = root->next;
+ count--;
+ }
+}
+
+int main (int argc, const char * argv[])
+{
+ node root(1);
+ make_tree(&root,25000);
+ return 0; // Set break point at this line.
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/register/Makefile b/packages/Python/lldbsuite/test/functionalities/register/Makefile
new file mode 100644
index 000000000000..7144b25c58c9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/register/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp a.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/register/TestRegisters.py b/packages/Python/lldbsuite/test/functionalities/register/TestRegisters.py
new file mode 100644
index 000000000000..c5d4650aa371
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/register/TestRegisters.py
@@ -0,0 +1,349 @@
+"""
+Test the 'register' command.
+"""
+
+from __future__ import print_function
+
+
+
+import os, sys, time
+import re
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class RegisterCommandsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ TestBase.setUp(self)
+ self.has_teardown = False
+
+ def tearDown(self):
+ self.dbg.GetSelectedTarget().GetProcess().Destroy()
+ TestBase.tearDown(self)
+
+ @skipIfiOSSimulator
+ @skipUnlessArch(['amd64', 'arm', 'i386', 'x86_64'])
+ def test_register_commands(self):
+ """Test commands related to registers, in particular vector registers."""
+ self.build()
+ self.common_setup()
+
+ # verify that logging does not assert
+ self.log_enable("registers")
+
+ self.expect("register read -a", MISSING_EXPECTED_REGISTERS,
+ substrs = ['registers were unavailable'], matching = False)
+
+ if self.getArchitecture() in ['amd64', 'i386', 'x86_64']:
+ self.runCmd("register read xmm0")
+ self.runCmd("register read ymm15") # may be available
+ elif self.getArchitecture() in ['arm']:
+ self.runCmd("register read s0")
+ self.runCmd("register read q15") # may be available
+
+ self.expect("register read -s 3", substrs = ['invalid register set index: 3'], error = True)
+
+ @skipIfiOSSimulator
+ @skipIfTargetAndroid(archs=["i386"]) # Writing of mxcsr register fails, presumably due to a kernel/hardware problem
+ @skipUnlessArch(['amd64', 'arm', 'i386', 'x86_64'])
+ def test_fp_register_write(self):
+ """Test commands that write to registers, in particular floating-point registers."""
+ self.build()
+ self.fp_register_write()
+
+ @skipIfiOSSimulator
+ @expectedFailureAndroid(archs=["i386"]) # "register read fstat" always return 0xffff
+ @skipIfFreeBSD #llvm.org/pr25057
+ @skipUnlessArch(['amd64', 'i386', 'x86_64'])
+ def test_fp_special_purpose_register_read(self):
+ """Test commands that read fpu special purpose registers."""
+ self.build()
+ self.fp_special_purpose_register_read()
+
+ @skipIfiOSSimulator
+ @skipUnlessArch(['amd64', 'arm', 'i386', 'x86_64'])
+ def test_register_expressions(self):
+ """Test expression evaluation with commands related to registers."""
+ self.build()
+ self.common_setup()
+
+ if self.getArchitecture() in ['amd64', 'i386', 'x86_64']:
+ gpr = "eax"
+ vector = "xmm0"
+ elif self.getArchitecture() in ['arm']:
+ gpr = "r0"
+ vector = "q0"
+
+ self.expect("expr/x $%s" % gpr, substrs = ['unsigned int', ' = 0x'])
+ self.expect("expr $%s" % vector, substrs = ['vector_type'])
+ self.expect("expr (unsigned int)$%s[0]" % vector, substrs = ['unsigned int'])
+
+ if self.getArchitecture() in ['amd64', 'x86_64']:
+ self.expect("expr -- ($rax & 0xffffffff) == $eax", substrs = ['true'])
+
+ @skipIfiOSSimulator
+ @skipUnlessArch(['amd64', 'x86_64'])
+ def test_convenience_registers(self):
+ """Test convenience registers."""
+ self.build()
+ self.convenience_registers()
+
+ @skipIfiOSSimulator
+ @skipUnlessArch(['amd64', 'x86_64'])
+ def test_convenience_registers_with_process_attach(self):
+ """Test convenience registers after a 'process attach'."""
+ self.build()
+ self.convenience_registers_with_process_attach(test_16bit_regs=False)
+
+ @skipIfiOSSimulator
+ @skipUnlessArch(['amd64', 'x86_64'])
+ def test_convenience_registers_16bit_with_process_attach(self):
+ """Test convenience registers after a 'process attach'."""
+ self.build()
+ self.convenience_registers_with_process_attach(test_16bit_regs=True)
+
+ def common_setup(self):
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break in main().
+ lldbutil.run_break_set_by_symbol (self, "main", num_expected_locations=-1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped', 'stop reason = breakpoint'])
+
+ # platform specific logging of the specified category
+ def log_enable(self, category):
+ # This intentionally checks the host platform rather than the target
+ # platform as logging is host side.
+ self.platform = ""
+ if sys.platform.startswith("darwin"):
+ self.platform = "" # TODO: add support for "log enable darwin registers"
+
+ if sys.platform.startswith("freebsd"):
+ self.platform = "freebsd"
+
+ if sys.platform.startswith("linux"):
+ self.platform = "linux"
+
+ if sys.platform.startswith("netbsd"):
+ self.platform = "netbsd"
+
+ if self.platform != "":
+ self.log_file = os.path.join(os.getcwd(), 'TestRegisters.log')
+ self.runCmd("log enable " + self.platform + " " + str(category) + " registers -v -f " + self.log_file, RUN_SUCCEEDED)
+ if not self.has_teardown:
+ def remove_log(self):
+ if os.path.exists(self.log_file):
+ os.remove(self.log_file)
+ self.has_teardown = True
+ self.addTearDownHook(remove_log)
+
+ def write_and_read(self, frame, register, new_value, must_exist = True):
+ value = frame.FindValue(register, lldb.eValueTypeRegister)
+ if must_exist:
+ self.assertTrue(value.IsValid(), "finding a value for register " + register)
+ elif not value.IsValid():
+ return # If register doesn't exist, skip this test
+
+ self.runCmd("register write " + register + " \'" + new_value + "\'")
+ self.expect("register read " + register, substrs = [register + ' = ', new_value])
+
+ def fp_special_purpose_register_read(self):
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Launch the process and stop.
+ self.expect ("run", PROCESS_STOPPED, substrs = ['stopped'])
+
+ # Check stop reason; Should be either signal SIGTRAP or EXC_BREAKPOINT
+ output = self.res.GetOutput()
+ matched = False
+ substrs = ['stop reason = EXC_BREAKPOINT', 'stop reason = signal SIGTRAP']
+ for str1 in substrs:
+ matched = output.find(str1) != -1
+ with recording(self, False) as sbuf:
+ print("%s sub string: %s" % ('Expecting', str1), file=sbuf)
+ print("Matched" if matched else "Not Matched", file=sbuf)
+ if matched:
+ break
+ self.assertTrue(matched, STOPPED_DUE_TO_SIGNAL)
+
+ process = target.GetProcess()
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+
+ thread = process.GetThreadAtIndex(0)
+ self.assertTrue(thread.IsValid(), "current thread is valid")
+
+ currentFrame = thread.GetFrameAtIndex(0)
+ self.assertTrue(currentFrame.IsValid(), "current frame is valid")
+
+ # Extract the value of fstat and ftag flag at the point just before
+ # we start pushing floating point values on st% register stack
+ value = currentFrame.FindValue("fstat", lldb.eValueTypeRegister)
+ error = lldb.SBError()
+ reg_value_fstat_initial = value.GetValueAsUnsigned(error, 0)
+
+ self.assertTrue(error.Success(), "reading a value for fstat")
+ value = currentFrame.FindValue("ftag", lldb.eValueTypeRegister)
+ error = lldb.SBError()
+ reg_value_ftag_initial = value.GetValueAsUnsigned(error, 0)
+
+ self.assertTrue(error.Success(), "reading a value for ftag")
+ fstat_top_pointer_initial = (reg_value_fstat_initial & 0x3800)>>11
+
+ # Execute 'si' aka 'thread step-inst' instruction 5 times and with
+ # every execution verify the value of fstat and ftag registers
+ for x in range(0,5):
+ # step into the next instruction to push a value on 'st' register stack
+ self.runCmd ("si", RUN_SUCCEEDED)
+
+ # Verify fstat and save it to be used for verification in next execution of 'si' command
+ if not (reg_value_fstat_initial & 0x3800):
+ self.expect("register read fstat",
+ substrs = ['fstat' + ' = ', str("0x%0.4x" %((reg_value_fstat_initial & ~(0x3800))| 0x3800))])
+ reg_value_fstat_initial = ((reg_value_fstat_initial & ~(0x3800))| 0x3800)
+ fstat_top_pointer_initial = 7
+ else :
+ self.expect("register read fstat",
+ substrs = ['fstat' + ' = ', str("0x%0.4x" % (reg_value_fstat_initial - 0x0800))])
+ reg_value_fstat_initial = (reg_value_fstat_initial - 0x0800)
+ fstat_top_pointer_initial -= 1
+
+ # Verify ftag and save it to be used for verification in next execution of 'si' command
+ self.expect("register read ftag",
+ substrs = ['ftag' + ' = ', str("0x%0.2x" % (reg_value_ftag_initial | (1<< fstat_top_pointer_initial)))])
+ reg_value_ftag_initial = reg_value_ftag_initial | (1<< fstat_top_pointer_initial)
+
+ def fp_register_write(self):
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ lldbutil.run_break_set_by_symbol (self, "main", num_expected_locations=-1)
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ process = target.GetProcess()
+ self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED)
+
+ thread = process.GetThreadAtIndex(0)
+ self.assertTrue(thread.IsValid(), "current thread is valid")
+
+ currentFrame = thread.GetFrameAtIndex(0)
+ self.assertTrue(currentFrame.IsValid(), "current frame is valid")
+
+ if self.getArchitecture() in ['amd64', 'i386', 'x86_64']:
+ reg_list = [
+ # reg value must-have
+ ("fcw", "0x0000ff0e", False),
+ ("fsw", "0x0000ff0e", False),
+ ("ftw", "0x0000ff0e", False),
+ ("ip", "0x0000ff0e", False),
+ ("dp", "0x0000ff0e", False),
+ ("mxcsr", "0x0000ff0e", False),
+ ("mxcsrmask", "0x0000ff0e", False),
+ ]
+
+ st0regname = None
+ if currentFrame.FindRegister("st0").IsValid():
+ st0regname = "st0"
+ elif currentFrame.FindRegister("stmm0").IsValid():
+ st0regname = "stmm0"
+ if st0regname is not None:
+ # reg value must-have
+ reg_list.append((st0regname, "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x00 0x00}", True))
+ reg_list.append(("xmm0", "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x2f 0x2f}", True))
+ reg_list.append(("xmm15", "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f}", False))
+ elif self.getArchitecture() in ['arm']:
+ reg_list = [
+ # reg value must-have
+ ("fpscr", "0xfbf79f9f", True),
+ ("s0", "1.25", True),
+ ("s31", "0.75", True),
+ ("d1", "123", True),
+ ("d17", "987", False),
+ ("q1", "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x2f 0x2f}", True),
+ ("q14", "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f}", False),
+ ]
+
+ for (reg, val, must) in reg_list:
+ self.write_and_read(currentFrame, reg, val, must)
+
+ if self.getArchitecture() in ['amd64', 'i386', 'x86_64']:
+ self.runCmd("register write " + st0regname + " \"{0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00}\"")
+ self.expect("register read " + st0regname + " --format f", substrs = [st0regname + ' = 0'])
+
+ has_avx = False
+ registerSets = currentFrame.GetRegisters() # Returns an SBValueList.
+ for registerSet in registerSets:
+ if 'advanced vector extensions' in registerSet.GetName().lower():
+ has_avx = True
+ break
+
+ if has_avx:
+ new_value = "{0x01 0x02 0x03 0x00 0x00 0x00 0x00 0x00 0x09 0x0a 0x2f 0x2f 0x2f 0x2f 0x0e 0x0f 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x0c 0x0d 0x0e 0x0f}"
+ self.write_and_read(currentFrame, "ymm0", new_value)
+ self.write_and_read(currentFrame, "ymm7", new_value)
+ self.expect("expr $ymm0", substrs = ['vector_type'])
+ else:
+ self.runCmd("register read ymm0")
+
+ def convenience_registers(self):
+ """Test convenience registers."""
+ self.common_setup()
+
+ # The command "register read -a" does output a derived register like eax...
+ self.expect("register read -a", matching=True,
+ substrs = ['eax'])
+
+ # ...however, the vanilla "register read" command should not output derived registers like eax.
+ self.expect("register read", matching=False,
+ substrs = ['eax'])
+
+ # Test reading of rax and eax.
+ self.expect("register read rax eax",
+ substrs = ['rax = 0x', 'eax = 0x'])
+
+ # Now write rax with a unique bit pattern and test that eax indeed represents the lower half of rax.
+ self.runCmd("register write rax 0x1234567887654321")
+ self.expect("register read rax 0x1234567887654321",
+ substrs = ['0x1234567887654321'])
+
+ def convenience_registers_with_process_attach(self, test_16bit_regs):
+ """Test convenience registers after a 'process attach'."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Spawn a new process
+ pid = self.spawnSubprocess(exe, ['wait_for_attach']).pid
+ self.addTearDownHook(self.cleanupSubprocesses)
+
+ if self.TraceOn():
+ print("pid of spawned process: %d" % pid)
+
+ self.runCmd("process attach -p %d" % pid)
+
+ # Check that "register read eax" works.
+ self.runCmd("register read eax")
+
+ if self.getArchitecture() in ['amd64', 'x86_64']:
+ self.expect("expr -- ($rax & 0xffffffff) == $eax",
+ substrs = ['true'])
+
+ if test_16bit_regs:
+ self.expect("expr -- $ax == (($ah << 8) | $al)",
+ substrs = ['true'])
diff --git a/packages/Python/lldbsuite/test/functionalities/register/a.cpp b/packages/Python/lldbsuite/test/functionalities/register/a.cpp
new file mode 100644
index 000000000000..fbacec1918e8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/register/a.cpp
@@ -0,0 +1,44 @@
+//===-- a.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+long double
+return_long_double (long double value)
+{
+#if defined (__i386__) || defined (__x86_64__)
+ float a=2, b=4,c=8, d=16, e=32, f=64, k=128, l=256, add=0;
+ __asm__ (
+ "int3 ;"
+ "flds %1 ;"
+ "flds %2 ;"
+ "flds %3 ;"
+ "flds %4 ;"
+ "flds %5 ;"
+ "flds %6 ;"
+ "flds %7 ;"
+ "faddp ;" : "=g" (add) : "g" (a), "g" (b), "g" (c), "g" (d), "g" (e), "g" (f), "g" (k), "g" (l) ); // Set break point at this line.
+#endif // #if defined (__i386__) || defined (__x86_64__)
+ return value;
+}
+
+long double
+outer_return_long_double (long double value)
+{
+ long double val = return_long_double(value);
+ val *= 2 ;
+ return val;
+}
+
+long double
+outermost_return_long_double (long double value)
+{
+ long double val = outer_return_long_double(value);
+ val *= 2 ;
+ return val;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/register/main.cpp b/packages/Python/lldbsuite/test/functionalities/register/main.cpp
new file mode 100644
index 000000000000..876dd0833e54
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/register/main.cpp
@@ -0,0 +1,51 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+#if defined(__linux__)
+#include <sys/prctl.h>
+#endif
+
+#include <chrono>
+#include <thread>
+
+long double outermost_return_long_double (long double my_long_double);
+
+int main (int argc, char const *argv[])
+{
+#if defined(__linux__)
+ // Immediately enable any ptracer so that we can allow the stub attach
+ // operation to succeed. Some Linux kernels are locked down so that
+ // only an ancestor process can be a ptracer of a process. This disables that
+ // restriction. Without it, attach-related stub tests will fail.
+#if defined(PR_SET_PTRACER) && defined(PR_SET_PTRACER_ANY)
+ // For now we execute on best effort basis. If this fails for
+ // some reason, so be it.
+ const int prctl_result = prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
+ static_cast<void> (prctl_result);
+#endif
+#endif
+
+ char my_string[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 0};
+ double my_double = 1234.5678;
+ long double my_long_double = 1234.5678;
+
+ // For simplicity assume that any cmdline argument means wait for attach.
+ if (argc > 1)
+ {
+ volatile int wait_for_attach=1;
+ while (wait_for_attach)
+ std::this_thread::sleep_for(std::chrono::microseconds(1));
+ }
+
+ printf("my_string=%s\n", my_string);
+ printf("my_double=%g\n", my_double);
+ outermost_return_long_double (my_long_double);
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/rerun/Makefile b/packages/Python/lldbsuite/test/functionalities/rerun/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/rerun/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/rerun/TestRerun.py b/packages/Python/lldbsuite/test/functionalities/rerun/TestRerun.py
new file mode 100644
index 000000000000..0ed56de35699
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/rerun/TestRerun.py
@@ -0,0 +1,76 @@
+"""
+Test that argdumper is a viable launching strategy.
+"""
+from __future__ import print_function
+
+
+
+import lldb
+import os
+import time
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TestRerun(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test (self):
+ self.build()
+ exe = os.path.join (os.getcwd(), "a.out")
+
+ self.runCmd("target create %s" % exe)
+
+ # Create the target
+ target = self.dbg.CreateTarget(exe)
+
+ # Create any breakpoints we need
+ breakpoint = target.BreakpointCreateBySourceRegex ('break here', lldb.SBFileSpec ("main.cpp", False))
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ self.runCmd("process launch 1 2 3")
+
+ process = self.process()
+
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ STOPPED_DUE_TO_BREAKPOINT)
+
+ thread = process.GetThreadAtIndex (0)
+
+ self.assertTrue (thread.IsValid(),
+ "Process stopped at 'main' should have a valid thread");
+
+ stop_reason = thread.GetStopReason()
+
+ self.assertTrue (stop_reason == lldb.eStopReasonBreakpoint,
+ "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint");
+
+ self.expect("frame variable argv[1]", substrs=['1'])
+ self.expect("frame variable argv[2]", substrs=['2'])
+ self.expect("frame variable argv[3]", substrs=['3'])
+
+ # Let program exit
+ self.runCmd("continue")
+
+ # Re-run with no args and make sure we still run with 1 2 3 as arguments as
+ # they should have been stored in "target.run-args"
+ self.runCmd("process launch")
+
+ process = self.process()
+
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ STOPPED_DUE_TO_BREAKPOINT)
+
+ thread = process.GetThreadAtIndex (0)
+
+ self.assertTrue (thread.IsValid(),
+ "Process stopped at 'main' should have a valid thread");
+
+ stop_reason = thread.GetStopReason()
+
+ self.assertTrue (stop_reason == lldb.eStopReasonBreakpoint,
+ "Thread in process stopped in 'main' should have a stop reason of eStopReasonBreakpoint");
+
+ self.expect("frame variable argv[1]", substrs=['1'])
+ self.expect("frame variable argv[2]", substrs=['2'])
+ self.expect("frame variable argv[3]", substrs=['3'])
diff --git a/packages/Python/lldbsuite/test/functionalities/rerun/main.cpp b/packages/Python/lldbsuite/test/functionalities/rerun/main.cpp
new file mode 100644
index 000000000000..cbef8d1e6da1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/rerun/main.cpp
@@ -0,0 +1,5 @@
+int
+main (int argc, char const **argv)
+{
+ return 0; // break here
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/return-value/Makefile b/packages/Python/lldbsuite/test/functionalities/return-value/Makefile
new file mode 100644
index 000000000000..cb03eabfc274
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/return-value/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := call-func.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/return-value/TestReturnValue.py b/packages/Python/lldbsuite/test/functionalities/return-value/TestReturnValue.py
new file mode 100644
index 000000000000..246eb5c3fdbd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/return-value/TestReturnValue.py
@@ -0,0 +1,214 @@
+"""
+Test getting return-values correctly when stepping out
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ReturnValueTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureAll(oslist=["macosx","freebsd"], archs=["i386"])
+ @expectedFailureAll(oslist=["linux"], compiler="clang", compiler_version=["<=", "3.6"], archs=["i386"])
+ @expectedFailureAll(bugnumber="llvm.org/pr25785", hostoslist=["windows"], compiler="gcc", archs=["i386"], triple='.*-android')
+ @expectedFailureWindows("llvm.org/pr24778")
+ @add_test_categories(['pyapi'])
+ def test_with_python(self):
+ """Test getting return values from stepping out."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ error = lldb.SBError()
+
+ self.target = self.dbg.CreateTarget(exe)
+ self.assertTrue(self.target, VALID_TARGET)
+
+ inner_sint_bkpt = self.target.BreakpointCreateByName("inner_sint", exe)
+ self.assertTrue(inner_sint_bkpt, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ self.process = self.target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(self.process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ self.assertTrue(self.process.GetState() == lldb.eStateStopped,
+ STOPPED_DUE_TO_BREAKPOINT)
+
+ # Now finish, and make sure the return value is correct.
+ thread = lldbutil.get_stopped_thread (self.process, lldb.eStopReasonBreakpoint)
+
+ # inner_sint returns the variable value, so capture that here:
+ in_int = thread.GetFrameAtIndex(0).FindVariable ("value").GetValueAsSigned(error)
+ self.assertTrue (error.Success())
+
+ thread.StepOut();
+
+ self.assertTrue (self.process.GetState() == lldb.eStateStopped)
+ self.assertTrue (thread.GetStopReason() == lldb.eStopReasonPlanComplete)
+
+ frame = thread.GetFrameAtIndex(0)
+ fun_name = frame.GetFunctionName()
+ self.assertTrue (fun_name == "outer_sint")
+
+ return_value = thread.GetStopReturnValue()
+ self.assertTrue (return_value.IsValid())
+
+ ret_int = return_value.GetValueAsSigned(error)
+ self.assertTrue (error.Success())
+ self.assertTrue (in_int == ret_int)
+
+ # Run again and we will stop in inner_sint the second time outer_sint is called.
+ #Then test stepping out two frames at once:
+
+ self.process.Continue()
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (self.process, inner_sint_bkpt)
+ self.assertTrue(len(thread_list) == 1)
+ thread = thread_list[0]
+
+ # We are done with the inner_sint breakpoint:
+ self.target.BreakpointDelete (inner_sint_bkpt.GetID())
+
+ frame = thread.GetFrameAtIndex(1)
+ fun_name = frame.GetFunctionName ()
+ self.assertTrue (fun_name == "outer_sint")
+ in_int = frame.FindVariable ("value").GetValueAsSigned(error)
+ self.assertTrue (error.Success())
+
+ thread.StepOutOfFrame (frame)
+
+ self.assertTrue (self.process.GetState() == lldb.eStateStopped)
+ self.assertTrue (thread.GetStopReason() == lldb.eStopReasonPlanComplete)
+ frame = thread.GetFrameAtIndex(0)
+ fun_name = frame.GetFunctionName()
+ self.assertTrue (fun_name == "main")
+
+ ret_value = thread.GetStopReturnValue()
+ self.assertTrue (return_value.IsValid())
+ ret_int = ret_value.GetValueAsSigned (error)
+ self.assertTrue (error.Success())
+ self.assertTrue (2 * in_int == ret_int)
+
+ # Now try some simple returns that have different types:
+ inner_float_bkpt = self.target.BreakpointCreateByName("inner_float", exe)
+ self.assertTrue(inner_float_bkpt, VALID_BREAKPOINT)
+ self.process.Continue()
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (self.process, inner_float_bkpt)
+ self.assertTrue (len(thread_list) == 1)
+ thread = thread_list[0]
+
+ self.target.BreakpointDelete (inner_float_bkpt.GetID())
+
+ frame = thread.GetFrameAtIndex(0)
+ in_value = frame.FindVariable ("value")
+ in_float = float (in_value.GetValue())
+ thread.StepOut()
+
+ self.assertTrue (self.process.GetState() == lldb.eStateStopped)
+ self.assertTrue (thread.GetStopReason() == lldb.eStopReasonPlanComplete)
+
+ frame = thread.GetFrameAtIndex(0)
+ fun_name = frame.GetFunctionName()
+ self.assertTrue (fun_name == "outer_float")
+
+ return_value = thread.GetStopReturnValue()
+ self.assertTrue (return_value.IsValid())
+ return_float = float (return_value.GetValue())
+
+ self.assertTrue(in_float == return_float)
+
+ self.return_and_test_struct_value ("return_one_int")
+ self.return_and_test_struct_value ("return_two_int")
+ self.return_and_test_struct_value ("return_three_int")
+ self.return_and_test_struct_value ("return_four_int")
+ self.return_and_test_struct_value ("return_five_int")
+
+ self.return_and_test_struct_value ("return_two_double")
+ self.return_and_test_struct_value ("return_one_double_two_float")
+ self.return_and_test_struct_value ("return_one_int_one_float_one_int")
+
+ self.return_and_test_struct_value ("return_one_pointer")
+ self.return_and_test_struct_value ("return_two_pointer")
+ self.return_and_test_struct_value ("return_one_float_one_pointer")
+ self.return_and_test_struct_value ("return_one_int_one_pointer")
+ self.return_and_test_struct_value ("return_three_short_one_float")
+
+ self.return_and_test_struct_value ("return_one_int_one_double")
+ self.return_and_test_struct_value ("return_one_int_one_double_one_int")
+ self.return_and_test_struct_value ("return_one_short_one_double_one_short")
+ self.return_and_test_struct_value ("return_one_float_one_int_one_float")
+ self.return_and_test_struct_value ("return_two_float")
+ # I am leaving out the packed test until we have a way to tell CLANG
+ # about alignment when reading DWARF for packed types.
+ #self.return_and_test_struct_value ("return_one_int_one_double_packed")
+ self.return_and_test_struct_value ("return_one_int_one_long")
+
+ # icc and gcc don't support this extension.
+ if self.getCompiler().endswith('clang'):
+ self.return_and_test_struct_value ("return_vector_size_float32_8")
+ self.return_and_test_struct_value ("return_vector_size_float32_16")
+ self.return_and_test_struct_value ("return_vector_size_float32_32")
+ self.return_and_test_struct_value ("return_ext_vector_size_float32_2")
+ self.return_and_test_struct_value ("return_ext_vector_size_float32_4")
+ self.return_and_test_struct_value ("return_ext_vector_size_float32_8")
+
+ def return_and_test_struct_value (self, func_name):
+ """Pass in the name of the function to return from - takes in value, returns value."""
+
+ # Set the breakpoint, run to it, finish out.
+ bkpt = self.target.BreakpointCreateByName (func_name)
+ self.assertTrue (bkpt.GetNumResolvedLocations() > 0)
+
+ self.process.Continue ()
+
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (self.process, bkpt)
+
+ self.assertTrue (len(thread_list) == 1)
+ thread = thread_list[0]
+
+ self.target.BreakpointDelete (bkpt.GetID())
+
+ in_value = thread.GetFrameAtIndex(0).FindVariable ("value")
+
+ self.assertTrue (in_value.IsValid())
+ num_in_children = in_value.GetNumChildren()
+
+ # This is a little hokey, but if we don't get all the children now, then
+ # once we've stepped we won't be able to get them?
+
+ for idx in range(0, num_in_children):
+ in_child = in_value.GetChildAtIndex (idx)
+ in_child_str = in_child.GetValue()
+
+ thread.StepOut()
+
+ self.assertTrue (self.process.GetState() == lldb.eStateStopped)
+ self.assertTrue (thread.GetStopReason() == lldb.eStopReasonPlanComplete)
+
+ # Assuming all these functions step out to main. Could figure out the caller dynamically
+ # if that would add something to the test.
+ frame = thread.GetFrameAtIndex(0)
+ fun_name = frame.GetFunctionName()
+ self.assertTrue (fun_name == "main")
+
+ frame = thread.GetFrameAtIndex(0)
+ ret_value = thread.GetStopReturnValue()
+
+ self.assertTrue (ret_value.IsValid())
+
+ num_ret_children = ret_value.GetNumChildren()
+ self.assertTrue (num_in_children == num_ret_children)
+ for idx in range(0, num_ret_children):
+ in_child = in_value.GetChildAtIndex(idx)
+ ret_child = ret_value.GetChildAtIndex(idx)
+ in_child_str = in_child.GetValue()
+ ret_child_str = ret_child.GetValue()
+
+ self.assertEqual(in_child_str, ret_child_str)
diff --git a/packages/Python/lldbsuite/test/functionalities/return-value/call-func.c b/packages/Python/lldbsuite/test/functionalities/return-value/call-func.c
new file mode 100644
index 000000000000..0c026ffcca17
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/return-value/call-func.c
@@ -0,0 +1,407 @@
+// Some convenient things to return:
+static char *g_first_pointer = "I am the first";
+static char *g_second_pointer = "I am the second";
+
+// First we have some simple functions that return standard types, ints, floats and doubles.
+// We have a function calling a function in a few cases to test that if you stop in the
+// inner function then do "up/fin" you get the return value from the outer-most frame.
+
+int
+inner_sint (int value)
+{
+ return value;
+}
+
+int
+outer_sint (int value)
+{
+ int outer_value = 2 * inner_sint (value);
+ return outer_value;
+}
+
+float
+inner_float (float value)
+{
+ return value;
+}
+
+float
+outer_float (float value)
+{
+ float outer_value = 2 * inner_float(value);
+ return outer_value;
+}
+
+double
+return_double (double value)
+{
+ return value;
+}
+
+long double
+return_long_double (long double value)
+{
+ return value;
+}
+
+char *
+return_pointer (char *value)
+{
+ return value;
+}
+
+struct one_int
+{
+ int one_field;
+};
+
+struct one_int
+return_one_int (struct one_int value)
+{
+ return value;
+}
+
+struct two_int
+{
+ int first_field;
+ int second_field;
+};
+
+struct two_int
+return_two_int (struct two_int value)
+{
+ return value;
+}
+
+struct three_int
+{
+ int first_field;
+ int second_field;
+ int third_field;
+};
+
+struct three_int
+return_three_int (struct three_int value)
+{
+ return value;
+}
+
+struct four_int
+{
+ int first_field;
+ int second_field;
+ int third_field;
+ int fourth_field;
+};
+
+struct four_int
+return_four_int (struct four_int value)
+{
+ return value;
+}
+
+struct five_int
+{
+ int first_field;
+ int second_field;
+ int third_field;
+ int fourth_field;
+ int fifth_field;
+};
+
+struct five_int
+return_five_int (struct five_int value)
+{
+ return value;
+}
+
+struct one_int_one_double
+{
+ int first_field;
+ double second_field;
+};
+
+struct one_int_one_double
+return_one_int_one_double (struct one_int_one_double value)
+{
+ return value;
+}
+
+struct one_int_one_double_one_int
+{
+ int one_field;
+ double second_field;
+ int third_field;
+};
+
+struct one_int_one_double_one_int
+return_one_int_one_double_one_int (struct one_int_one_double_one_int value)
+{
+ return value;
+}
+
+struct one_short_one_double_one_short
+{
+ int one_field;
+ double second_field;
+ int third_field;
+};
+
+struct one_short_one_double_one_short
+return_one_short_one_double_one_short (struct one_short_one_double_one_short value)
+{
+ return value;
+}
+
+struct three_short_one_float
+{
+ short one_field;
+ short second_field;
+ short third_field;
+ float fourth_field;
+};
+
+struct three_short_one_float
+return_three_short_one_float (struct three_short_one_float value)
+{
+ return value;
+}
+
+struct one_int_one_float_one_int
+{
+ int one_field;
+ float second_field;
+ int third_field;
+};
+
+struct one_int_one_float_one_int
+return_one_int_one_float_one_int (struct one_int_one_float_one_int value)
+{
+ return value;
+}
+
+struct one_float_one_int_one_float
+{
+ float one_field;
+ int second_field;
+ float third_field;
+};
+
+struct one_float_one_int_one_float
+return_one_float_one_int_one_float (struct one_float_one_int_one_float value)
+{
+ return value;
+}
+
+struct one_double_two_float
+{
+ double one_field;
+ float second_field;
+ float third_field;
+};
+
+struct one_double_two_float
+return_one_double_two_float (struct one_double_two_float value)
+{
+ return value;
+}
+
+struct two_double
+{
+ double first_field;
+ double second_field;
+};
+
+struct two_double
+return_two_double (struct two_double value)
+{
+ return value;
+}
+
+struct two_float
+{
+ float first_field;
+ float second_field;
+};
+
+struct two_float
+return_two_float (struct two_float value)
+{
+ return value;
+}
+
+struct one_int_one_double_packed
+{
+ int first_field;
+ double second_field;
+} __attribute__((__packed__));
+
+struct one_int_one_double_packed
+return_one_int_one_double_packed (struct one_int_one_double_packed value)
+{
+ return value;
+}
+
+struct one_int_one_long
+{
+ int first_field;
+ long second_field;
+};
+
+struct one_int_one_long
+return_one_int_one_long (struct one_int_one_long value)
+{
+ return value;
+}
+
+struct one_pointer
+{
+ char *first_field;
+};
+
+struct one_pointer
+return_one_pointer (struct one_pointer value)
+{
+ return value;
+}
+
+struct two_pointer
+{
+ char *first_field;
+ char *second_field;
+};
+
+struct two_pointer
+return_two_pointer (struct two_pointer value)
+{
+ return value;
+}
+
+struct one_float_one_pointer
+{
+ float first_field;
+ char *second_field;
+};
+
+struct one_float_one_pointer
+return_one_float_one_pointer (struct one_float_one_pointer value)
+{
+ return value;
+}
+
+struct one_int_one_pointer
+{
+ int first_field;
+ char *second_field;
+};
+
+struct one_int_one_pointer
+return_one_int_one_pointer (struct one_int_one_pointer value)
+{
+ return value;
+}
+
+typedef float vector_size_float32_8 __attribute__((__vector_size__(8)));
+typedef float vector_size_float32_16 __attribute__((__vector_size__(16)));
+typedef float vector_size_float32_32 __attribute__((__vector_size__(32)));
+
+typedef float ext_vector_size_float32_2 __attribute__((ext_vector_type(2)));
+typedef float ext_vector_size_float32_4 __attribute__((ext_vector_type(4)));
+typedef float ext_vector_size_float32_8 __attribute__((ext_vector_type(8)));
+
+vector_size_float32_8
+return_vector_size_float32_8 (vector_size_float32_8 value)
+{
+ return value;
+}
+
+vector_size_float32_16
+return_vector_size_float32_16 (vector_size_float32_16 value)
+{
+ return value;
+}
+
+vector_size_float32_32
+return_vector_size_float32_32 (vector_size_float32_32 value)
+{
+ return value;
+}
+
+ext_vector_size_float32_2
+return_ext_vector_size_float32_2 (ext_vector_size_float32_2 value)
+{
+ return value;
+}
+
+ext_vector_size_float32_4
+return_ext_vector_size_float32_4 (ext_vector_size_float32_4 value)
+{
+ return value;
+}
+
+ext_vector_size_float32_8
+return_ext_vector_size_float32_8 (ext_vector_size_float32_8 value)
+{
+ return value;
+}
+
+int
+main ()
+{
+ int first_int = 123456;
+ int second_int = 234567;
+
+ outer_sint (first_int);
+ outer_sint (second_int);
+
+ float first_float_value = 12.34;
+ float second_float_value = 23.45;
+
+ outer_float (first_float_value);
+ outer_float (second_float_value);
+
+ double double_value = -23.45;
+
+ return_double (double_value);
+
+ return_pointer(g_first_pointer);
+
+ long double long_double_value = -3456789.987654321;
+
+ return_long_double (long_double_value);
+
+ // Okay, now the structures:
+ return_one_int ((struct one_int) {10});
+ return_two_int ((struct two_int) {10, 20});
+ return_three_int ((struct three_int) {10, 20, 30});
+ return_four_int ((struct four_int) {10, 20, 30, 40});
+ return_five_int ((struct five_int) {10, 20, 30, 40, 50});
+
+ return_two_double ((struct two_double) {10.0, 20.0});
+ return_one_double_two_float ((struct one_double_two_float) {10.0, 20.0, 30.0});
+ return_one_int_one_float_one_int ((struct one_int_one_float_one_int) {10, 20.0, 30});
+
+ return_one_pointer ((struct one_pointer) {g_first_pointer});
+ return_two_pointer ((struct two_pointer) {g_first_pointer, g_second_pointer});
+ return_one_float_one_pointer ((struct one_float_one_pointer) {10.0, g_first_pointer});
+ return_one_int_one_pointer ((struct one_int_one_pointer) {10, g_first_pointer});
+ return_three_short_one_float ((struct three_short_one_float) {10, 20, 30, 40.0});
+
+ return_one_int_one_double ((struct one_int_one_double) {10, 20.0});
+ return_one_int_one_double_one_int ((struct one_int_one_double_one_int) {10, 20.0, 30});
+ return_one_short_one_double_one_short ((struct one_short_one_double_one_short) {10, 20.0, 30});
+ return_one_float_one_int_one_float ((struct one_float_one_int_one_float) {10.0, 20, 30.0});
+ return_two_float ((struct two_float) { 10.0, 20.0});
+ return_one_int_one_double_packed ((struct one_int_one_double_packed) {10, 20.0});
+ return_one_int_one_long ((struct one_int_one_long) {10, 20});
+
+ return_vector_size_float32_8 (( vector_size_float32_8 ){1.5, 2.25});
+ return_vector_size_float32_16 (( vector_size_float32_16 ){1.5, 2.25, 4.125, 8.0625});
+ return_vector_size_float32_32 (( vector_size_float32_32 ){1.5, 2.25, 4.125, 8.0625, 7.89, 8.52, 6.31, 9.12});
+
+ return_ext_vector_size_float32_2 ((ext_vector_size_float32_2){ 16.5, 32.25});
+ return_ext_vector_size_float32_4 ((ext_vector_size_float32_4){ 16.5, 32.25, 64.125, 128.0625});
+ return_ext_vector_size_float32_8 ((ext_vector_size_float32_8){ 16.5, 32.25, 64.125, 128.0625, 1.59, 3.57, 8.63, 9.12 });
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/set-data/Makefile b/packages/Python/lldbsuite/test/functionalities/set-data/Makefile
new file mode 100644
index 000000000000..9e1d63a183bc
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/set-data/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../make
+
+OBJC_SOURCES := main.m
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/functionalities/set-data/TestSetData.py b/packages/Python/lldbsuite/test/functionalities/set-data/TestSetData.py
new file mode 100644
index 000000000000..3acad5f87be0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/set-data/TestSetData.py
@@ -0,0 +1,62 @@
+"""
+Set the contents of variables and registers using raw data
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class SetDataTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipUnlessDarwin
+ def test_set_data(self):
+ """Test setting the contents of variables and registers using raw data."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ self.runCmd("br s -p First");
+ self.runCmd("br s -p Second");
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.expect("p myFoo.x", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['2'])
+
+ process = self.dbg.GetSelectedTarget().GetProcess()
+ frame = process.GetSelectedThread().GetFrameAtIndex(0)
+
+ x = frame.FindVariable("myFoo").GetChildMemberWithName("x")
+
+ my_data = lldb.SBData.CreateDataFromSInt32Array(lldb.eByteOrderLittle, 8, [4])
+ err = lldb.SBError()
+
+ self.assertTrue (x.SetData(my_data, err))
+
+ self.runCmd("continue")
+
+ self.expect("p myFoo.x", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['4'])
+
+ frame = process.GetSelectedThread().GetFrameAtIndex(0)
+
+ x = frame.FindVariable("string")
+
+ if process.GetAddressByteSize() == 8:
+ my_data = lldb.SBData.CreateDataFromUInt64Array(process.GetByteOrder(), 8, [0])
+ else:
+ my_data = lldb.SBData.CreateDataFromUInt32Array(process.GetByteOrder(), 4, [0])
+
+ err = lldb.SBError()
+
+ self.assertTrue (x.SetData(my_data, err))
+
+ self.expect("fr var -d run-target string", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['NSString *', 'nil'])
diff --git a/packages/Python/lldbsuite/test/functionalities/set-data/main.m b/packages/Python/lldbsuite/test/functionalities/set-data/main.m
new file mode 100644
index 000000000000..e1e69dc55715
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/set-data/main.m
@@ -0,0 +1,19 @@
+#import <Foundation/Foundation.h>
+
+int main ()
+{
+ @autoreleasepool
+ {
+ struct foo {
+ int x;
+ int y;
+ } myFoo;
+
+ myFoo.x = 2;
+ myFoo.y = 3; // First breakpoint
+
+ NSString *string = [NSString stringWithFormat:@"%s", "Hello world!"];
+
+ NSLog(@"%d %@", myFoo.x, string); // Second breakpoint
+ }
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/signal/Makefile b/packages/Python/lldbsuite/test/functionalities/signal/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/signal/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/signal/TestSendSignal.py b/packages/Python/lldbsuite/test/functionalities/signal/TestSendSignal.py
new file mode 100644
index 000000000000..971b82a7c75d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/signal/TestSendSignal.py
@@ -0,0 +1,105 @@
+"""Test that lldb command 'process signal SIGUSR1' to send a signal to the inferior works."""
+
+from __future__ import print_function
+
+
+
+import os, time, signal
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+
+class SendSignalTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.c', 'Put breakpoint here')
+
+ @expectedFailureFreeBSD("llvm.org/pr23318: does not report running state")
+ @skipIfWindows # Windows does not support signals
+ def test_with_run_command(self):
+ """Test that lldb command 'process signal SIGUSR1' sends a signal to the inferior process."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create a breakpoint on main.c by name 'c'.
+ breakpoint = target.BreakpointCreateByLocation('main.c', self.line)
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Get the breakpoint location from breakpoint after we verified that,
+ # indeed, it has one location.
+ location = breakpoint.GetLocationAtIndex(0)
+ self.assertTrue(location and
+ location.IsEnabled(),
+ VALID_BREAKPOINT_LOCATION)
+
+ # Now launch the process, no arguments & do not stop at entry point.
+ launch_info = lldb.SBLaunchInfo([exe])
+ launch_info.SetWorkingDirectory(self.get_process_working_directory())
+
+ process_listener = lldb.SBListener("signal_test_listener")
+ launch_info.SetListener(process_listener)
+ error = lldb.SBError()
+ process = target.Launch(launch_info, error)
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ self.runCmd("process handle -n False -p True -s True SIGUSR1")
+
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "We hit the first breakpoint.")
+
+ # After resuming the process, send it a SIGUSR1 signal.
+
+ self.setAsync(True)
+
+ self.assertTrue(process_listener.IsValid(), "Got a good process listener")
+
+ # Disable our breakpoint, we don't want to hit it anymore...
+ breakpoint.SetEnabled(False)
+
+ # Now continue:
+ process.Continue()
+
+ # If running remote test, there should be a connected event
+ if lldb.remote_platform:
+ self.match_state(process_listener, lldb.eStateConnected)
+
+ self.match_state(process_listener, lldb.eStateRunning)
+
+ # Now signal the process, and make sure it stops:
+ process.Signal(lldbutil.get_signal_number('SIGUSR1'))
+
+ self.match_state(process_listener, lldb.eStateStopped)
+
+ # Now make sure the thread was stopped with a SIGUSR1:
+ threads = lldbutil.get_stopped_threads(process, lldb.eStopReasonSignal)
+ self.assertTrue(len(threads) == 1, "One thread stopped for a signal.")
+ thread = threads[0]
+
+ self.assertTrue(thread.GetStopReasonDataCount() >= 1, "There was data in the event.")
+ self.assertTrue(thread.GetStopReasonDataAtIndex(0) == lldbutil.get_signal_number('SIGUSR1'),
+ "The stop signal was SIGUSR1")
+
+ def match_state(self, process_listener, expected_state):
+ num_seconds = 5
+ broadcaster = self.process().GetBroadcaster()
+ event_type_mask = lldb.SBProcess.eBroadcastBitStateChanged
+ event = lldb.SBEvent()
+ got_event = process_listener.WaitForEventForBroadcasterWithType(
+ num_seconds, broadcaster, event_type_mask, event)
+ self.assertTrue(got_event, "Got an event")
+ state = lldb.SBProcess.GetStateFromEvent(event)
+ self.assertTrue(state == expected_state,
+ "It was the %s state." %
+ lldb.SBDebugger_StateAsCString(expected_state))
diff --git a/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/Makefile b/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/TestHandleSegv.py b/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/TestHandleSegv.py
new file mode 100644
index 000000000000..feed5bfb3c76
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/TestHandleSegv.py
@@ -0,0 +1,43 @@
+"""Test that we can debug inferiors that handle SIGSEGV by themselves"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+import re
+
+
+class HandleSegvTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfWindows # signals do not exist on Windows
+ @skipIfDarwin
+ @expectedFailureFreeBSD("llvm.org/pr23699 SIGSEGV is reported as exception, not signal")
+ def test_inferior_handle_sigsegv(self):
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # launch
+ process = target.LaunchSimple(None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+ self.assertEqual(process.GetState(), lldb.eStateStopped)
+ signo = process.GetUnixSignals().GetSignalNumberFromName("SIGSEGV")
+
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonSignal)
+ self.assertTrue(thread and thread.IsValid(), "Thread should be stopped due to a signal")
+ self.assertTrue(thread.GetStopReasonDataCount() >= 1, "There was data in the event.")
+ self.assertEqual(thread.GetStopReasonDataAtIndex(0), signo, "The stop signal was SIGSEGV")
+
+ # Continue until we exit.
+ process.Continue()
+ self.assertEqual(process.GetState(), lldb.eStateExited)
+ self.assertEqual(process.GetExitStatus(), 0)
diff --git a/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/main.c b/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/main.c
new file mode 100644
index 000000000000..27d9b8e500ab
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/signal/handle-segv/main.c
@@ -0,0 +1,58 @@
+#include <sys/mman.h>
+#include <signal.h>
+#include <stdio.h>
+#include <unistd.h>
+
+enum {
+ kMmapSize = 0x1000,
+ kMagicValue = 47,
+};
+
+void *address;
+volatile sig_atomic_t signaled = 0;
+
+void handler(int sig)
+{
+ signaled = 1;
+ if (munmap(address, kMmapSize) != 0)
+ {
+ perror("munmap");
+ _exit(5);
+ }
+
+ void* newaddr = mmap(address, kMmapSize, PROT_READ | PROT_WRITE,
+ MAP_ANON | MAP_FIXED | MAP_PRIVATE, -1, 0);
+ if (newaddr != address)
+ {
+ fprintf(stderr, "Newly mmaped address (%p) does not equal old address (%p).\n",
+ newaddr, address);
+ _exit(6);
+ }
+ *(int*)newaddr = kMagicValue;
+}
+
+int main()
+{
+ if (signal(SIGSEGV, handler) == SIG_ERR)
+ {
+ perror("signal");
+ return 1;
+ }
+
+ address = mmap(NULL, kMmapSize, PROT_NONE, MAP_ANON | MAP_PRIVATE, -1, 0);
+ if (address == MAP_FAILED)
+ {
+ perror("mmap");
+ return 2;
+ }
+
+ // This should first trigger a segfault. Our handler will make the memory readable and write
+ // the magic value into memory.
+ if (*(int*)address != kMagicValue)
+ return 3;
+
+ if (! signaled)
+ return 4;
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/signal/main.c b/packages/Python/lldbsuite/test/functionalities/signal/main.c
new file mode 100644
index 000000000000..77e760503410
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/signal/main.c
@@ -0,0 +1,27 @@
+#include <signal.h>
+#include <stdio.h>
+#include <unistd.h>
+
+void handler_usr1 (int i)
+{
+ puts ("got signal usr1");
+}
+
+void handler_alrm (int i)
+{
+ puts ("got signal ALRM");
+}
+
+int main ()
+{
+ int i = 0;
+
+ signal (SIGUSR1, handler_usr1);
+ signal (SIGALRM, handler_alrm);
+
+ puts ("Put breakpoint here");
+
+ while (i++ < 20)
+ sleep (1);
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/signal/raise/Makefile b/packages/Python/lldbsuite/test/functionalities/signal/raise/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/signal/raise/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/signal/raise/TestRaise.py b/packages/Python/lldbsuite/test/functionalities/signal/raise/TestRaise.py
new file mode 100644
index 000000000000..39e7753397d1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/signal/raise/TestRaise.py
@@ -0,0 +1,221 @@
+"""Test that we handle inferiors that send signals to themselves"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+import re
+
+
+@skipIfWindows # signals do not exist on Windows
+class RaiseTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test_sigstop(self):
+ self.build()
+ self.signal_test('SIGSTOP', False)
+ # passing of SIGSTOP is not correctly handled, so not testing that scenario: https://llvm.org/bugs/show_bug.cgi?id=23574
+
+ @skipIfDarwin # darwin does not support real time signals
+ @skipIfTargetAndroid()
+ def test_sigsigrtmin(self):
+ self.build()
+ self.signal_test('SIGRTMIN', True)
+
+ def launch(self, target, signal):
+ # launch the process, do not stop at entry point.
+ process = target.LaunchSimple([signal], None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+ self.assertEqual(process.GetState(), lldb.eStateStopped)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "Thread should be stopped due to a breakpoint")
+ return process
+
+ def set_handle(self, signal, pass_signal, stop_at_signal, notify_signal):
+ return_obj = lldb.SBCommandReturnObject()
+ self.dbg.GetCommandInterpreter().HandleCommand(
+ "process handle %s -p %s -s %s -n %s" % (signal, pass_signal, stop_at_signal, notify_signal),
+ return_obj)
+ self.assertTrue (return_obj.Succeeded() == True, "Setting signal handling failed")
+
+
+ def signal_test(self, signal, test_passing):
+ """Test that we handle inferior raising signals"""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+ lldbutil.run_break_set_by_symbol(self, "main")
+
+ # launch
+ process = self.launch(target, signal)
+ signo = process.GetUnixSignals().GetSignalNumberFromName(signal)
+
+ # retrieve default signal disposition
+ return_obj = lldb.SBCommandReturnObject()
+ self.dbg.GetCommandInterpreter().HandleCommand("process handle %s " % signal, return_obj)
+ match = re.match('NAME *PASS *STOP *NOTIFY.*(false|true) *(false|true) *(false|true)',
+ return_obj.GetOutput(), re.IGNORECASE | re.DOTALL)
+ if not match:
+ self.fail('Unable to retrieve default signal disposition.')
+ default_pass = match.group(1)
+ default_stop = match.group(2)
+ default_notify = match.group(3)
+
+ # Make sure we stop at the signal
+ self.set_handle(signal, "false", "true", "true")
+ process.Continue()
+ self.assertEqual(process.GetState(), lldb.eStateStopped)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonSignal)
+ self.assertTrue(thread.IsValid(), "Thread should be stopped due to a signal")
+ self.assertTrue(thread.GetStopReasonDataCount() >= 1, "There was data in the event.")
+ self.assertEqual(thread.GetStopReasonDataAtIndex(0), signo,
+ "The stop signal was %s" % signal)
+
+ # Continue until we exit.
+ process.Continue()
+ self.assertEqual(process.GetState(), lldb.eStateExited)
+ self.assertEqual(process.GetExitStatus(), 0)
+
+ # launch again
+ process = self.launch(target, signal)
+
+ # Make sure we do not stop at the signal. We should still get the notification.
+ self.set_handle(signal, "false", "false", "true")
+ self.expect("process continue", substrs=["stopped and restarted", signal])
+ self.assertEqual(process.GetState(), lldb.eStateExited)
+ self.assertEqual(process.GetExitStatus(), 0)
+
+ # launch again
+ process = self.launch(target, signal)
+
+ # Make sure we do not stop at the signal, and we do not get the notification.
+ self.set_handle(signal, "false", "false", "false")
+ self.expect("process continue", substrs=["stopped and restarted"], matching=False)
+ self.assertEqual(process.GetState(), lldb.eStateExited)
+ self.assertEqual(process.GetExitStatus(), 0)
+
+ if not test_passing:
+ # reset signal handling to default
+ self.set_handle(signal, default_pass, default_stop, default_notify)
+ return
+
+ # launch again
+ process = self.launch(target, signal)
+
+ # Make sure we stop at the signal
+ self.set_handle(signal, "true", "true", "true")
+ process.Continue()
+ self.assertEqual(process.GetState(), lldb.eStateStopped)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonSignal)
+ self.assertTrue(thread.IsValid(), "Thread should be stopped due to a signal")
+ self.assertTrue(thread.GetStopReasonDataCount() >= 1, "There was data in the event.")
+ self.assertEqual(thread.GetStopReasonDataAtIndex(0),
+ process.GetUnixSignals().GetSignalNumberFromName(signal),
+ "The stop signal was %s" % signal)
+
+ # Continue until we exit. The process should receive the signal.
+ process.Continue()
+ self.assertEqual(process.GetState(), lldb.eStateExited)
+ self.assertEqual(process.GetExitStatus(), signo)
+
+ # launch again
+ process = self.launch(target, signal)
+
+ # Make sure we do not stop at the signal. We should still get the notification. Process
+ # should receive the signal.
+ self.set_handle(signal, "true", "false", "true")
+ self.expect("process continue", substrs=["stopped and restarted", signal])
+ self.assertEqual(process.GetState(), lldb.eStateExited)
+ self.assertEqual(process.GetExitStatus(), signo)
+
+ # launch again
+ process = self.launch(target, signal)
+
+ # Make sure we do not stop at the signal, and we do not get the notification. Process
+ # should receive the signal.
+ self.set_handle(signal, "true", "false", "false")
+ self.expect("process continue", substrs=["stopped and restarted"], matching=False)
+ self.assertEqual(process.GetState(), lldb.eStateExited)
+ self.assertEqual(process.GetExitStatus(), signo)
+
+ # reset signal handling to default
+ self.set_handle(signal, default_pass, default_stop, default_notify)
+
+ @expectedFailureLinux("llvm.org/pr24530") # the signal the inferior generates gets lost
+ @expectedFailureDarwin("llvm.org/pr24530") # the signal the inferior generates gets lost
+ def test_restart_bug(self):
+ """Test that we catch a signal in the edge case where the process receives it while we are
+ about to interrupt it"""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+ bkpt = target.BreakpointCreateByName("main")
+ self.assertTrue(bkpt.IsValid(), VALID_BREAKPOINT)
+
+ # launch the inferior and don't wait for it to stop
+ self.dbg.SetAsync(True)
+ error = lldb.SBError()
+ listener = lldb.SBListener("my listener")
+ process = target.Launch (listener,
+ ["SIGSTOP"], # argv
+ None, # envp
+ None, # stdin_path
+ None, # stdout_path
+ None, # stderr_path
+ None, # working directory
+ 0, # launch flags
+ False, # Stop at entry
+ error) # error
+
+ self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID)
+
+ event = lldb.SBEvent()
+
+ # Give the child enough time to reach the breakpoint,
+ # while clearing out all the pending events.
+ # The last WaitForEvent call will time out after 2 seconds.
+ while listener.WaitForEvent(2, event):
+ if self.TraceOn():
+ print("Process changing state to:", self.dbg.StateAsCString(process.GetStateFromEvent(event)))
+
+ # now the process should be stopped
+ self.assertEqual(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED)
+ self.assertEqual(len(lldbutil.get_threads_stopped_at_breakpoint(process, bkpt)), 1,
+ "A thread should be stopped at breakpoint")
+
+ # Remove all breakpoints. This makes sure we don't have to single-step over them when we
+ # resume the process below
+ target.DeleteAllBreakpoints()
+
+ # resume the process and immediately try to set another breakpoint. When using the remote
+ # stub, this will trigger a request to stop the process just as it is about to stop
+ # naturally due to a SIGSTOP signal it raises. Make sure we do not lose this signal.
+ process.Continue()
+ self.assertTrue(target.BreakpointCreateByName("handler").IsValid(), VALID_BREAKPOINT)
+
+ # Clear the events again
+ while listener.WaitForEvent(2, event):
+ if self.TraceOn():
+ print("Process changing state to:", self.dbg.StateAsCString(process.GetStateFromEvent(event)))
+
+ # The process should be stopped due to a signal
+ self.assertEqual(process.GetState(), lldb.eStateStopped)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonSignal)
+ self.assertTrue(thread.IsValid(), "Thread should be stopped due to a signal")
+ self.assertTrue(thread.GetStopReasonDataCount() >= 1, "There was data in the event.")
+ signo = process.GetUnixSignals().GetSignalNumberFromName("SIGSTOP")
+ self.assertEqual(thread.GetStopReasonDataAtIndex(0), signo,
+ "The stop signal was %s" % signal)
+
+ # We are done
+ process.Kill()
diff --git a/packages/Python/lldbsuite/test/functionalities/signal/raise/main.c b/packages/Python/lldbsuite/test/functionalities/signal/raise/main.c
new file mode 100644
index 000000000000..8827174e758e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/signal/raise/main.c
@@ -0,0 +1,42 @@
+#include <signal.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+void handler(int signo)
+{
+ _exit(signo);
+}
+
+int main (int argc, char *argv[])
+{
+#ifndef __APPLE__
+ // Real time signals not supported on apple platforms.
+ if (signal(SIGRTMIN, handler) == SIG_ERR)
+ {
+ perror("signal(SIGRTMIN)");
+ return 1;
+ }
+#endif
+
+ if (argc < 2)
+ {
+ puts("Please specify a signal to raise");
+ return 1;
+ }
+
+ if (strcmp(argv[1], "SIGSTOP") == 0)
+ raise(SIGSTOP);
+#ifndef __APPLE__
+ else if (strcmp(argv[1], "SIGRTMIN") == 0)
+ raise(SIGRTMIN);
+#endif
+ else
+ {
+ printf("Unknown signal: %s\n", argv[1]);
+ return 1;
+ }
+
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/single-quote-in-filename-to-lldb/Makefile b/packages/Python/lldbsuite/test/functionalities/single-quote-in-filename-to-lldb/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/single-quote-in-filename-to-lldb/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/single-quote-in-filename-to-lldb/TestSingleQuoteInFilename.py b/packages/Python/lldbsuite/test/functionalities/single-quote-in-filename-to-lldb/TestSingleQuoteInFilename.py
new file mode 100644
index 000000000000..6a2dd74d3956
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/single-quote-in-filename-to-lldb/TestSingleQuoteInFilename.py
@@ -0,0 +1,71 @@
+"""
+Test the lldb command line takes a filename with single quote chars.
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class SingleQuoteInCommandLineTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+ myexe = "path with '09/a.out"
+
+ @classmethod
+ def classCleanup(cls):
+ """Cleanup the test byproducts."""
+ try:
+ os.remove("child_send.txt")
+ os.remove("child_read.txt")
+ os.remove(cls.myexe)
+ except:
+ pass
+
+ @expectedFailureHostWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ @no_debug_info_test
+ def test_lldb_invocation_with_single_quote_in_filename(self):
+ """Test that 'lldb my_file_name' works where my_file_name is a string with a single quote char in it."""
+ import pexpect
+ self.buildDefault()
+ system([["cp", "a.out", "\"%s\"" % self.myexe]])
+
+ # The default lldb prompt.
+ prompt = "(lldb) "
+
+ # So that the child gets torn down after the test.
+ self.child = pexpect.spawn('%s %s "%s"' % (lldbtest_config.lldbExec, self.lldbOption, self.myexe))
+ child = self.child
+ child.setecho(True)
+ # Turn on logging for input/output to/from the child.
+ with open('child_send.txt', 'w') as f_send:
+ with open('child_read.txt', 'w') as f_read:
+ child.logfile_send = f_send
+ child.logfile_read = f_read
+
+ child.expect_exact(prompt)
+
+ child.send("help watchpoint")
+ child.sendline('')
+ child.expect_exact(prompt)
+
+ # Now that the necessary logging is done, restore logfile to None to
+ # stop further logging.
+ child.logfile_send = None
+ child.logfile_read = None
+
+ with open('child_send.txt', 'r') as fs:
+ if self.TraceOn():
+ print("\n\nContents of child_send.txt:")
+ print(fs.read())
+ with open('child_read.txt', 'r') as fr:
+ from_child = fr.read()
+ if self.TraceOn():
+ print("\n\nContents of child_read.txt:")
+ print(from_child)
+
+ self.expect(from_child, exe=False,
+ substrs = ["Current executable set to"])
diff --git a/packages/Python/lldbsuite/test/functionalities/single-quote-in-filename-to-lldb/main.c b/packages/Python/lldbsuite/test/functionalities/single-quote-in-filename-to-lldb/main.c
new file mode 100644
index 000000000000..7cee7306547a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/single-quote-in-filename-to-lldb/main.c
@@ -0,0 +1,7 @@
+#include <stdio.h>
+
+int main(int argc, const char *argv[])
+{
+ printf("Hello, world!\n");
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/single-quote-in-filename-to-lldb/path with '09/.keep b/packages/Python/lldbsuite/test/functionalities/single-quote-in-filename-to-lldb/path with '09/.keep
new file mode 100644
index 000000000000..e69de29bb2d1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/single-quote-in-filename-to-lldb/path with '09/.keep
diff --git a/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/Makefile b/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/Makefile
new file mode 100644
index 000000000000..45b69a5bb6eb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../make
+
+C_SOURCES := with-debug.c without-debug.c
+
+include $(LEVEL)/Makefile.rules
+
+without-debug.o: without-debug.c
+ $(CC) $(CFLAGS_NO_DEBUG) -c without-debug.c
diff --git a/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/TestStepNoDebug.py b/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/TestStepNoDebug.py
new file mode 100644
index 000000000000..6c1f2c3da41b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/TestStepNoDebug.py
@@ -0,0 +1,113 @@
+"""
+Test thread step-in, step-over and step-out work with the "Avoid no debug" option.
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+import sys
+from lldbsuite.test.lldbtest import *
+
+class ReturnValueTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @add_test_categories(['pyapi'])
+ def test_step_out_with_python(self):
+ """Test stepping out using avoid-no-debug with dsyms."""
+ self.build()
+ self.get_to_starting_point()
+ self.do_step_out_past_nodebug()
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureGcc("llvm.org/pr19247")
+ def test_step_over_with_python(self):
+ """Test stepping over using avoid-no-debug with dwarf."""
+ self.build()
+ self.get_to_starting_point()
+ self.do_step_over_past_nodebug()
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureGcc("llvm.org/pr19247")
+ def test_step_in_with_python(self):
+ """Test stepping in using avoid-no-debug with dwarf."""
+ self.build()
+ self.get_to_starting_point()
+ self.do_step_in_past_nodebug()
+
+ def setUp (self):
+ TestBase.setUp(self)
+ self.main_source = "with-debug.c"
+ self.main_source_spec = lldb.SBFileSpec("with-debug.c")
+ self.dbg.HandleCommand ("settings set target.process.thread.step-out-avoid-nodebug true")
+
+ def tearDown (self):
+ self.dbg.HandleCommand ("settings set target.process.thread.step-out-avoid-nodebug false")
+ TestBase.tearDown(self)
+
+ def hit_correct_line (self, pattern):
+ target_line = line_number (self.main_source, pattern)
+ self.assertTrue (target_line != 0, "Could not find source pattern " + pattern)
+ cur_line = self.thread.frames[0].GetLineEntry().GetLine()
+ self.assertTrue (cur_line == target_line, "Stepped to line %d instead of expected %d with pattern '%s'."%(cur_line, target_line, pattern))
+
+ def hit_correct_function (self, pattern):
+ name = self.thread.frames[0].GetFunctionName()
+ self.assertTrue (pattern in name, "Got to '%s' not the expected function '%s'."%(name, pattern))
+
+ def get_to_starting_point (self):
+ exe = os.path.join(os.getcwd(), "a.out")
+ error = lldb.SBError()
+
+ self.target = self.dbg.CreateTarget(exe)
+ self.assertTrue(self.target, VALID_TARGET)
+
+ inner_bkpt = self.target.BreakpointCreateBySourceRegex("Stop here and step out of me", self.main_source_spec)
+ self.assertTrue(inner_bkpt, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ self.process = self.target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(self.process, PROCESS_IS_VALID)
+
+ # Now finish, and make sure the return value is correct.
+ threads = lldbutil.get_threads_stopped_at_breakpoint (self.process, inner_bkpt)
+ self.assertTrue(len(threads) == 1, "Stopped at inner breakpoint.")
+ self.thread = threads[0]
+
+ def do_step_out_past_nodebug(self):
+ # The first step out takes us to the called_from_nodebug frame, just to make sure setting
+ # step-out-avoid-nodebug doesn't change the behavior in frames with debug info.
+ self.thread.StepOut()
+ self.hit_correct_line ("intermediate_return_value = called_from_nodebug_actual(some_value)")
+ self.thread.StepOut()
+ self.hit_correct_line ("int return_value = no_debug_caller(5, called_from_nodebug)")
+
+ def do_step_over_past_nodebug (self):
+ self.thread.StepOver()
+ self.hit_correct_line ("intermediate_return_value = called_from_nodebug_actual(some_value)")
+ self.thread.StepOver()
+ self.hit_correct_line ("return intermediate_return_value")
+ self.thread.StepOver()
+ # Note, lldb doesn't follow gdb's distinction between "step-out" and "step-over/step-in"
+ # when exiting a frame. In all cases we leave the pc at the point where we exited the
+ # frame. In gdb, step-over/step-in move to the end of the line they stepped out to.
+ # If we ever change this we will need to fix this test.
+ self.hit_correct_line ("int return_value = no_debug_caller(5, called_from_nodebug)")
+
+ def do_step_in_past_nodebug (self):
+ self.thread.StepInto()
+ self.hit_correct_line ("intermediate_return_value = called_from_nodebug_actual(some_value)")
+ self.thread.StepInto()
+ self.hit_correct_line ("return intermediate_return_value")
+ self.thread.StepInto()
+ # Note, lldb doesn't follow gdb's distinction between "step-out" and "step-over/step-in"
+ # when exiting a frame. In all cases we leave the pc at the point where we exited the
+ # frame. In gdb, step-over/step-in move to the end of the line they stepped out to.
+ # If we ever change this we will need to fix this test.
+ self.hit_correct_line ("int return_value = no_debug_caller(5, called_from_nodebug)")
diff --git a/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/with-debug.c b/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/with-debug.c
new file mode 100644
index 000000000000..c7ac309d2c1a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/with-debug.c
@@ -0,0 +1,29 @@
+#include <stdio.h>
+
+typedef int (*debug_callee) (int);
+
+extern int no_debug_caller (int, debug_callee);
+
+int
+called_from_nodebug_actual(int some_value)
+{
+ int return_value = 0;
+ return_value = printf ("Length: %d.\n", some_value);
+ return return_value; // Stop here and step out of me
+}
+
+int
+called_from_nodebug(int some_value)
+{
+ int intermediate_return_value = 0;
+ intermediate_return_value = called_from_nodebug_actual(some_value);
+ return intermediate_return_value;
+}
+
+int
+main()
+{
+ int return_value = no_debug_caller(5, called_from_nodebug);
+ printf ("I got: %d.\n", return_value);
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/without-debug.c b/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/without-debug.c
new file mode 100644
index 000000000000..d71d74af5e90
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/step-avoids-no-debug/without-debug.c
@@ -0,0 +1,17 @@
+typedef int (*debug_callee) (int);
+
+int
+no_debug_caller_intermediate(int input, debug_callee callee)
+{
+ int return_value = 0;
+ return_value = callee(input);
+ return return_value;
+}
+
+int
+no_debug_caller (int input, debug_callee callee)
+{
+ int return_value = 0;
+ return_value = no_debug_caller_intermediate (input, callee);
+ return return_value;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/stop-hook/Makefile b/packages/Python/lldbsuite/test/functionalities/stop-hook/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/stop-hook/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/stop-hook/TestStopHookCmd.py b/packages/Python/lldbsuite/test/functionalities/stop-hook/TestStopHookCmd.py
new file mode 100644
index 000000000000..753491339c4c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/stop-hook/TestStopHookCmd.py
@@ -0,0 +1,65 @@
+"""
+Test lldb target stop-hook command.
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class StopHookCmdTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers inside main.cpp.
+ self.begl = line_number('main.cpp', '// Set breakpoint here to test target stop-hook.')
+ self.endl = line_number('main.cpp', '// End of the line range for which stop-hook is to be run.')
+ self.line = line_number('main.cpp', '// Another breakpoint which is outside of the stop-hook range.')
+
+ @no_debug_info_test
+ def test_not_crashing_if_no_target(self):
+ """target stop-hook list should not crash if no target has been set."""
+ self.runCmd("target stop-hook list", check=False)
+
+ def test(self):
+ """Test a sequence of target stop-hook commands."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.begl, num_expected_locations=1, loc_exact=True)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("target stop-hook add -f main.cpp -l %d -e %d -o 'expr ptr'" % (self.begl, self.endl))
+
+ self.expect('target stop-hook list', 'Stop Hook added successfully',
+ substrs = ['State: enabled',
+ 'expr ptr'])
+
+ self.runCmd('target stop-hook disable')
+
+ self.expect('target stop-hook list', 'Stop Hook disabled successfully',
+ substrs = ['State: disabled',
+ 'expr ptr'])
+
+ self.runCmd('target stop-hook enable')
+
+ self.expect('target stop-hook list', 'Stop Hook enabled successfully',
+ substrs = ['State: enabled',
+ 'expr ptr'])
+
+ self.runCmd("settings set auto-confirm true")
+ self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm"))
+
+ self.runCmd('target stop-hook delete')
+
+ self.expect('target stop-hook list', 'Stop Hook deleted successfully',
+ substrs = ['No stop hooks.'])
diff --git a/packages/Python/lldbsuite/test/functionalities/stop-hook/TestStopHookMechanism.py b/packages/Python/lldbsuite/test/functionalities/stop-hook/TestStopHookMechanism.py
new file mode 100644
index 000000000000..7785d85772e2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/stop-hook/TestStopHookMechanism.py
@@ -0,0 +1,101 @@
+"""
+Test lldb target stop-hook mechanism to see whether it fires off correctly .
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test import configuration
+from lldbsuite.test.lldbtest import *
+
+class StopHookMechanismTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers inside main.cpp.
+ self.begl = line_number('main.cpp', '// Set breakpoint here to test target stop-hook.')
+ self.endl = line_number('main.cpp', '// End of the line range for which stop-hook is to be run.')
+ self.correct_step_line = line_number ('main.cpp', '// We should stop here after stepping.')
+ self.line = line_number('main.cpp', '// Another breakpoint which is outside of the stop-hook range.')
+
+ @skipIfFreeBSD # llvm.org/pr15037
+ @expectedFlakeyLinux('llvm.org/pr15037') # stop-hooks sometimes fail to fire on Linux
+ @expectedFailureHostWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ def test(self):
+ """Test the stop-hook mechanism."""
+ self.build()
+
+ import pexpect
+ exe = os.path.join(os.getcwd(), "a.out")
+ prompt = "(lldb) "
+ add_prompt = "Enter your stop hook command(s). Type 'DONE' to end."
+ add_prompt1 = "> "
+
+ # So that the child gets torn down after the test.
+ self.child = pexpect.spawn('%s %s' % (lldbtest_config.lldbExec, self.lldbOption))
+ child = self.child
+ # Turn on logging for what the child sends back.
+ if self.TraceOn():
+ child.logfile_read = sys.stdout
+
+ if lldb.remote_platform:
+ child.expect_exact(prompt)
+ child.sendline('platform select %s' % lldb.remote_platform.GetName())
+ child.expect_exact(prompt)
+ child.sendline('platform connect %s' % configuration.lldb_platform_url)
+ child.expect_exact(prompt)
+ child.sendline('platform settings -w %s' % configuration.lldb_platform_working_dir)
+
+ child.expect_exact(prompt)
+ child.sendline('target create %s' % exe)
+
+ # Set the breakpoint, followed by the target stop-hook commands.
+ child.expect_exact(prompt)
+ child.sendline('breakpoint set -f main.cpp -l %d' % self.begl)
+ child.expect_exact(prompt)
+ child.sendline('breakpoint set -f main.cpp -l %d' % self.line)
+ child.expect_exact(prompt)
+ child.sendline('target stop-hook add -f main.cpp -l %d -e %d' % (self.begl, self.endl))
+ child.expect_exact(add_prompt)
+ child.expect_exact(add_prompt1)
+ child.sendline('expr ptr')
+ child.expect_exact(add_prompt1)
+ child.sendline('DONE')
+ child.expect_exact(prompt)
+ child.sendline('target stop-hook list')
+
+ # Now run the program, expect to stop at the first breakpoint which is within the stop-hook range.
+ child.expect_exact(prompt)
+ child.sendline('run')
+ # Make sure we see the stop hook text from the stop of the process from the run hitting the first breakpoint
+ child.expect_exact('(void *) $')
+ child.expect_exact(prompt)
+ child.sendline('thread step-over')
+ # Expecting to find the output emitted by the firing of our stop hook.
+ child.expect_exact('(void *) $')
+ # This is orthogonal to the main stop hook test, but this example shows a bug in
+ # CLANG where the line table entry for the "return -1" actually includes some code
+ # from the other branch of the if/else, so we incorrectly stop at the "return -1" line.
+ # I fixed that in lldb and I'm sticking in a test here because I don't want to have to
+ # make up a whole nother test case for it.
+ child.sendline('frame info')
+ at_line = 'at main.cpp:%d' % (self.correct_step_line)
+ print('expecting "%s"' % at_line)
+ child.expect_exact(at_line)
+
+ # Now continue the inferior, we'll stop at another breakpoint which is outside the stop-hook range.
+ child.sendline('process continue')
+ child.expect_exact('// Another breakpoint which is outside of the stop-hook range.')
+ #self.DebugPExpect(child)
+ child.sendline('thread step-over')
+ child.expect_exact('// Another breakpoint which is outside of the stop-hook range.')
+ #self.DebugPExpect(child)
+ # Verify that the 'Stop Hooks' mechanism is NOT BEING fired off.
+ self.expect(child.before, exe=False, matching=False,
+ substrs = ['(void *) $'])
diff --git a/packages/Python/lldbsuite/test/functionalities/stop-hook/main.cpp b/packages/Python/lldbsuite/test/functionalities/stop-hook/main.cpp
new file mode 100644
index 000000000000..c10c1e5ef0d2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/stop-hook/main.cpp
@@ -0,0 +1,54 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+#include <stdlib.h>
+
+int a(int);
+int b(int);
+int c(int);
+
+int a(int val)
+{
+ if (val <= 1)
+ return b(val);
+ else if (val >= 3)
+ return c(val);
+
+ return val;
+}
+
+int b(int val)
+{
+ int rc = c(val);
+ void *ptr = malloc(1024);
+ if (!ptr) // Set breakpoint here to test target stop-hook.
+ return -1;
+ else
+ printf("ptr=%p\n", ptr); // We should stop here after stepping.
+ return rc; // End of the line range for which stop-hook is to be run.
+}
+
+int c(int val)
+{
+ return val + 3;
+}
+
+int main (int argc, char const *argv[])
+{
+ int A1 = a(1);
+ printf("a(1) returns %d\n", A1);
+
+ int C2 = c(2); // Another breakpoint which is outside of the stop-hook range.
+ printf("c(2) returns %d\n", C2);
+
+ int A3 = a(3);
+ printf("a(3) returns %d\n", A3);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/stop-hook/multiple_threads/Makefile b/packages/Python/lldbsuite/test/functionalities/stop-hook/multiple_threads/Makefile
new file mode 100644
index 000000000000..035413ff763d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/stop-hook/multiple_threads/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+ENABLE_THREADS := YES
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/stop-hook/multiple_threads/TestStopHookMultipleThreads.py b/packages/Python/lldbsuite/test/functionalities/stop-hook/multiple_threads/TestStopHookMultipleThreads.py
new file mode 100644
index 000000000000..c7fb53d495e6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/stop-hook/multiple_threads/TestStopHookMultipleThreads.py
@@ -0,0 +1,77 @@
+"""
+Test that lldb stop-hook works for multiple threads.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test import configuration
+from lldbsuite.test.lldbtest import *
+
+class StopHookForMultipleThreadsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Our simple source filename.
+ self.source = 'main.cpp'
+ # Find the line number to break inside main().
+ self.first_stop = line_number(self.source, '// Set break point at this line, and add a stop-hook.')
+ self.thread_function = line_number(self.source, '// Break here to test that the stop-hook mechanism works for multiple threads.')
+ # Build dictionary to have unique executable names for each test method.
+ self.exe_name = self.testMethodName
+ self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name}
+
+ @expectedFlakeyFreeBSD("llvm.org/pr15037")
+ @expectedFlakeyLinux("llvm.org/pr15037") # stop hooks sometimes fail to fire on Linux
+ @expectedFailureHostWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ def test_stop_hook_multiple_threads(self):
+ """Test that lldb stop-hook works for multiple threads."""
+ self.build(dictionary=self.d)
+ self.setTearDownCleanup(dictionary=self.d)
+
+ import pexpect
+ exe = os.path.join(os.getcwd(), self.exe_name)
+ prompt = "(lldb) "
+
+ # So that the child gets torn down after the test.
+ self.child = pexpect.spawn('%s %s' % (lldbtest_config.lldbExec, self.lldbOption))
+ child = self.child
+ # Turn on logging for what the child sends back.
+ if self.TraceOn():
+ child.logfile_read = sys.stdout
+
+ if lldb.remote_platform:
+ child.expect_exact(prompt)
+ child.sendline('platform select %s' % lldb.remote_platform.GetName())
+ child.expect_exact(prompt)
+ child.sendline('platform connect %s' % configuration.lldb_platform_url)
+ child.expect_exact(prompt)
+ child.sendline('platform settings -w %s' % configuration.lldb_platform_working_dir)
+
+ child.expect_exact(prompt)
+ child.sendline('target create %s' % exe)
+
+ # Set the breakpoint, followed by the target stop-hook commands.
+ child.expect_exact(prompt)
+ child.sendline('breakpoint set -f main.cpp -l %d' % self.first_stop)
+ child.expect_exact(prompt)
+ child.sendline('breakpoint set -f main.cpp -l %d' % self.thread_function)
+ child.expect_exact(prompt)
+
+ # Now run the program, expect to stop at the first breakpoint which is within the stop-hook range.
+ child.sendline('run')
+ child.expect_exact("Process") # 'Process 2415 launched', 'Process 2415 stopped'
+ child.expect_exact(prompt)
+ child.sendline('target stop-hook add -o "frame variable --show-globals g_val"')
+ child.expect_exact("Stop hook") # 'Stop hook #1 added.'
+ child.expect_exact(prompt)
+
+ # Continue and expect to find the output emitted by the firing of our stop hook.
+ child.sendline('continue')
+ child.expect_exact('(uint32_t) ::g_val = ')
diff --git a/packages/Python/lldbsuite/test/functionalities/stop-hook/multiple_threads/main.cpp b/packages/Python/lldbsuite/test/functionalities/stop-hook/multiple_threads/main.cpp
new file mode 100644
index 000000000000..e193ae18e2c1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/stop-hook/multiple_threads/main.cpp
@@ -0,0 +1,77 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <chrono>
+#include <cstdio>
+#include <mutex>
+#include <random>
+#include <thread>
+
+std::default_random_engine g_random_engine{std::random_device{}()};
+std::uniform_int_distribution<> g_distribution{0, 3000000};
+
+uint32_t g_val = 0;
+
+uint32_t
+access_pool (bool flag = false)
+{
+ static std::mutex g_access_mutex;
+ if (!flag)
+ g_access_mutex.lock();
+
+ uint32_t old_val = g_val;
+ if (flag)
+ g_val = old_val + 1;
+
+ if (!flag)
+ g_access_mutex.unlock();
+ return g_val;
+}
+
+void
+thread_func (uint32_t thread_index)
+{
+ // Break here to test that the stop-hook mechanism works for multiple threads.
+ printf ("%s (thread index = %u) startng...\n", __FUNCTION__, thread_index);
+
+ uint32_t count = 0;
+ uint32_t val;
+ while (count++ < 15)
+ {
+ // random micro second sleep from zero to 3 seconds
+ int usec = g_distribution(g_random_engine);
+ printf ("%s (thread = %u) doing a usleep (%d)...\n", __FUNCTION__, thread_index, usec);
+ std::this_thread::sleep_for(std::chrono::microseconds{usec});
+
+ if (count < 7)
+ val = access_pool ();
+ else
+ val = access_pool (true);
+
+ printf ("%s (thread = %u) after usleep access_pool returns %d (count=%d)...\n", __FUNCTION__, thread_index, val, count);
+ }
+ printf ("%s (thread index = %u) exiting...\n", __FUNCTION__, thread_index);
+}
+
+
+int main (int argc, char const *argv[])
+{
+ std::thread threads[3];
+
+ printf ("Before turning all three threads loose...\n"); // Set break point at this line, and add a stop-hook.
+ // Create 3 threads
+ for (auto &thread : threads)
+ thread = std::thread{thread_func, std::distance(threads, &thread)};
+
+ // Join all of our threads
+ for (auto &thread : threads)
+ thread.join();
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/target_command/Makefile b/packages/Python/lldbsuite/test/functionalities/target_command/Makefile
new file mode 100644
index 000000000000..9117ab9388b7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/target_command/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../make
+
+# Example:
+#
+# C_SOURCES := b.c
+# EXE := b.out
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/target_command/TestTargetCommand.py b/packages/Python/lldbsuite/test/functionalities/target_command/TestTargetCommand.py
new file mode 100644
index 000000000000..0ab965d2aa16
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/target_command/TestTargetCommand.py
@@ -0,0 +1,201 @@
+"""
+Test some target commands: create, list, select, variable.
+"""
+
+from __future__ import print_function
+
+
+
+import lldb
+import sys
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class targetCommandTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers for our breakpoints.
+ self.line_b = line_number('b.c', '// Set break point at this line.')
+ self.line_c = line_number('c.c', '// Set break point at this line.')
+
+ def test_target_command(self):
+ """Test some target commands: create, list, select."""
+ da = {'C_SOURCES': 'a.c', 'EXE': 'a.out'}
+ self.build(dictionary=da)
+ self.addTearDownCleanup(dictionary=da)
+
+ db = {'C_SOURCES': 'b.c', 'EXE': 'b.out'}
+ self.build(dictionary=db)
+ self.addTearDownCleanup(dictionary=db)
+
+ dc = {'C_SOURCES': 'c.c', 'EXE': 'c.out'}
+ self.build(dictionary=dc)
+ self.addTearDownCleanup(dictionary=dc)
+
+ self.do_target_command()
+
+ # rdar://problem/9763907
+ # 'target variable' command fails if the target program has been run
+ @expectedFailureAndroid(archs=['aarch64'])
+ def test_target_variable_command(self):
+ """Test 'target variable' command before and after starting the inferior."""
+ d = {'C_SOURCES': 'globals.c', 'EXE': 'globals'}
+ self.build(dictionary=d)
+ self.addTearDownCleanup(dictionary=d)
+
+ self.do_target_variable_command('globals')
+
+ @expectedFailureAndroid(archs=['aarch64'])
+ def test_target_variable_command_no_fail(self):
+ """Test 'target variable' command before and after starting the inferior."""
+ d = {'C_SOURCES': 'globals.c', 'EXE': 'globals'}
+ self.build(dictionary=d)
+ self.addTearDownCleanup(dictionary=d)
+
+ self.do_target_variable_command_no_fail('globals')
+
+ def do_target_command(self):
+ """Exercise 'target create', 'target list', 'target select' commands."""
+ exe_a = os.path.join(os.getcwd(), "a.out")
+ exe_b = os.path.join(os.getcwd(), "b.out")
+ exe_c = os.path.join(os.getcwd(), "c.out")
+
+ self.runCmd("target list")
+ output = self.res.GetOutput()
+ if output.startswith("No targets"):
+ # We start from index 0.
+ base = 0
+ else:
+ # Find the largest index of the existing list.
+ import re
+ pattern = re.compile("target #(\d+):")
+ for line in reversed(output.split(os.linesep)):
+ match = pattern.search(line)
+ if match:
+ # We will start from (index + 1) ....
+ base = int(match.group(1), 10) + 1
+ #print("base is:", base)
+ break;
+
+ self.runCmd("target create " + exe_a, CURRENT_EXECUTABLE_SET)
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.runCmd("target create " + exe_b, CURRENT_EXECUTABLE_SET)
+ lldbutil.run_break_set_by_file_and_line (self, 'b.c', self.line_b, num_expected_locations=1, loc_exact=True)
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.runCmd("target create " + exe_c, CURRENT_EXECUTABLE_SET)
+ lldbutil.run_break_set_by_file_and_line (self, 'c.c', self.line_c, num_expected_locations=1, loc_exact=True)
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.runCmd("target list")
+
+ self.runCmd("target select %d" % base)
+ self.runCmd("thread backtrace")
+
+ self.runCmd("target select %d" % (base + 2))
+ self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['c.c:%d' % self.line_c,
+ 'stop reason = breakpoint'])
+
+ self.runCmd("target select %d" % (base + 1))
+ self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['b.c:%d' % self.line_b,
+ 'stop reason = breakpoint'])
+
+ self.runCmd("target list")
+
+ def do_target_variable_command(self, exe_name):
+ """Exercise 'target variable' command before and after starting the inferior."""
+ self.runCmd("file " + exe_name, CURRENT_EXECUTABLE_SET)
+
+ self.expect("target variable my_global_char", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["my_global_char", "'X'"])
+ self.expect("target variable my_global_str", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['my_global_str', '"abc"'])
+ self.expect("target variable my_static_int", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['my_static_int', '228'])
+ self.expect("target variable my_global_str_ptr", matching=False,
+ substrs = ['"abc"'])
+ self.expect("target variable *my_global_str_ptr", matching=True,
+ substrs = ['"abc"'])
+ self.expect("target variable *my_global_str", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['a'])
+
+ self.runCmd("b main")
+ self.runCmd("run")
+
+ self.expect("target variable my_global_str", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['my_global_str', '"abc"'])
+ self.expect("target variable my_static_int", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['my_static_int', '228'])
+ self.expect("target variable my_global_str_ptr", matching=False,
+ substrs = ['"abc"'])
+ self.expect("target variable *my_global_str_ptr", matching=True,
+ substrs = ['"abc"'])
+ self.expect("target variable *my_global_str", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['a'])
+ self.expect("target variable my_global_char", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["my_global_char", "'X'"])
+
+ self.runCmd("c")
+
+ # rdar://problem/9763907
+ # 'target variable' command fails if the target program has been run
+ self.expect("target variable my_global_str", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['my_global_str', '"abc"'])
+ self.expect("target variable my_static_int", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['my_static_int', '228'])
+ self.expect("target variable my_global_str_ptr", matching=False,
+ substrs = ['"abc"'])
+ self.expect("target variable *my_global_str_ptr", matching=True,
+ substrs = ['"abc"'])
+ self.expect("target variable *my_global_str", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['a'])
+ self.expect("target variable my_global_char", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["my_global_char", "'X'"])
+
+ def do_target_variable_command_no_fail(self, exe_name):
+ """Exercise 'target variable' command before and after starting the inferior."""
+ self.runCmd("file " + exe_name, CURRENT_EXECUTABLE_SET)
+
+ self.expect("target variable my_global_char", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["my_global_char", "'X'"])
+ self.expect("target variable my_global_str", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['my_global_str', '"abc"'])
+ self.expect("target variable my_static_int", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['my_static_int', '228'])
+ self.expect("target variable my_global_str_ptr", matching=False,
+ substrs = ['"abc"'])
+ self.expect("target variable *my_global_str_ptr", matching=True,
+ substrs = ['"abc"'])
+ self.expect("target variable *my_global_str", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['a'])
+
+ self.runCmd("b main")
+ self.runCmd("run")
+
+ # New feature: you don't need to specify the variable(s) to 'target vaiable'.
+ # It will find all the global and static variables in the current compile unit.
+ self.expect("target variable",
+ substrs = ['my_global_char',
+ 'my_global_str',
+ 'my_global_str_ptr',
+ 'my_static_int'])
+
+ self.expect("target variable my_global_str", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['my_global_str', '"abc"'])
+ self.expect("target variable my_static_int", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['my_static_int', '228'])
+ self.expect("target variable my_global_str_ptr", matching=False,
+ substrs = ['"abc"'])
+ self.expect("target variable *my_global_str_ptr", matching=True,
+ substrs = ['"abc"'])
+ self.expect("target variable *my_global_str", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['a'])
+ self.expect("target variable my_global_char", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["my_global_char", "'X'"])
diff --git a/packages/Python/lldbsuite/test/functionalities/target_command/a.c b/packages/Python/lldbsuite/test/functionalities/target_command/a.c
new file mode 100644
index 000000000000..9d0706a0862d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/target_command/a.c
@@ -0,0 +1,16 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+int main(int argc, const char* argv[])
+{
+ int *null_ptr = 0;
+ printf("Hello, segfault!\n");
+ printf("Now crash %d\n", *null_ptr); // Crash here.
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/target_command/b.c b/packages/Python/lldbsuite/test/functionalities/target_command/b.c
new file mode 100644
index 000000000000..62ec97f43284
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/target_command/b.c
@@ -0,0 +1,13 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+int main (int argc, char const *argv[])
+{
+ return 0; // Set break point at this line.
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/target_command/c.c b/packages/Python/lldbsuite/test/functionalities/target_command/c.c
new file mode 100644
index 000000000000..7c362cc437af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/target_command/c.c
@@ -0,0 +1,29 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+int main (int argc, char const *argv[])
+{
+ enum days {
+ Monday = 10,
+ Tuesday,
+ Wednesday,
+ Thursday,
+ Friday,
+ Saturday,
+ Sunday,
+ kNumDays
+ };
+ enum days day;
+ for (day = Monday - 1; day <= kNumDays + 1; day++)
+ {
+ printf("day as int is %i\n", (int)day);
+ }
+ return 0; // Set break point at this line.
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/target_command/globals.c b/packages/Python/lldbsuite/test/functionalities/target_command/globals.c
new file mode 100644
index 000000000000..6902bc415681
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/target_command/globals.c
@@ -0,0 +1,25 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+char my_global_char = 'X';
+const char* my_global_str = "abc";
+const char **my_global_str_ptr = &my_global_str;
+static int my_static_int = 228;
+
+int main (int argc, char const *argv[])
+{
+ printf("global char: %c\n", my_global_char);
+
+ printf("global str: %s\n", my_global_str);
+
+ printf("argc + my_static_int = %d\n", (argc + my_static_int));
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/Makefile b/packages/Python/lldbsuite/test/functionalities/thread/Makefile
new file mode 100644
index 000000000000..644e2971a2c1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+ENABLE_THREADS := YES
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/TestNumThreads.py b/packages/Python/lldbsuite/test/functionalities/thread/TestNumThreads.py
new file mode 100644
index 000000000000..8184ddcfbf48
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/TestNumThreads.py
@@ -0,0 +1,53 @@
+"""
+Test number of threads.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class NumberOfThreadsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def test(self):
+ """Test number of threads."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # This should create a breakpoint with 1 location.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1)
+
+ # The breakpoint list should show 3 locations.
+ self.expect("breakpoint list -f", "Breakpoint location shown correctly",
+ substrs = ["1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % self.line])
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Stopped once.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ["stop reason = breakpoint 1."])
+
+ # Get the target process
+ target = self.dbg.GetSelectedTarget()
+ process = target.GetProcess()
+
+ # Get the number of threads
+ num_threads = process.GetNumThreads()
+
+ # Using std::thread may involve extra threads, so we assert that there are
+ # at least 4 rather than exactly 4.
+ self.assertTrue(num_threads >= 4, 'Number of expected threads and actual threads do not match.')
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/Makefile b/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/Makefile
new file mode 100644
index 000000000000..24e68012ebd3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+CXXFLAGS += -std=c++11
+CXX_SOURCES := ParallelTask.cpp
+ENABLE_THREADS := YES
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/ParallelTask.cpp b/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/ParallelTask.cpp
new file mode 100755
index 000000000000..71fb8e3bb565
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/ParallelTask.cpp
@@ -0,0 +1,151 @@
+#include <cstdint>
+#include <thread>
+#include <vector>
+#include <queue>
+#include <future>
+#include <iostream>
+#include <cassert>
+
+class TaskPoolImpl
+{
+public:
+ TaskPoolImpl(uint32_t num_threads) :
+ m_stop(false)
+ {
+ for (uint32_t i = 0; i < num_threads; ++i)
+ m_threads.emplace_back(Worker, this);
+ }
+
+ ~TaskPoolImpl()
+ {
+ Stop();
+ }
+
+ template<typename F, typename... Args>
+ std::future<typename std::result_of<F(Args...)>::type>
+ AddTask(F&& f, Args&&... args)
+ {
+ auto task = std::make_shared<std::packaged_task<typename std::result_of<F(Args...)>::type()>>(
+ std::bind(std::forward<F>(f), std::forward<Args>(args)...));
+
+ std::unique_lock<std::mutex> lock(m_tasks_mutex);
+ assert(!m_stop && "Can't add task to TaskPool after it is stopped");
+ m_tasks.emplace([task](){ (*task)(); });
+ lock.unlock();
+ m_tasks_cv.notify_one();
+
+ return task->get_future();
+ }
+
+ void
+ Stop()
+ {
+ std::unique_lock<std::mutex> lock(m_tasks_mutex);
+ m_stop = true;
+ m_tasks_mutex.unlock();
+ m_tasks_cv.notify_all();
+ for (auto& t : m_threads)
+ t.join();
+ }
+
+private:
+ static void
+ Worker(TaskPoolImpl* pool)
+ {
+ while (true)
+ {
+ std::unique_lock<std::mutex> lock(pool->m_tasks_mutex);
+ if (pool->m_tasks.empty())
+ pool->m_tasks_cv.wait(lock, [pool](){ return !pool->m_tasks.empty() || pool->m_stop; });
+ if (pool->m_tasks.empty())
+ break;
+
+ std::function<void()> f = pool->m_tasks.front();
+ pool->m_tasks.pop();
+ lock.unlock();
+
+ f();
+ }
+ }
+
+ std::queue<std::function<void()>> m_tasks;
+ std::mutex m_tasks_mutex;
+ std::condition_variable m_tasks_cv;
+ bool m_stop;
+ std::vector<std::thread> m_threads;
+};
+
+class TaskPool
+{
+public:
+ // Add a new task to the thread pool and return a std::future belongs for the newly created task.
+ // The caller of this function have to wait on the future for this task to complete.
+ template<typename F, typename... Args>
+ static std::future<typename std::result_of<F(Args...)>::type>
+ AddTask(F&& f, Args&&... args)
+ {
+ return GetImplementation().AddTask(std::forward<F>(f), std::forward<Args>(args)...);
+ }
+
+ // Run all of the specified tasks on the thread pool and wait until all of them are finished
+ // before returning
+ template<typename... T>
+ static void
+ RunTasks(T&&... t)
+ {
+ RunTaskImpl<T...>::Run(std::forward<T>(t)...);
+ }
+
+private:
+ static TaskPoolImpl&
+ GetImplementation()
+ {
+ static TaskPoolImpl g_task_pool_impl(std::thread::hardware_concurrency());
+ return g_task_pool_impl;
+ }
+
+ template<typename... T>
+ struct RunTaskImpl;
+};
+
+template<typename H, typename... T>
+struct TaskPool::RunTaskImpl<H, T...>
+{
+ static void
+ Run(H&& h, T&&... t)
+ {
+ auto f = AddTask(std::forward<H>(h));
+ RunTaskImpl<T...>::Run(std::forward<T>(t)...);
+ f.wait();
+ }
+};
+
+template<>
+struct TaskPool::RunTaskImpl<>
+{
+ static void
+ Run() {}
+};
+
+int main()
+{
+ std::vector<std::future<uint32_t>> tasks;
+ for (int i = 0; i < 100000; ++i)
+ {
+ tasks.emplace_back(TaskPool::AddTask([](int i){
+ uint32_t s = 0;
+ for (int j = 0; j <= i; ++j)
+ s += j;
+ return s;
+ },
+ i));
+ }
+
+ for (auto& it : tasks) // Set breakpoint here
+ it.wait();
+
+ TaskPool::RunTasks(
+ []() { return 1; },
+ []() { return "aaaa"; }
+ );
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/TestBacktraceAll.py b/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/TestBacktraceAll.py
new file mode 100644
index 000000000000..91bc68577a43
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/backtrace_all/TestBacktraceAll.py
@@ -0,0 +1,57 @@
+"""
+Test regression for Bug 25251.
+"""
+
+import os, time
+import unittest2
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class BreakpointAfterJoinTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number for our breakpoint.
+ self.breakpoint = line_number('ParallelTask.cpp', '// Set breakpoint here')
+
+ @skipIfTargetAndroid(archs=["arm"]) # The android-arm compiler can't compile the inferior
+ # because of an issue around std::future.
+ # TODO: Change the test to don't depend on std::future<T>
+ def test(self):
+ """Test breakpoint handling after a thread join."""
+ self.build(dictionary=self.getBuildFlags())
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # This should create a breakpoint
+ lldbutil.run_break_set_by_file_and_line (self, "ParallelTask.cpp", self.breakpoint, num_expected_locations=-1)
+
+ # The breakpoint list should show 1 location.
+ self.expect("breakpoint list -f", "Breakpoint location shown correctly",
+ substrs = ["1: file = 'ParallelTask.cpp', line = %d, exact_match = 0" % self.breakpoint])
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This should not result in a segmentation fault
+ self.expect("thread backtrace all", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ["stop reason = breakpoint 1."])
+
+ # Run to completion
+ self.runCmd("continue")
+
+if __name__ == '__main__':
+ import atexit
+ lldb.SBDebugger.Initialize()
+ atexit.register(lambda: lldb.SBDebugger.Terminate())
+ unittest2.main()
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/Makefile b/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/Makefile
new file mode 100644
index 000000000000..67aa16625bff
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+ENABLE_THREADS := YES
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/TestBreakAfterJoin.py b/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/TestBreakAfterJoin.py
new file mode 100644
index 000000000000..43397a122391
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/TestBreakAfterJoin.py
@@ -0,0 +1,77 @@
+"""
+Test number of threads.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class BreakpointAfterJoinTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number for our breakpoint.
+ self.breakpoint = line_number('main.cpp', '// Set breakpoint here')
+
+ @expectedFailureDarwin("llvm.org/pr15824") # thread states not properly maintained
+ @expectedFailureFreeBSD("llvm.org/pr18190") # thread states not properly maintained
+ @expectedFailureLinux("llvm.org/pr15824") # thread states not properly maintained
+ def test(self):
+ """Test breakpoint handling after a thread join."""
+ self.build(dictionary=self.getBuildFlags())
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # This should create a breakpoint in the main thread.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.breakpoint, num_expected_locations=1)
+
+ # The breakpoint list should show 1 location.
+ self.expect("breakpoint list -f", "Breakpoint location shown correctly",
+ substrs = ["1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % self.breakpoint])
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Get the target process
+ target = self.dbg.GetSelectedTarget()
+ process = target.GetProcess()
+
+ # The exit probably occurred during breakpoint handling, but it isn't
+ # guaranteed. The main thing we're testing here is that the debugger
+ # handles this cleanly is some way.
+
+ # Get the number of threads
+ num_threads = process.GetNumThreads()
+
+ # Make sure we see at least six threads
+ self.assertTrue(num_threads >= 6, 'Number of expected threads and actual threads do not match.')
+
+ # Make sure all threads are stopped
+ for i in range(0, num_threads):
+ self.assertTrue(process.GetThreadAtIndex(i).IsStopped(),
+ "Thread {0} didn't stop during breakpoint.".format(i))
+
+ # Run to completion
+ self.runCmd("continue")
+
+ # If the process hasn't exited, collect some information
+ if process.GetState() != lldb.eStateExited:
+ self.runCmd("thread list")
+ self.runCmd("process status")
+
+ # At this point, the inferior process should have exited.
+ self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED)
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/main.cpp b/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/main.cpp
new file mode 100644
index 000000000000..a63079524ee2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/break_after_join/main.cpp
@@ -0,0 +1,118 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+// This test is intended to create a situation in which one thread will exit
+// while a breakpoint is being handled in another thread. This may not always
+// happen because it's possible that the exiting thread will exit before the
+// breakpoint is hit. The test case should be flexible enough to treat that
+// as success.
+
+#include <atomic>
+#include <chrono>
+#include <thread>
+
+volatile int g_test = 0;
+
+// Note that although hogging the CPU while waiting for a variable to change
+// would be terrible in production code, it's great for testing since it
+// avoids a lot of messy context switching to get multiple threads synchronized.
+#define do_nothing()
+
+#define pseudo_barrier_wait(bar) \
+ --bar; \
+ while (bar > 0) \
+ do_nothing();
+
+#define pseudo_barrier_init(bar, count) (bar = count)
+
+// A barrier to synchronize all the threads.
+std::atomic_int g_barrier1;
+
+// A barrier to keep the threads from exiting until after the breakpoint has
+// been passed.
+std::atomic_int g_barrier2;
+
+void *
+break_thread_func ()
+{
+ // Wait until all the threads are running
+ pseudo_barrier_wait(g_barrier1);
+
+ // Wait for the join thread to join
+ std::this_thread::sleep_for(std::chrono::microseconds(50));
+
+ // Do something
+ g_test++; // Set breakpoint here
+
+ // Synchronize after the breakpoint
+ pseudo_barrier_wait(g_barrier2);
+
+ // Return
+ return NULL;
+}
+
+void *
+wait_thread_func ()
+{
+ // Wait until the entire first group of threads is running
+ pseudo_barrier_wait(g_barrier1);
+
+ // Wait until the breakpoint has been passed
+ pseudo_barrier_wait(g_barrier2);
+
+ // Return
+ return NULL;
+}
+
+void *
+join_thread_func (void *input)
+{
+ std::thread *thread_to_join = (std::thread *)input;
+
+ // Sync up with the rest of the threads.
+ pseudo_barrier_wait(g_barrier1);
+
+ // Join the other thread
+ thread_to_join->join();
+
+ // Return
+ return NULL;
+}
+
+int main ()
+{
+ // The first barrier waits for the non-joining threads to start.
+ // This thread will also participate in that barrier.
+ // The idea here is to guarantee that the joining thread will be
+ // last in the internal list maintained by the debugger.
+ pseudo_barrier_init(g_barrier1, 5);
+
+ // The second barrier keeps the waiting threads around until the breakpoint
+ // has been passed.
+ pseudo_barrier_init(g_barrier2, 4);
+
+ // Create a thread to hit the breakpoint
+ std::thread thread_1(break_thread_func);
+
+ // Create more threads to slow the debugger down during processing.
+ std::thread thread_2(wait_thread_func);
+ std::thread thread_3(wait_thread_func);
+ std::thread thread_4(wait_thread_func);
+
+ // Create a thread to join the breakpoint thread
+ std::thread thread_5(join_thread_func, &thread_1);
+
+ // Wait for the threads to finish
+ thread_5.join(); // implies thread_1 is already finished
+ thread_4.join();
+ thread_3.join();
+ thread_2.join();
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/Makefile b/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/Makefile
new file mode 100644
index 000000000000..469c0809aa24
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+ENABLE_THREADS := YES
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentEvents.py b/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentEvents.py
new file mode 100644
index 000000000000..9eb25b68765a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/TestConcurrentEvents.py
@@ -0,0 +1,491 @@
+"""
+A stress-test of sorts for LLDB's handling of threads in the inferior.
+
+This test sets a breakpoint in the main thread where test parameters (numbers of
+threads) can be adjusted, runs the inferior to that point, and modifies the
+locals that control the event thread counts. This test also sets a breakpoint in
+breakpoint_func (the function executed by each 'breakpoint' thread) and a
+watchpoint on a global modified in watchpoint_func. The inferior is continued
+until exit or a crash takes place, and the number of events seen by LLDB is
+verified to match the expected number of events.
+"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+@skipIfWindows
+@expectedFailureAll(archs=['mips64', 'mips64el']) # Atomic sequences are not supported yet for MIPS in LLDB.
+class ConcurrentEventsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ #
+ ## Tests for multiple threads that generate a single event.
+ #
+ @unittest2.skipIf(TestBase.skipLongRunningTest(), "Skip this long running test")
+ def test_many_breakpoints(self):
+ """Test 100 breakpoints from 100 threads."""
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_breakpoint_threads=100)
+
+ @unittest2.skipIf(TestBase.skipLongRunningTest(), "Skip this long running test")
+ def test_many_watchpoints(self):
+ """Test 100 watchpoints from 100 threads."""
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_watchpoint_threads=100)
+
+ @unittest2.skipIf(TestBase.skipLongRunningTest(), "Skip this long running test")
+ def test_many_signals(self):
+ """Test 100 signals from 100 threads."""
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_signal_threads=100)
+
+ @unittest2.skipIf(TestBase.skipLongRunningTest(), "Skip this long running test")
+ def test_many_crash(self):
+ """Test 100 threads that cause a segfault."""
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_crash_threads=100)
+
+
+ #
+ ## Tests for concurrent signal and breakpoint
+ #
+ @skipIfFreeBSD # timing out on buildbot
+ def test_signal_break(self):
+ """Test signal and a breakpoint in multiple threads."""
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_breakpoint_threads=1, num_signal_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ def test_delay_signal_break(self):
+ """Test (1-second delay) signal and a breakpoint in multiple threads."""
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_breakpoint_threads=1, num_delay_signal_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ def test_signal_delay_break(self):
+ """Test signal and a (1 second delay) breakpoint in multiple threads."""
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_delay_breakpoint_threads=1, num_signal_threads=1)
+
+
+ #
+ ## Tests for concurrent watchpoint and breakpoint
+ #
+ @skipIfFreeBSD # timing out on buildbot
+ @skipIfRemoteDueToDeadlock
+ def test_watch_break(self):
+ """Test watchpoint and a breakpoint in multiple threads."""
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_breakpoint_threads=1, num_watchpoint_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ @skipIfRemoteDueToDeadlock
+ def test_delay_watch_break(self):
+ """Test (1-second delay) watchpoint and a breakpoint in multiple threads."""
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_breakpoint_threads=1, num_delay_watchpoint_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ @skipIfRemoteDueToDeadlock
+ def test_watch_break_delay(self):
+ """Test watchpoint and a (1 second delay) breakpoint in multiple threads."""
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_delay_breakpoint_threads=1, num_watchpoint_threads=1)
+
+ #
+ ## Tests for concurrent signal and watchpoint
+ #
+ @skipIfFreeBSD # timing out on buildbot
+ @skipIfRemoteDueToDeadlock
+ def test_signal_watch(self):
+ """Test a watchpoint and a signal in multiple threads."""
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_signal_threads=1, num_watchpoint_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ @skipIfRemoteDueToDeadlock
+ def test_delay_signal_watch(self):
+ """Test a watchpoint and a (1 second delay) signal in multiple threads."""
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_delay_signal_threads=1, num_watchpoint_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ @skipIfRemoteDueToDeadlock
+ @expectedFailureAll("llvm.org/pr16714", oslist=["linux"], archs=["i386"])
+ def test_signal_delay_watch(self):
+ """Test a (1 second delay) watchpoint and a signal in multiple threads."""
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_signal_threads=1, num_delay_watchpoint_threads=1)
+
+
+ #
+ ## Tests for multiple breakpoint threads
+ #
+ @skipIfFreeBSD # timing out on buildbot
+ def test_two_breakpoint_threads(self):
+ """Test two threads that trigger a breakpoint. """
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_breakpoint_threads=2)
+
+ @skipIfFreeBSD # timing out on buildbot
+ def test_breakpoint_one_delay_breakpoint_threads(self):
+ """Test threads that trigger a breakpoint where one thread has a 1 second delay. """
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_breakpoint_threads=1,
+ num_delay_breakpoint_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ def test_two_breakpoints_one_signal(self):
+ """Test two threads that trigger a breakpoint and one signal thread. """
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_breakpoint_threads=2, num_signal_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ def test_breakpoint_delay_breakpoint_one_signal(self):
+ """Test two threads that trigger a breakpoint (one with a 1 second delay) and one signal thread. """
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_breakpoint_threads=1,
+ num_delay_breakpoint_threads=1,
+ num_signal_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ def test_two_breakpoints_one_delay_signal(self):
+ """Test two threads that trigger a breakpoint and one (1 second delay) signal thread. """
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_breakpoint_threads=2, num_delay_signal_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ @skipIfRemoteDueToDeadlock
+ def test_two_breakpoints_one_watchpoint(self):
+ """Test two threads that trigger a breakpoint and one watchpoint thread. """
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_breakpoint_threads=2, num_watchpoint_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ @skipIfRemoteDueToDeadlock
+ def test_breakpoints_delayed_breakpoint_one_watchpoint(self):
+ """Test a breakpoint, a delayed breakpoint, and one watchpoint thread. """
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_breakpoint_threads=1,
+ num_delay_breakpoint_threads=1,
+ num_watchpoint_threads=1)
+
+ #
+ ## Tests for multiple watchpoint threads
+ #
+ @skipIfFreeBSD # timing out on buildbot
+ @skipIfRemoteDueToDeadlock
+ def test_two_watchpoint_threads(self):
+ """Test two threads that trigger a watchpoint. """
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_watchpoint_threads=2)
+
+ @skipIfFreeBSD # timing out on buildbot
+ @skipIfRemoteDueToDeadlock
+ def test_watchpoint_with_delay_watchpoint_threads(self):
+ """Test two threads that trigger a watchpoint where one thread has a 1 second delay. """
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_watchpoint_threads=1,
+ num_delay_watchpoint_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ @skipIfRemoteDueToDeadlock
+ def test_two_watchpoints_one_breakpoint(self):
+ """Test two threads that trigger a watchpoint and one breakpoint thread. """
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_watchpoint_threads=2, num_breakpoint_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ @skipIfRemoteDueToDeadlock
+ def test_two_watchpoints_one_delay_breakpoint(self):
+ """Test two threads that trigger a watchpoint and one (1 second delay) breakpoint thread. """
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_watchpoint_threads=2, num_delay_breakpoint_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ @skipIfRemoteDueToDeadlock
+ def test_watchpoint_delay_watchpoint_one_breakpoint(self):
+ """Test two threads that trigger a watchpoint (one with a 1 second delay) and one breakpoint thread. """
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_watchpoint_threads=1,
+ num_delay_watchpoint_threads=1,
+ num_breakpoint_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ @skipIfRemoteDueToDeadlock
+ def test_two_watchpoints_one_signal(self):
+ """Test two threads that trigger a watchpoint and one signal thread. """
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_watchpoint_threads=2, num_signal_threads=1)
+
+ #
+ ## Test for watchpoint, signal and breakpoint happening concurrently
+ #
+ @skipIfFreeBSD # timing out on buildbot
+ @skipIfRemoteDueToDeadlock
+ def test_signal_watch_break(self):
+ """Test a signal/watchpoint/breakpoint in multiple threads."""
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_signal_threads=1,
+ num_watchpoint_threads=1,
+ num_breakpoint_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ @skipIfRemoteDueToDeadlock
+ def test_signal_watch_break(self):
+ """Test one signal thread with 5 watchpoint and breakpoint threads."""
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_signal_threads=1,
+ num_watchpoint_threads=5,
+ num_breakpoint_threads=5)
+
+ @skipIfFreeBSD # timing out on buildbot
+ @skipIfRemoteDueToDeadlock
+ def test_signal_watch_break(self):
+ """Test with 5 watchpoint and breakpoint threads."""
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_watchpoint_threads=5,
+ num_breakpoint_threads=5)
+
+
+ #
+ ## Test for crashing threads happening concurrently with other events
+ #
+ @skipIfFreeBSD # timing out on buildbot
+ def test_crash_with_break(self):
+ """ Test a thread that crashes while another thread hits a breakpoint."""
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_crash_threads=1, num_breakpoint_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ @skipIfRemoteDueToDeadlock
+ def test_crash_with_watchpoint(self):
+ """ Test a thread that crashes while another thread hits a watchpoint."""
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_crash_threads=1, num_watchpoint_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ def test_crash_with_signal(self):
+ """ Test a thread that crashes while another thread generates a signal."""
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_crash_threads=1, num_signal_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ @skipIfRemoteDueToDeadlock
+ def test_crash_with_watchpoint_breakpoint_signal(self):
+ """ Test a thread that crashes while other threads generate a signal and hit a watchpoint and breakpoint. """
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_crash_threads=1,
+ num_breakpoint_threads=1,
+ num_signal_threads=1,
+ num_watchpoint_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ @skipIfRemoteDueToDeadlock
+ def test_delayed_crash_with_breakpoint_watchpoint(self):
+ """ Test a thread with a delayed crash while other threads hit a watchpoint and a breakpoint. """
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_delay_crash_threads=1,
+ num_breakpoint_threads=1,
+ num_watchpoint_threads=1)
+
+ @skipIfFreeBSD # timing out on buildbot
+ def test_delayed_crash_with_breakpoint_signal(self):
+ """ Test a thread with a delayed crash while other threads generate a signal and hit a breakpoint. """
+ self.build(dictionary=self.getBuildFlags())
+ self.do_thread_actions(num_delay_crash_threads=1,
+ num_breakpoint_threads=1,
+ num_signal_threads=1)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number for our breakpoint.
+ self.filename = 'main.cpp'
+ self.thread_breakpoint_line = line_number(self.filename, '// Set breakpoint here')
+ self.setup_breakpoint_line = line_number(self.filename, '// Break here and adjust num')
+ self.finish_breakpoint_line = line_number(self.filename, '// Break here and verify one thread is active')
+
+ def describe_threads(self):
+ ret = []
+ for x in self.inferior_process:
+ id = x.GetIndexID()
+ reason = x.GetStopReason()
+ status = "stopped" if x.IsStopped() else "running"
+ reason_str = lldbutil.stop_reason_to_str(reason)
+ if reason == lldb.eStopReasonBreakpoint:
+ bpid = x.GetStopReasonDataAtIndex(0)
+ bp = self.inferior_target.FindBreakpointByID(bpid)
+ reason_str = "%s hit %d times" % (lldbutil.get_description(bp), bp.GetHitCount())
+ elif reason == lldb.eStopReasonWatchpoint:
+ watchid = x.GetStopReasonDataAtIndex(0)
+ watch = self.inferior_target.FindWatchpointByID(watchid)
+ reason_str = "%s hit %d times" % (lldbutil.get_description(watch), watch.GetHitCount())
+ elif reason == lldb.eStopReasonSignal:
+ signals = self.inferior_process.GetUnixSignals()
+ signal_name = signals.GetSignalAsCString(x.GetStopReasonDataAtIndex(0))
+ reason_str = "signal %s" % signal_name
+
+ location = "\t".join([lldbutil.get_description(x.GetFrameAtIndex(i)) for i in range(x.GetNumFrames())])
+ ret.append("thread %d %s due to %s at\n\t%s" % (id, status, reason_str, location))
+ return ret
+
+ def add_breakpoint(self, line, descriptions):
+ """ Adds a breakpoint at self.filename:line and appends its description to descriptions, and
+ returns the LLDB SBBreakpoint object.
+ """
+
+ bpno = lldbutil.run_break_set_by_file_and_line(self, self.filename, line, num_expected_locations=-1)
+ bp = self.inferior_target.FindBreakpointByID(bpno)
+ descriptions.append(": file = 'main.cpp', line = %d" % self.finish_breakpoint_line)
+ return bp
+
+ def inferior_done(self):
+ """ Returns true if the inferior is done executing all the event threads (and is stopped at self.finish_breakpoint,
+ or has terminated execution.
+ """
+ return self.finish_breakpoint.GetHitCount() > 0 or \
+ self.crash_count > 0 or \
+ self.inferior_process.GetState() == lldb.eStateExited
+
+ def count_signaled_threads(self):
+ count = 0
+ for thread in self.inferior_process:
+ if thread.GetStopReason() == lldb.eStopReasonSignal and thread.GetStopReasonDataAtIndex(0) == self.inferior_process.GetUnixSignals().GetSignalNumberFromName('SIGUSR1'):
+ count += 1
+ return count
+
+ def do_thread_actions(self,
+ num_breakpoint_threads = 0,
+ num_signal_threads = 0,
+ num_watchpoint_threads = 0,
+ num_crash_threads = 0,
+ num_delay_breakpoint_threads = 0,
+ num_delay_signal_threads = 0,
+ num_delay_watchpoint_threads = 0,
+ num_delay_crash_threads = 0):
+ """ Sets a breakpoint in the main thread where test parameters (numbers of threads) can be adjusted, runs the inferior
+ to that point, and modifies the locals that control the event thread counts. Also sets a breakpoint in
+ breakpoint_func (the function executed by each 'breakpoint' thread) and a watchpoint on a global modified in
+ watchpoint_func. The inferior is continued until exit or a crash takes place, and the number of events seen by LLDB
+ is verified to match the expected number of events.
+ """
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Get the target
+ self.inferior_target = self.dbg.GetSelectedTarget()
+
+ expected_bps = []
+
+ # Initialize all the breakpoints (main thread/aux thread)
+ self.setup_breakpoint = self.add_breakpoint(self.setup_breakpoint_line, expected_bps)
+ self.finish_breakpoint = self.add_breakpoint(self.finish_breakpoint_line, expected_bps)
+
+ # Set the thread breakpoint
+ if num_breakpoint_threads + num_delay_breakpoint_threads > 0:
+ self.thread_breakpoint = self.add_breakpoint(self.thread_breakpoint_line, expected_bps)
+
+ # Verify breakpoints
+ self.expect("breakpoint list -f", "Breakpoint locations shown correctly", substrs = expected_bps)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Check we are at line self.setup_breakpoint
+ self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ["stop reason = breakpoint 1."])
+
+ # Initialize the (single) watchpoint on the global variable (g_watchme)
+ if num_watchpoint_threads + num_delay_watchpoint_threads > 0:
+ self.runCmd("watchpoint set variable g_watchme")
+ for w in self.inferior_target.watchpoint_iter():
+ self.thread_watchpoint = w
+ self.assertTrue("g_watchme" in str(self.thread_watchpoint), "Watchpoint location not shown correctly")
+
+ # Get the process
+ self.inferior_process = self.inferior_target.GetProcess()
+
+ # We should be stopped at the setup site where we can set the number of
+ # threads doing each action (break/crash/signal/watch)
+ self.assertEqual(self.inferior_process.GetNumThreads(), 1, 'Expected to stop before any additional threads are spawned.')
+
+ self.runCmd("expr num_breakpoint_threads=%d" % num_breakpoint_threads)
+ self.runCmd("expr num_crash_threads=%d" % num_crash_threads)
+ self.runCmd("expr num_signal_threads=%d" % num_signal_threads)
+ self.runCmd("expr num_watchpoint_threads=%d" % num_watchpoint_threads)
+
+ self.runCmd("expr num_delay_breakpoint_threads=%d" % num_delay_breakpoint_threads)
+ self.runCmd("expr num_delay_crash_threads=%d" % num_delay_crash_threads)
+ self.runCmd("expr num_delay_signal_threads=%d" % num_delay_signal_threads)
+ self.runCmd("expr num_delay_watchpoint_threads=%d" % num_delay_watchpoint_threads)
+
+ # Continue the inferior so threads are spawned
+ self.runCmd("continue")
+
+ # Make sure we see all the threads. The inferior program's threads all synchronize with a pseudo-barrier; that is,
+ # the inferior program ensures all threads are started and running before any thread triggers its 'event'.
+ num_threads = self.inferior_process.GetNumThreads()
+ expected_num_threads = num_breakpoint_threads + num_delay_breakpoint_threads \
+ + num_signal_threads + num_delay_signal_threads \
+ + num_watchpoint_threads + num_delay_watchpoint_threads \
+ + num_crash_threads + num_delay_crash_threads + 1
+ self.assertEqual(num_threads, expected_num_threads,
+ 'Expected to see %d threads, but seeing %d. Details:\n%s' % (expected_num_threads,
+ num_threads,
+ "\n\t".join(self.describe_threads())))
+
+ self.signal_count = self.count_signaled_threads()
+ self.crash_count = len(lldbutil.get_crashed_threads(self, self.inferior_process))
+
+ # Run to completion (or crash)
+ while not self.inferior_done():
+ if self.TraceOn():
+ self.runCmd("thread backtrace all")
+ self.runCmd("continue")
+ self.signal_count += self.count_signaled_threads()
+ self.crash_count += len(lldbutil.get_crashed_threads(self, self.inferior_process))
+
+ if num_crash_threads > 0 or num_delay_crash_threads > 0:
+ # Expecting a crash
+ self.assertTrue(self.crash_count > 0,
+ "Expecting at least one thread to crash. Details: %s" % "\t\n".join(self.describe_threads()))
+
+ # Ensure the zombie process is reaped
+ self.runCmd("process kill")
+
+ elif num_crash_threads == 0 and num_delay_crash_threads == 0:
+ # There should be a single active thread (the main one) which hit the breakpoint after joining
+ self.assertEqual(1, self.finish_breakpoint.GetHitCount(), "Expected main thread (finish) breakpoint to be hit once")
+
+ num_threads = self.inferior_process.GetNumThreads()
+ self.assertEqual(1, num_threads, "Expecting 1 thread but seeing %d. Details:%s" % (num_threads,
+ "\n\t".join(self.describe_threads())))
+ self.runCmd("continue")
+
+ # The inferior process should have exited without crashing
+ self.assertEqual(0, self.crash_count, "Unexpected thread(s) in crashed state")
+ self.assertEqual(self.inferior_process.GetState(), lldb.eStateExited, PROCESS_EXITED)
+
+ # Verify the number of actions took place matches expected numbers
+ expected_breakpoint_threads = num_delay_breakpoint_threads + num_breakpoint_threads
+ breakpoint_hit_count = self.thread_breakpoint.GetHitCount() if expected_breakpoint_threads > 0 else 0
+ self.assertEqual(expected_breakpoint_threads, breakpoint_hit_count,
+ "Expected %d breakpoint hits, but got %d" % (expected_breakpoint_threads, breakpoint_hit_count))
+
+ expected_signal_threads = num_delay_signal_threads + num_signal_threads
+ self.assertEqual(expected_signal_threads, self.signal_count,
+ "Expected %d stops due to signal delivery, but got %d" % (expected_signal_threads, self.signal_count))
+
+ expected_watchpoint_threads = num_delay_watchpoint_threads + num_watchpoint_threads
+ watchpoint_hit_count = self.thread_watchpoint.GetHitCount() if expected_watchpoint_threads > 0 else 0
+ self.assertEqual(expected_watchpoint_threads, watchpoint_hit_count,
+ "Expected %d watchpoint hits, got %d" % (expected_watchpoint_threads, watchpoint_hit_count))
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/main.cpp b/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/main.cpp
new file mode 100644
index 000000000000..ac2535cd2bff
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/concurrent_events/main.cpp
@@ -0,0 +1,200 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+// This test is intended to create a situation in which multiple events
+// (breakpoints, watchpoints, crashes, and signal generation/delivery) happen
+// from multiple threads. The test expects the debugger to set a breakpoint on
+// the main thread (before any worker threads are spawned) and modify variables
+// which control the number of threads that are spawned for each action.
+
+#include <atomic>
+#include <vector>
+using namespace std;
+
+#include <pthread.h>
+
+#include <signal.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+// Note that although hogging the CPU while waiting for a variable to change
+// would be terrible in production code, it's great for testing since it
+// avoids a lot of messy context switching to get multiple threads synchronized.
+#define do_nothing()
+
+#define pseudo_barrier_wait(bar) \
+ --bar; \
+ while (bar > 0) \
+ do_nothing();
+
+#define pseudo_barrier_init(bar, count) (bar = count)
+
+typedef std::vector<std::pair<unsigned, void*(*)(void*)> > action_counts;
+typedef std::vector<pthread_t> thread_vector;
+
+std::atomic_int g_barrier;
+int g_breakpoint = 0;
+int g_sigusr1_count = 0;
+std::atomic_int g_watchme;
+
+struct action_args {
+ int delay;
+};
+
+// Perform any extra actions required by thread 'input' arg
+void do_action_args(void *input) {
+ if (input) {
+ action_args *args = static_cast<action_args*>(input);
+ sleep(args->delay);
+ }
+}
+
+void *
+breakpoint_func (void *input)
+{
+ // Wait until all threads are running
+ pseudo_barrier_wait(g_barrier);
+ do_action_args(input);
+
+ // Do something
+ g_breakpoint++; // Set breakpoint here
+ return 0;
+}
+
+void *
+signal_func (void *input) {
+ // Wait until all threads are running
+ pseudo_barrier_wait(g_barrier);
+ do_action_args(input);
+
+ // Send a user-defined signal to the current process
+ //kill(getpid(), SIGUSR1);
+ // Send a user-defined signal to the current thread
+ pthread_kill(pthread_self(), SIGUSR1);
+
+ return 0;
+}
+
+void *
+watchpoint_func (void *input) {
+ pseudo_barrier_wait(g_barrier);
+ do_action_args(input);
+
+ g_watchme += 1; // watchpoint triggers here
+ return 0;
+}
+
+void *
+crash_func (void *input) {
+ pseudo_barrier_wait(g_barrier);
+ do_action_args(input);
+
+ int *a = 0;
+ *a = 5; // crash happens here
+ return 0;
+}
+
+void sigusr1_handler(int sig) {
+ if (sig == SIGUSR1)
+ g_sigusr1_count += 1; // Break here in signal handler
+}
+
+/// Register a simple function for to handle signal
+void register_signal_handler(int signal, void (*handler)(int))
+{
+ sigset_t empty_sigset;
+ sigemptyset(&empty_sigset);
+
+ struct sigaction action;
+ action.sa_sigaction = 0;
+ action.sa_mask = empty_sigset;
+ action.sa_flags = 0;
+ action.sa_handler = handler;
+ sigaction(SIGUSR1, &action, 0);
+}
+
+void start_threads(thread_vector& threads,
+ action_counts& actions,
+ void* args = 0) {
+ action_counts::iterator b = actions.begin(), e = actions.end();
+ for(action_counts::iterator i = b; i != e; ++i) {
+ for(unsigned count = 0; count < i->first; ++count) {
+ pthread_t t;
+ pthread_create(&t, 0, i->second, args);
+ threads.push_back(t);
+ }
+ }
+}
+
+int dotest()
+{
+ g_watchme = 0;
+
+ // Actions are triggered immediately after the thread is spawned
+ unsigned num_breakpoint_threads = 1;
+ unsigned num_watchpoint_threads = 0;
+ unsigned num_signal_threads = 1;
+ unsigned num_crash_threads = 0;
+
+ // Actions below are triggered after a 1-second delay
+ unsigned num_delay_breakpoint_threads = 0;
+ unsigned num_delay_watchpoint_threads = 0;
+ unsigned num_delay_signal_threads = 0;
+ unsigned num_delay_crash_threads = 0;
+
+ register_signal_handler(SIGUSR1, sigusr1_handler); // Break here and adjust num_[breakpoint|watchpoint|signal|crash]_threads
+
+ unsigned total_threads = num_breakpoint_threads \
+ + num_watchpoint_threads \
+ + num_signal_threads \
+ + num_crash_threads \
+ + num_delay_breakpoint_threads \
+ + num_delay_watchpoint_threads \
+ + num_delay_signal_threads \
+ + num_delay_crash_threads;
+
+ // Don't let either thread do anything until they're both ready.
+ pseudo_barrier_init(g_barrier, total_threads);
+
+ action_counts actions;
+ actions.push_back(std::make_pair(num_breakpoint_threads, breakpoint_func));
+ actions.push_back(std::make_pair(num_watchpoint_threads, watchpoint_func));
+ actions.push_back(std::make_pair(num_signal_threads, signal_func));
+ actions.push_back(std::make_pair(num_crash_threads, crash_func));
+
+ action_counts delay_actions;
+ delay_actions.push_back(std::make_pair(num_delay_breakpoint_threads, breakpoint_func));
+ delay_actions.push_back(std::make_pair(num_delay_watchpoint_threads, watchpoint_func));
+ delay_actions.push_back(std::make_pair(num_delay_signal_threads, signal_func));
+ delay_actions.push_back(std::make_pair(num_delay_crash_threads, crash_func));
+
+ // Create threads that handle instant actions
+ thread_vector threads;
+ start_threads(threads, actions);
+
+ // Create threads that handle delayed actions
+ action_args delay_arg;
+ delay_arg.delay = 1;
+ start_threads(threads, delay_actions, &delay_arg);
+
+ // Join all threads
+ typedef std::vector<pthread_t>::iterator thread_iterator;
+ for(thread_iterator t = threads.begin(); t != threads.end(); ++t)
+ pthread_join(*t, 0);
+
+ return 0;
+}
+
+int main ()
+{
+ dotest();
+ return 0; // Break here and verify one thread is active.
+}
+
+
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/Makefile b/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/Makefile
new file mode 100644
index 000000000000..26db4816b6ea
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/Makefile
@@ -0,0 +1,4 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/TestCrashDuringStep.py b/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/TestCrashDuringStep.py
new file mode 100644
index 000000000000..24b5bf0dad36
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/TestCrashDuringStep.py
@@ -0,0 +1,53 @@
+"""
+Test that step-inst over a crash behaves correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class CreateDuringStepTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ TestBase.setUp(self)
+ self.breakpoint = line_number('main.cpp', '// Set breakpoint here')
+
+ @expectedFailureWindows("llvm.org/pr24778")
+ @expectedFailureAndroid("llvm.org/pr24497", archs=['arm', 'aarch64'])
+ @expectedFailureAll(archs=['mips', 'mipsel', 'mips64', 'mips64el']) # IO error due to breakpoint at invalid address
+ def test_step_inst_with(self):
+ """Test thread creation during step-inst handling."""
+ self.build(dictionary=self.getBuildFlags())
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target and target.IsValid(), "Target is valid")
+
+ self.bp_num = lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.breakpoint, num_expected_locations=1)
+
+ # Run the program.
+ process = target.LaunchSimple(None, None, self.get_process_working_directory())
+ self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID)
+
+ # The stop reason should be breakpoint.
+ self.assertEqual(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED)
+ self.assertEqual(lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint).IsValid(), 1,
+ STOPPED_DUE_TO_BREAKPOINT)
+
+ thread = process.GetThreadAtIndex(0)
+ self.assertTrue(thread and thread.IsValid(), "Thread is valid")
+
+ # Keep stepping until the inferior crashes
+ while process.GetState() == lldb.eStateStopped and not lldbutil.is_thread_crashed(self, thread):
+ thread.StepInstruction(False)
+
+ self.assertEqual(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED)
+ self.assertTrue(lldbutil.is_thread_crashed(self, thread), "Thread has crashed")
+ process.Kill()
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/main.cpp b/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/main.cpp
new file mode 100644
index 000000000000..02f3ce338229
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/crash_during_step/main.cpp
@@ -0,0 +1,16 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+void (*crash)() = nullptr;
+
+int main()
+{
+ crash(); // Set breakpoint here
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/Makefile b/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/Makefile
new file mode 100644
index 000000000000..67aa16625bff
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+ENABLE_THREADS := YES
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/TestCreateAfterAttach.py b/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/TestCreateAfterAttach.py
new file mode 100644
index 000000000000..977254343aa0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/TestCreateAfterAttach.py
@@ -0,0 +1,122 @@
+"""
+Test thread creation after process attach.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class CreateAfterAttachTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfFreeBSD # Hangs. May be the same as Linux issue llvm.org/pr16229 but
+ # not yet investigated. Revisit once required functionality
+ # is implemented for FreeBSD.
+ @skipIfWindows # Occasionally hangs on Windows, may be same as other issues.
+ @skipIfiOSSimulator
+ def test_create_after_attach_with_popen(self):
+ """Test thread creation after process attach."""
+ self.build(dictionary=self.getBuildFlags(use_cpp11=False))
+ self.create_after_attach(use_fork=False)
+
+ @skipIfFreeBSD # Hangs. Revisit once required functionality is implemented
+ # for FreeBSD.
+ @skipIfRemote
+ @skipIfWindows # Windows doesn't have fork.
+ @expectedFlakeyLinux("llvm.org/pr16229") # 1/100 dosep, build 3546, clang-3.5 x84_64
+ @skipIfiOSSimulator
+ def test_create_after_attach_with_fork(self):
+ """Test thread creation after process attach."""
+ self.build(dictionary=self.getBuildFlags(use_cpp11=False))
+ self.create_after_attach(use_fork=True)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers for our breakpoints.
+ self.break_1 = line_number('main.cpp', '// Set first breakpoint here')
+ self.break_2 = line_number('main.cpp', '// Set second breakpoint here')
+ self.break_3 = line_number('main.cpp', '// Set third breakpoint here')
+
+ def create_after_attach(self, use_fork):
+ """Test thread creation after process attach."""
+
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Spawn a new process
+ if use_fork:
+ pid = self.forkSubprocess(exe)
+ else:
+ popen = self.spawnSubprocess(exe)
+ pid = popen.pid
+ self.addTearDownHook(self.cleanupSubprocesses)
+
+ # Attach to the spawned process
+ self.runCmd("process attach -p " + str(pid))
+
+ target = self.dbg.GetSelectedTarget()
+
+ process = target.GetProcess()
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # This should create a breakpoint in the main thread.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_1, num_expected_locations=1)
+
+ # This should create a breakpoint in the second child thread.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_2, num_expected_locations=1)
+
+ # This should create a breakpoint in the first child thread.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_3, num_expected_locations=1)
+
+ # Note: With std::thread, we cannot rely on particular thread numbers. Using
+ # std::thread may cause the program to spin up a thread pool (and it does on
+ # Windows), so the thread numbers are non-deterministic.
+
+ # Run to the first breakpoint
+ self.runCmd("continue")
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ '* thread #',
+ 'main',
+ 'stop reason = breakpoint'])
+
+ # Change a variable to escape the loop
+ self.runCmd("expression main_thread_continue = 1")
+
+ # Run to the second breakpoint
+ self.runCmd("continue")
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ '* thread #',
+ 'thread_2_func',
+ 'stop reason = breakpoint'])
+
+ # Change a variable to escape the loop
+ self.runCmd("expression child_thread_continue = 1")
+
+ # Run to the third breakpoint
+ self.runCmd("continue")
+
+ # The stop reason of the thread should be breakpoint.
+ # Thread 3 may or may not have already exited.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ '* thread #',
+ 'thread_1_func',
+ 'stop reason = breakpoint'])
+
+ # Run to completion
+ self.runCmd("continue")
+
+ # At this point, the inferior process should have exited.
+ self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED)
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/main.cpp b/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/main.cpp
new file mode 100644
index 000000000000..8434458f0648
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/create_after_attach/main.cpp
@@ -0,0 +1,78 @@
+#include <stdio.h>
+#include <chrono>
+#include <thread>
+
+using std::chrono::microseconds;
+
+#if defined(__linux__)
+#include <sys/prctl.h>
+#endif
+
+volatile int g_thread_2_continuing = 0;
+
+void *
+thread_1_func (void *input)
+{
+ // Waiting to be released by the debugger.
+ while (!g_thread_2_continuing) // Another thread will change this value
+ {
+ std::this_thread::sleep_for(microseconds(1));
+ }
+
+ // Return
+ return NULL; // Set third breakpoint here
+}
+
+void *
+thread_2_func (void *input)
+{
+ // Waiting to be released by the debugger.
+ int child_thread_continue = 0;
+ while (!child_thread_continue) // The debugger will change this value
+ {
+ std::this_thread::sleep_for(microseconds(1)); // Set second breakpoint here
+ }
+
+ // Release thread 1
+ g_thread_2_continuing = 1;
+
+ // Return
+ return NULL;
+}
+
+int main(int argc, char const *argv[])
+{
+#if defined(__linux__)
+ // Immediately enable any ptracer so that we can allow the stub attach
+ // operation to succeed. Some Linux kernels are locked down so that
+ // only an ancestor process can be a ptracer of a process. This disables that
+ // restriction. Without it, attach-related stub tests will fail.
+#if defined(PR_SET_PTRACER) && defined(PR_SET_PTRACER_ANY)
+ int prctl_result;
+
+ // For now we execute on best effort basis. If this fails for
+ // some reason, so be it.
+ prctl_result = prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
+ (void) prctl_result;
+#endif
+#endif
+
+ // Create a new thread
+ std::thread thread_1(thread_1_func, nullptr);
+
+ // Waiting to be attached by the debugger.
+ int main_thread_continue = 0;
+ while (!main_thread_continue) // The debugger will change this value
+ {
+ std::this_thread::sleep_for(microseconds(1)); // Set first breakpoint here
+ }
+
+ // Create another new thread
+ std::thread thread_2(thread_2_func, nullptr);
+
+ // Wait for the threads to finish.
+ thread_1.join();
+ thread_2.join();
+
+ printf("Exiting now\n");
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/Makefile b/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/Makefile
new file mode 100644
index 000000000000..67aa16625bff
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+ENABLE_THREADS := YES
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/TestCreateDuringStep.py b/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/TestCreateDuringStep.py
new file mode 100644
index 000000000000..046a86509c0f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/TestCreateDuringStep.py
@@ -0,0 +1,127 @@
+"""
+Test number of threads.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class CreateDuringStepTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureDarwin("llvm.org/pr15824") # thread states not properly maintained
+ @expectedFailureFreeBSD("llvm.org/pr18190") # thread states not properly maintained
+ @expectedFailureLinux("llvm.org/pr15824") # thread states not properly maintained
+ @expectedFailureWindows("llvm.org/pr24668") # Breakpoints not resolved correctly
+ def test_step_inst(self):
+ """Test thread creation during step-inst handling."""
+ self.build(dictionary=self.getBuildFlags())
+ self.create_during_step_base("thread step-inst -m all-threads", 'stop reason = instruction step')
+
+ @expectedFailureDarwin("llvm.org/pr15824") # thread states not properly maintained
+ @expectedFailureFreeBSD("llvm.org/pr18190") # thread states not properly maintained
+ @expectedFailureLinux("llvm.org/pr15824") # thread states not properly maintained
+ @expectedFailureWindows("llvm.org/pr24668") # Breakpoints not resolved correctly
+ def test_step_over(self):
+ """Test thread creation during step-over handling."""
+ self.build(dictionary=self.getBuildFlags())
+ self.create_during_step_base("thread step-over -m all-threads", 'stop reason = step over')
+
+ @expectedFailureDarwin("llvm.org/pr15824") # thread states not properly maintained
+ @expectedFailureFreeBSD("llvm.org/pr18190") # thread states not properly maintained
+ @expectedFailureLinux("llvm.org/pr15824") # thread states not properly maintained
+ @expectedFailureWindows("llvm.org/pr24668") # Breakpoints not resolved correctly
+ def test_step_in(self):
+ """Test thread creation during step-in handling."""
+ self.build(dictionary=self.getBuildFlags())
+ self.create_during_step_base("thread step-in -m all-threads", 'stop reason = step in')
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break and continue.
+ self.breakpoint = line_number('main.cpp', '// Set breakpoint here')
+ self.continuepoint = line_number('main.cpp', '// Continue from here')
+
+ def create_during_step_base(self, step_cmd, step_stop_reason):
+ """Test thread creation while using step-in."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # This should create a breakpoint in the stepping thread.
+ self.bp_num = lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.breakpoint, num_expected_locations=1)
+
+ # The breakpoint list should show 1 location.
+ self.expect("breakpoint list -f", "Breakpoint location shown correctly",
+ substrs = ["1: file = 'main.cpp', line = %d, locations = 1" % self.breakpoint])
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Get the target process
+ target = self.dbg.GetSelectedTarget()
+ process = target.GetProcess()
+
+ # Get the number of threads
+ num_threads = process.GetNumThreads()
+
+ # Make sure we see only two threads
+ self.assertTrue(num_threads == 2, 'Number of expected threads and actual threads do not match.')
+
+ # Get the thread objects
+ thread1 = process.GetThreadAtIndex(0)
+ thread2 = process.GetThreadAtIndex(1)
+
+ # Make sure both threads are stopped
+ self.assertTrue(thread1.IsStopped(), "Thread 1 didn't stop during breakpoint")
+ self.assertTrue(thread2.IsStopped(), "Thread 2 didn't stop during breakpoint")
+
+ # Find the thread that is stopped at the breakpoint
+ stepping_thread = None
+ for thread in process:
+ expected_bp_desc = "breakpoint %s." % self.bp_num
+ if expected_bp_desc in thread.GetStopDescription(100):
+ stepping_thread = thread
+ break
+ self.assertTrue(stepping_thread != None, "unable to find thread stopped at %s" % expected_bp_desc)
+ current_line = self.breakpoint
+ # Keep stepping until we've reached our designated continue point
+ while current_line != self.continuepoint:
+ if stepping_thread != process.GetSelectedThread():
+ process.SetSelectedThread(stepping_thread)
+
+ self.runCmd(step_cmd)
+
+ frame = stepping_thread.GetFrameAtIndex(0)
+ current_line = frame.GetLineEntry().GetLine()
+
+ # Make sure we're still where we thought we were
+ self.assertTrue(current_line >= self.breakpoint, "Stepped to unexpected line, " + str(current_line))
+ self.assertTrue(current_line <= self.continuepoint, "Stepped to unexpected line, " + str(current_line))
+
+ # Update the number of threads
+ num_threads = process.GetNumThreads()
+
+ # Check to see that we increased the number of threads as expected
+ self.assertTrue(num_threads == 3, 'Number of expected threads and actual threads do not match after thread exit.')
+
+ self.expect("thread list", 'Process state is stopped due to step',
+ substrs = ['stopped',
+ step_stop_reason])
+
+ # Run to completion
+ self.runCmd("process continue")
+
+ # At this point, the inferior process should have exited.
+ self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED)
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/main.cpp b/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/main.cpp
new file mode 100644
index 000000000000..3a00248c022a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/create_during_step/main.cpp
@@ -0,0 +1,89 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+// This test is intended to create a situation in which one thread will be
+// created while the debugger is stepping in another thread.
+
+#include <atomic>
+#include <thread>
+
+// Note that although hogging the CPU while waiting for a variable to change
+// would be terrible in production code, it's great for testing since it
+// avoids a lot of messy context switching to get multiple threads synchronized.
+#define do_nothing()
+
+#define pseudo_barrier_wait(bar) \
+ --bar; \
+ while (bar > 0) \
+ do_nothing();
+
+#define pseudo_barrier_init(bar, count) (bar = count)
+
+std::atomic_int g_barrier;
+
+volatile int g_thread_created = 0;
+volatile int g_test = 0;
+
+void *
+step_thread_func ()
+{
+ g_test = 0; // Set breakpoint here
+
+ while (!g_thread_created)
+ g_test++;
+
+ // One more time to provide a continue point
+ g_test++; // Continue from here
+
+ // Return
+ return NULL;
+}
+
+void *
+create_thread_func (void *input)
+{
+ std::thread *step_thread = (std::thread*)input;
+
+ // Wait until the main thread knows this thread is started.
+ pseudo_barrier_wait(g_barrier);
+
+ // Wait until the other thread is done.
+ step_thread->join();
+
+ // Return
+ return NULL;
+}
+
+int main ()
+{
+ // Use a simple count to simulate a barrier.
+ pseudo_barrier_init(g_barrier, 2);
+
+ // Create a thread to hit the breakpoint.
+ std::thread thread_1(step_thread_func);
+
+ // Wait until the step thread is stepping
+ while (g_test < 1)
+ do_nothing();
+
+ // Create a thread to exit while we're stepping.
+ std::thread thread_2(create_thread_func, &thread_1);
+
+ // Wait until that thread is started
+ pseudo_barrier_wait(g_barrier);
+
+ // Let the stepping thread know the other thread is there
+ g_thread_created = 1;
+
+ // Wait for the threads to finish.
+ thread_2.join();
+ thread_1.join();
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/Makefile b/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/Makefile
new file mode 100644
index 000000000000..67aa16625bff
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+ENABLE_THREADS := YES
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/TestExitDuringBreak.py b/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/TestExitDuringBreak.py
new file mode 100644
index 000000000000..f999ffe108f3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/TestExitDuringBreak.py
@@ -0,0 +1,81 @@
+"""
+Test number of threads.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ExitDuringBreakpointTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number for our breakpoint.
+ self.breakpoint = line_number('main.cpp', '// Set breakpoint here')
+
+ @expectedFailureDarwin("llvm.org/pr15824") # thread states not properly maintained
+ @expectedFailureFreeBSD("llvm.org/pr18190") # thread states not properly maintained
+ @expectedFailureLinux("llvm.org/pr15824") # thread states not properly maintained
+ @expectedFailureWindows("llvm.org/pr24668") # Breakpoints not resolved correctly
+ def test(self):
+ """Test thread exit during breakpoint handling."""
+ self.build(dictionary=self.getBuildFlags())
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # This should create a breakpoint in the main thread.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.breakpoint, num_expected_locations=1)
+
+ # The breakpoint list should show 1 location.
+ self.expect("breakpoint list -f", "Breakpoint location shown correctly",
+ substrs = ["1: file = 'main.cpp', line = %d, locations = 1" % self.breakpoint])
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Get the target process
+ target = self.dbg.GetSelectedTarget()
+ process = target.GetProcess()
+
+ # The exit probably occurred during breakpoint handling, but it isn't
+ # guaranteed. The main thing we're testing here is that the debugger
+ # handles this cleanly is some way.
+
+ # Get the number of threads
+ num_threads = process.GetNumThreads()
+
+ # Make sure we see at least five threads
+ self.assertTrue(num_threads >= 5, 'Number of expected threads and actual threads do not match.')
+
+ # Get the thread objects
+ thread1 = process.GetThreadAtIndex(0)
+ thread2 = process.GetThreadAtIndex(1)
+ thread3 = process.GetThreadAtIndex(2)
+ thread4 = process.GetThreadAtIndex(3)
+ thread5 = process.GetThreadAtIndex(4)
+
+ # Make sure all threads are stopped
+ self.assertTrue(thread1.IsStopped(), "Thread 1 didn't stop during breakpoint")
+ self.assertTrue(thread2.IsStopped(), "Thread 2 didn't stop during breakpoint")
+ self.assertTrue(thread3.IsStopped(), "Thread 3 didn't stop during breakpoint")
+ self.assertTrue(thread4.IsStopped(), "Thread 4 didn't stop during breakpoint")
+ self.assertTrue(thread5.IsStopped(), "Thread 5 didn't stop during breakpoint")
+
+ # Run to completion
+ self.runCmd("continue")
+
+ # At this point, the inferior process should have exited.
+ self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED)
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/main.cpp b/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/main.cpp
new file mode 100644
index 000000000000..3570637207d2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/exit_during_break/main.cpp
@@ -0,0 +1,130 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+// This test is intended to create a situation in which one thread will exit
+// while a breakpoint is being handled in another thread. This may not always
+// happen because it's possible that the exiting thread will exit before the
+// breakpoint is hit. The test case should be flexible enough to treat that
+// as success.
+
+#include <atomic>
+#include <chrono>
+#include <thread>
+
+volatile int g_test = 0;
+
+// Note that although hogging the CPU while waiting for a variable to change
+// would be terrible in production code, it's great for testing since it
+// avoids a lot of messy context switching to get multiple threads synchronized.
+#define do_nothing()
+
+#define pseudo_barrier_wait(bar) \
+ --bar; \
+ while (bar > 0) \
+ do_nothing();
+
+#define pseudo_barrier_init(bar, count) (bar = count)
+
+// A barrier to synchronize all the threads except the one that will exit.
+std::atomic_int g_barrier1;
+
+// A barrier to synchronize all the threads including the one that will exit.
+std::atomic_int g_barrier2;
+
+// A barrier to keep the first group of threads from exiting until after the
+// breakpoint has been passed.
+std::atomic_int g_barrier3;
+
+void *
+break_thread_func ()
+{
+ // Wait until the entire first group of threads is running
+ pseudo_barrier_wait(g_barrier1);
+
+ // Wait for the exiting thread to start
+ pseudo_barrier_wait(g_barrier2);
+
+ // Do something
+ g_test++; // Set breakpoint here
+
+ // Synchronize after the breakpoint
+ pseudo_barrier_wait(g_barrier3);
+
+ // Return
+ return NULL;
+}
+
+void *
+wait_thread_func ()
+{
+ // Wait until the entire first group of threads is running
+ pseudo_barrier_wait(g_barrier1);
+
+ // Wait for the exiting thread to start
+ pseudo_barrier_wait(g_barrier2);
+
+ // Wait until the breakpoint has been passed
+ pseudo_barrier_wait(g_barrier3);
+
+ // Return
+ return NULL;
+}
+
+void *
+exit_thread_func ()
+{
+ // Sync up with the rest of the threads.
+ pseudo_barrier_wait(g_barrier2);
+
+ // Try to make sure this thread doesn't exit until the breakpoint is hit.
+ std::this_thread::sleep_for(std::chrono::microseconds(1));
+
+ // Return
+ return NULL;
+}
+
+int main ()
+{
+
+ // The first barrier waits for the non-exiting threads to start.
+ // This thread will also participate in that barrier.
+ // The idea here is to guarantee that the exiting thread will be
+ // last in the internal list maintained by the debugger.
+ pseudo_barrier_init(g_barrier1, 5);
+
+ // The second break synchronyizes thread exection with the breakpoint.
+ pseudo_barrier_init(g_barrier2, 5);
+
+ // The third barrier keeps the waiting threads around until the breakpoint
+ // has been passed.
+ pseudo_barrier_init(g_barrier3, 4);
+
+ // Create a thread to hit the breakpoint
+ std::thread thread_1(break_thread_func);
+
+ // Create more threads to slow the debugger down during processing.
+ std::thread thread_2(wait_thread_func);
+ std::thread thread_3(wait_thread_func);
+ std::thread thread_4(wait_thread_func);
+
+ // Wait for all these threads to get started.
+ pseudo_barrier_wait(g_barrier1);
+
+ // Create a thread to exit during the breakpoint
+ std::thread thread_5(exit_thread_func);
+
+ // Wait for the threads to finish
+ thread_5.join();
+ thread_4.join();
+ thread_3.join();
+ thread_2.join();
+ thread_1.join();
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/Makefile b/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/Makefile
new file mode 100644
index 000000000000..d06a7d4685f3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+ENABLE_THREADS := YES
+CXX_SOURCES := main.cpp
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/TestExitDuringStep.py b/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/TestExitDuringStep.py
new file mode 100644
index 000000000000..67d1c96fd342
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/TestExitDuringStep.py
@@ -0,0 +1,144 @@
+"""
+Test number of threads.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ExitDuringStepTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureDarwin("llvm.org/pr15824") # thread states not properly maintained
+ @expectedFailureFreeBSD("llvm.org/pr18190") # thread states not properly maintained
+ @expectedFailureLinux("llvm.org/pr15824") # thread states not properly maintained
+ @expectedFailureWindows("llvm.org/pr24681")
+ def test_thread_state_is_stopped(self):
+ """Test thread exit during step handling."""
+ self.build(dictionary=self.getBuildFlags())
+ self.exit_during_step_base("thread step-in -m all-threads", 'stop reason = step in', True)
+
+ @skipIfFreeBSD # llvm.org/pr21411: test is hanging
+ @expectedFailureWindows("llvm.org/pr24681")
+ def test(self):
+ """Test thread exit during step handling."""
+ self.build(dictionary=self.getBuildFlags())
+ self.exit_during_step_base("thread step-inst -m all-threads", 'stop reason = instruction step', False)
+
+ @skipIfFreeBSD # llvm.org/pr21411: test is hanging
+ @expectedFailureWindows("llvm.org/pr24681")
+ def test_step_over(self):
+ """Test thread exit during step-over handling."""
+ self.build(dictionary=self.getBuildFlags())
+ self.exit_during_step_base("thread step-over -m all-threads", 'stop reason = step over', False)
+
+ @skipIfFreeBSD # llvm.org/pr21411: test is hanging
+ @expectedFailureWindows("llvm.org/pr24681")
+ def test_step_in(self):
+ """Test thread exit during step-in handling."""
+ self.build(dictionary=self.getBuildFlags())
+ self.exit_during_step_base("thread step-in -m all-threads", 'stop reason = step in', False)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break and continue.
+ self.breakpoint = line_number('main.cpp', '// Set breakpoint here')
+ self.continuepoint = line_number('main.cpp', '// Continue from here')
+
+ def exit_during_step_base(self, step_cmd, step_stop_reason, test_thread_state):
+ """Test thread exit during step handling."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # This should create a breakpoint in the main thread.
+ self.bp_num = lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.breakpoint, num_expected_locations=1)
+
+ # The breakpoint list should show 1 location.
+ self.expect("breakpoint list -f", "Breakpoint location shown correctly",
+ substrs = ["1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % self.breakpoint])
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Get the target process
+ target = self.dbg.GetSelectedTarget()
+ process = target.GetProcess()
+
+ # Get the number of threads
+ num_threads = process.GetNumThreads()
+
+ # Make sure we see all three threads
+ self.assertTrue(num_threads == 3, 'Number of expected threads and actual threads do not match.')
+
+ # Get the thread objects
+ thread1 = process.GetThreadAtIndex(0)
+ thread2 = process.GetThreadAtIndex(1)
+ thread3 = process.GetThreadAtIndex(2)
+
+ # Make sure all threads are stopped
+ if test_thread_state:
+ self.assertTrue(thread1.IsStopped(), "Thread 1 didn't stop during breakpoint")
+ self.assertTrue(thread2.IsStopped(), "Thread 2 didn't stop during breakpoint")
+ self.assertTrue(thread3.IsStopped(), "Thread 3 didn't stop during breakpoint")
+ return
+
+ # Find the thread that is stopped at the breakpoint
+ stepping_thread = None
+ for thread in process:
+ expected_bp_desc = "breakpoint %s." % self.bp_num
+ stop_desc = thread.GetStopDescription(100)
+ if stop_desc and (expected_bp_desc in stop_desc):
+ stepping_thread = thread
+ break
+ self.assertTrue(stepping_thread != None, "unable to find thread stopped at %s" % expected_bp_desc)
+
+ current_line = self.breakpoint
+ stepping_frame = stepping_thread.GetFrameAtIndex(0)
+ self.assertTrue(current_line == stepping_frame.GetLineEntry().GetLine(), "Starting line for stepping doesn't match breakpoint line.")
+
+ # Keep stepping until we've reached our designated continue point
+ while current_line != self.continuepoint:
+ # Since we're using the command interpreter to issue the thread command
+ # (on the selected thread) we need to ensure the selected thread is the
+ # stepping thread.
+ if stepping_thread != process.GetSelectedThread():
+ process.SetSelectedThread(stepping_thread)
+
+ self.runCmd(step_cmd)
+
+ frame = stepping_thread.GetFrameAtIndex(0)
+
+ current_line = frame.GetLineEntry().GetLine()
+
+ self.assertTrue(current_line >= self.breakpoint, "Stepped to unexpected line, " + str(current_line))
+ self.assertTrue(current_line <= self.continuepoint, "Stepped to unexpected line, " + str(current_line))
+
+ self.runCmd("thread list")
+
+ # Update the number of threads
+ num_threads = process.GetNumThreads()
+
+ # Check to see that we reduced the number of threads as expected
+ self.assertTrue(num_threads == 2, 'Number of expected threads and actual threads do not match after thread exit.')
+
+ self.expect("thread list", 'Process state is stopped due to step',
+ substrs = ['stopped',
+ step_stop_reason])
+
+ # Run to completion
+ self.runCmd("continue")
+
+ # At this point, the inferior process should have exited.
+ self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED)
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/main.cpp b/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/main.cpp
new file mode 100644
index 000000000000..d1b364b8baa2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/exit_during_step/main.cpp
@@ -0,0 +1,87 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+// This test is intended to create a situation in which one thread will exit
+// while the debugger is stepping in another thread.
+
+#include <thread>
+
+// Note that although hogging the CPU while waiting for a variable to change
+// would be terrible in production code, it's great for testing since it
+// avoids a lot of messy context switching to get multiple threads synchronized.
+#define do_nothing()
+
+#define pseudo_barrier_wait(bar) \
+ --bar; \
+ while (bar > 0) \
+ do_nothing();
+
+#define pseudo_barrier_init(bar, count) (bar = count)
+
+// A barrier to synchronize thread start.
+volatile int g_barrier;
+
+volatile int g_thread_exited = 0;
+
+volatile int g_test = 0;
+
+void *
+step_thread_func ()
+{
+ // Wait until both threads are started.
+ pseudo_barrier_wait(g_barrier);
+
+ g_test = 0; // Set breakpoint here
+
+ while (!g_thread_exited)
+ g_test++;
+
+ // One more time to provide a continue point
+ g_test++; // Continue from here
+
+ // Return
+ return NULL;
+}
+
+void *
+exit_thread_func ()
+{
+ // Wait until both threads are started.
+ pseudo_barrier_wait(g_barrier);
+
+ // Wait until the other thread is stepping.
+ while (g_test == 0)
+ do_nothing();
+
+ // Return
+ return NULL;
+}
+
+int main ()
+{
+ // Synchronize thread start so that doesn't happen during stepping.
+ pseudo_barrier_init(g_barrier, 2);
+
+ // Create a thread to hit the breakpoint.
+ std::thread thread_1(step_thread_func);
+
+ // Create a thread to exit while we're stepping.
+ std::thread thread_2(exit_thread_func);
+
+ // Wait for the exit thread to finish.
+ thread_2.join();
+
+ // Let the stepping thread know the other thread is gone.
+ g_thread_exited = 1;
+
+ // Wait for the stepping thread to finish.
+ thread_1.join();
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/jump/Makefile b/packages/Python/lldbsuite/test/functionalities/thread/jump/Makefile
new file mode 100644
index 000000000000..b726fc3695fd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/jump/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+ENABLE_THREADS := YES
+CXX_SOURCES := main.cpp other.cpp
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/jump/TestThreadJump.py b/packages/Python/lldbsuite/test/functionalities/thread/jump/TestThreadJump.py
new file mode 100644
index 000000000000..be49a210f0f0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/jump/TestThreadJump.py
@@ -0,0 +1,60 @@
+"""
+Test jumping to different places.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ThreadJumpTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test(self):
+ """Test thread jump handling."""
+ self.build(dictionary=self.getBuildFlags())
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Find the line numbers for our breakpoints.
+ self.mark1 = line_number('main.cpp', '// 1st marker')
+ self.mark2 = line_number('main.cpp', '// 2nd marker')
+ self.mark3 = line_number('main.cpp', '// 3rd marker')
+ self.mark4 = line_number('main.cpp', '// 4th marker')
+ self.mark5 = line_number('other.cpp', '// other marker')
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.mark3, num_expected_locations=1)
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint 1.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT + " 1",
+ substrs = ['stopped',
+ '* thread #1',
+ 'stop reason = breakpoint 1'])
+
+ self.do_min_test(self.mark3, self.mark1, "i", "4"); # Try the int path, force it to return 'a'
+ self.do_min_test(self.mark3, self.mark2, "i", "5"); # Try the int path, force it to return 'b'
+ self.do_min_test(self.mark4, self.mark1, "j", "7"); # Try the double path, force it to return 'a'
+ self.do_min_test(self.mark4, self.mark2, "j", "8"); # Try the double path, force it to return 'b'
+
+ # Try jumping to another function in a different file.
+ self.runCmd("thread jump --file other.cpp --line %i --force" % self.mark5)
+ self.expect("process status",
+ substrs = ["at other.cpp:%i" % self.mark5])
+
+ # Try jumping to another function (without forcing)
+ self.expect("j main.cpp:%i" % self.mark1, COMMAND_FAILED_AS_EXPECTED, error = True,
+ substrs = ["error"])
+
+ def do_min_test(self, start, jump, var, value):
+ self.runCmd("j %i" % start) # jump to the start marker
+ self.runCmd("thread step-in") # step into the min fn
+ self.runCmd("j %i" % jump) # jump to the branch we're interested in
+ self.runCmd("thread step-out") # return out
+ self.runCmd("thread step-over") # assign to the global
+ self.expect("expr %s" % var, substrs = [value]) # check it
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/jump/main.cpp b/packages/Python/lldbsuite/test/functionalities/thread/jump/main.cpp
new file mode 100644
index 000000000000..3497155a98f2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/jump/main.cpp
@@ -0,0 +1,35 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+// This test verifies the correct handling of program counter jumps.
+
+int otherfn();
+
+template<typename T>
+T min(T a, T b)
+{
+ if (a < b)
+ {
+ return a; // 1st marker
+ } else {
+ return b; // 2nd marker
+ }
+}
+
+int main ()
+{
+ int i;
+ double j;
+ int min_i_a = 4, min_i_b = 5;
+ double min_j_a = 7.0, min_j_b = 8.0;
+ i = min(min_i_a, min_i_b); // 3rd marker
+ j = min(min_j_a, min_j_b); // 4th marker
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/jump/other.cpp b/packages/Python/lldbsuite/test/functionalities/thread/jump/other.cpp
new file mode 100644
index 000000000000..8108a52c163d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/jump/other.cpp
@@ -0,0 +1,13 @@
+//===-- other.cpp -----------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+int otherfn()
+{
+ return 4; // other marker
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/main.cpp b/packages/Python/lldbsuite/test/functionalities/thread/main.cpp
new file mode 100644
index 000000000000..6a0ea4e0d119
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/main.cpp
@@ -0,0 +1,50 @@
+#include <condition_variable>
+#include <mutex>
+#include <thread>
+
+std::mutex mutex;
+std::condition_variable cond;
+
+void *
+thread3(void *input)
+{
+ std::unique_lock<std::mutex> lock(mutex);
+ cond.notify_all(); // Set break point at this line.
+ return NULL;
+}
+
+void *
+thread2(void *input)
+{
+ std::unique_lock<std::mutex> lock(mutex);
+ cond.notify_all();
+ cond.wait(lock);
+ return NULL;
+}
+
+void *
+thread1(void *input)
+{
+ std::thread thread_2(thread2, nullptr);
+ thread_2.join();
+
+ return NULL;
+}
+
+int main()
+{
+ std::unique_lock<std::mutex> lock(mutex);
+
+ std::thread thread_1(thread1, nullptr);
+ cond.wait(lock);
+
+ std::thread thread_3(thread3, nullptr);
+ cond.wait(lock);
+
+ lock.unlock();
+
+ thread_1.join();
+ thread_3.join();
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/multi_break/Makefile b/packages/Python/lldbsuite/test/functionalities/thread/multi_break/Makefile
new file mode 100644
index 000000000000..67aa16625bff
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/multi_break/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+ENABLE_THREADS := YES
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/multi_break/TestMultipleBreakpoints.py b/packages/Python/lldbsuite/test/functionalities/thread/multi_break/TestMultipleBreakpoints.py
new file mode 100644
index 000000000000..9dd212412216
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/multi_break/TestMultipleBreakpoints.py
@@ -0,0 +1,77 @@
+"""
+Test number of threads.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class MultipleBreakpointTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number for our breakpoint.
+ self.breakpoint = line_number('main.cpp', '// Set breakpoint here')
+
+ @expectedFailureDarwin("llvm.org/pr15824") # thread states not properly maintained
+ @expectedFailureFreeBSD("llvm.org/pr18190") # thread states not properly maintained
+ @expectedFailureLinux("llvm.org/pr15824") # thread states not properly maintained
+ @expectedFailureWindows("llvm.org/pr24668") # Breakpoints not resolved correctly
+ def test(self):
+ """Test simultaneous breakpoints in multiple threads."""
+ self.build(dictionary=self.getBuildFlags())
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # This should create a breakpoint in the main thread.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.breakpoint, num_expected_locations=1)
+
+ # The breakpoint list should show 1 location.
+ self.expect("breakpoint list -f", "Breakpoint location shown correctly",
+ substrs = ["1: file = 'main.cpp', line = %d, locations = 1" % self.breakpoint])
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ # The breakpoint may be hit in either thread 2 or thread 3.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Get the target process
+ target = self.dbg.GetSelectedTarget()
+ process = target.GetProcess()
+
+ # Get the number of threads
+ num_threads = process.GetNumThreads()
+
+ # Make sure we see all three threads
+ self.assertTrue(num_threads == 3, 'Number of expected threads and actual threads do not match.')
+
+ # Get the thread objects
+ thread1 = process.GetThreadAtIndex(0)
+ thread2 = process.GetThreadAtIndex(1)
+ thread3 = process.GetThreadAtIndex(2)
+
+ # Make sure both threads are stopped
+ self.assertTrue(thread1.IsStopped(), "Primary thread didn't stop during breakpoint")
+ self.assertTrue(thread2.IsStopped(), "Secondary thread didn't stop during breakpoint")
+ self.assertTrue(thread3.IsStopped(), "Tertiary thread didn't stop during breakpoint")
+
+ # Delete the first breakpoint then continue
+ self.runCmd("breakpoint delete 1")
+
+ # Run to completion
+ self.runCmd("continue")
+
+ # At this point, the inferior process should have exited.
+ self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED)
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/multi_break/main.cpp b/packages/Python/lldbsuite/test/functionalities/thread/multi_break/main.cpp
new file mode 100644
index 000000000000..01f4b8f98ea7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/multi_break/main.cpp
@@ -0,0 +1,61 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+// This test is intended to create a situation in which a breakpoint will be
+// hit in two threads at nearly the same moment. The expected result is that
+// the breakpoint in the second thread will be hit while the breakpoint handler
+// in the first thread is trying to stop all threads.
+
+#include <atomic>
+#include <thread>
+
+// Note that although hogging the CPU while waiting for a variable to change
+// would be terrible in production code, it's great for testing since it
+// avoids a lot of messy context switching to get multiple threads synchronized.
+#define do_nothing()
+
+#define pseudo_barrier_wait(bar) \
+ --bar; \
+ while (bar > 0) \
+ do_nothing();
+
+#define pseudo_barrier_init(bar, count) (bar = count)
+
+std::atomic_int g_barrier;
+
+volatile int g_test = 0;
+
+void *
+thread_func ()
+{
+ // Wait until both threads are running
+ pseudo_barrier_wait(g_barrier);
+
+ // Do something
+ g_test++; // Set breakpoint here
+
+ // Return
+ return NULL;
+}
+
+int main ()
+{
+ // Don't let either thread do anything until they're both ready.
+ pseudo_barrier_init(g_barrier, 2);
+
+ // Create two threads
+ std::thread thread_1(thread_func);
+ std::thread thread_2(thread_func);
+
+ // Wait for the threads to finish
+ thread_1.join();
+ thread_2.join();
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/state/Makefile b/packages/Python/lldbsuite/test/functionalities/thread/state/Makefile
new file mode 100644
index 000000000000..26db4816b6ea
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/state/Makefile
@@ -0,0 +1,4 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/state/TestThreadStates.py b/packages/Python/lldbsuite/test/functionalities/thread/state/TestThreadStates.py
new file mode 100644
index 000000000000..623c659ffa5c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/state/TestThreadStates.py
@@ -0,0 +1,333 @@
+"""
+Test thread states.
+"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ThreadStateTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureDarwin("rdar://15367566")
+ @expectedFailureFreeBSD('llvm.org/pr15824')
+ @expectedFailureLinux("llvm.org/pr15824") # thread states not properly maintained
+ @expectedFailureWindows("llvm.org/pr24668") # Breakpoints not resolved correctly
+ def test_state_after_breakpoint(self):
+ """Test thread state after breakpoint."""
+ self.build(dictionary=self.getBuildFlags(use_cpp11=False))
+ self.thread_state_after_breakpoint_test()
+
+ @skipIfDarwin # 'llvm.org/pr23669', cause Python crash randomly
+ @expectedFailureDarwin('llvm.org/pr23669')
+ @expectedFailureFreeBSD('llvm.org/pr15824')
+ @expectedFailureWindows("llvm.org/pr24660")
+ def test_state_after_continue(self):
+ """Test thread state after continue."""
+ self.build(dictionary=self.getBuildFlags(use_cpp11=False))
+ self.thread_state_after_continue_test()
+
+ @skipIfDarwin # 'llvm.org/pr23669', cause Python crash randomly
+ @expectedFailureDarwin('llvm.org/pr23669')
+ @expectedFailureWindows("llvm.org/pr24660")
+ @unittest2.expectedFailure("llvm.org/pr16712") # thread states not properly maintained
+ def test_state_after_expression(self):
+ """Test thread state after expression."""
+ self.build(dictionary=self.getBuildFlags(use_cpp11=False))
+ self.thread_state_after_expression_test()
+
+ @unittest2.expectedFailure("llvm.org/pr16712") # thread states not properly maintained
+ @expectedFailureWindows("llvm.org/pr24668") # Breakpoints not resolved correctly
+ def test_process_interrupt(self):
+ """Test process interrupt."""
+ self.build(dictionary=self.getBuildFlags(use_cpp11=False))
+ self.process_interrupt_test()
+
+ @unittest2.expectedFailure("llvm.org/pr15824") # thread states not properly maintained
+ @expectedFailureWindows("llvm.org/pr24668") # Breakpoints not resolved correctly
+ def test_process_state(self):
+ """Test thread states (comprehensive)."""
+ self.build(dictionary=self.getBuildFlags(use_cpp11=False))
+ self.thread_states_test()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers for our breakpoints.
+ self.break_1 = line_number('main.cpp', '// Set first breakpoint here')
+ self.break_2 = line_number('main.cpp', '// Set second breakpoint here')
+
+ def thread_state_after_breakpoint_test(self):
+ """Test thread state after breakpoint."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # This should create a breakpoint in the main thread.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_1, num_expected_locations=1)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ '* thread #1',
+ 'stop reason = breakpoint'])
+
+ # Get the target process
+ target = self.dbg.GetSelectedTarget()
+ process = target.GetProcess()
+
+ # Get the number of threads
+ num_threads = process.GetNumThreads()
+
+ self.assertTrue(num_threads == 1, 'Number of expected threads and actual threads do not match.')
+
+ # Get the thread object
+ thread = process.GetThreadAtIndex(0)
+
+ # Make sure the thread is in the stopped state.
+ self.assertTrue(thread.IsStopped(), "Thread state isn't \'stopped\' during breakpoint 1.")
+ self.assertFalse(thread.IsSuspended(), "Thread state is \'suspended\' during breakpoint 1.")
+
+ # Kill the process
+ self.runCmd("process kill")
+
+ def wait_for_running_event(self):
+ listener = self.dbg.GetListener()
+ if lldb.remote_platform:
+ lldbutil.expect_state_changes(self, listener, [lldb.eStateConnected])
+ lldbutil.expect_state_changes(self, listener, [lldb.eStateRunning])
+
+ def thread_state_after_continue_test(self):
+ """Test thread state after continue."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # This should create a breakpoint in the main thread.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_1, num_expected_locations=1)
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_2, num_expected_locations=1)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ '* thread #1',
+ 'stop reason = breakpoint'])
+
+ # Get the target process
+ target = self.dbg.GetSelectedTarget()
+ process = target.GetProcess()
+
+ # Get the number of threads
+ num_threads = process.GetNumThreads()
+
+ self.assertTrue(num_threads == 1, 'Number of expected threads and actual threads do not match.')
+
+ # Get the thread object
+ thread = process.GetThreadAtIndex(0)
+
+ # Continue, the inferior will go into an infinite loop waiting for 'g_test' to change.
+ self.dbg.SetAsync(True)
+ self.runCmd("continue")
+ self.wait_for_running_event()
+
+ # Check the thread state. It should be running.
+ self.assertFalse(thread.IsStopped(), "Thread state is \'stopped\' when it should be running.")
+ self.assertFalse(thread.IsSuspended(), "Thread state is \'suspended\' when it should be running.")
+
+ # Go back to synchronous interactions
+ self.dbg.SetAsync(False)
+
+ # Kill the process
+ self.runCmd("process kill")
+
+ def thread_state_after_expression_test(self):
+ """Test thread state after expression."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # This should create a breakpoint in the main thread.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_1, num_expected_locations=1)
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_2, num_expected_locations=1)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ '* thread #1',
+ 'stop reason = breakpoint'])
+
+ # Get the target process
+ target = self.dbg.GetSelectedTarget()
+ process = target.GetProcess()
+
+ # Get the number of threads
+ num_threads = process.GetNumThreads()
+
+ self.assertTrue(num_threads == 1, 'Number of expected threads and actual threads do not match.')
+
+ # Get the thread object
+ thread = process.GetThreadAtIndex(0)
+
+ # Get the inferior out of its loop
+ self.runCmd("expression g_test = 1")
+
+ # Check the thread state
+ self.assertTrue(thread.IsStopped(), "Thread state isn't \'stopped\' after expression evaluation.")
+ self.assertFalse(thread.IsSuspended(), "Thread state is \'suspended\' after expression evaluation.")
+
+ # Let the process run to completion
+ self.runCmd("process continue")
+
+
+ def process_interrupt_test(self):
+ """Test process interrupt and continue."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # This should create a breakpoint in the main thread.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_1, num_expected_locations=1)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ '* thread #1',
+ 'stop reason = breakpoint'])
+
+ # Get the target process
+ target = self.dbg.GetSelectedTarget()
+ process = target.GetProcess()
+
+ # Get the number of threads
+ num_threads = process.GetNumThreads()
+
+ self.assertTrue(num_threads == 1, 'Number of expected threads and actual threads do not match.')
+
+ # Continue, the inferior will go into an infinite loop waiting for 'g_test' to change.
+ self.dbg.SetAsync(True)
+ self.runCmd("continue")
+ self.wait_for_running_event()
+
+ # Go back to synchronous interactions
+ self.dbg.SetAsync(False)
+
+ # Stop the process
+ self.runCmd("process interrupt")
+
+ # The stop reason of the thread should be signal.
+ self.expect("process status", STOPPED_DUE_TO_SIGNAL,
+ substrs = ['stopped',
+ '* thread #1',
+ 'stop reason = signal'])
+
+ # Get the inferior out of its loop
+ self.runCmd("expression g_test = 1")
+
+ # Run to completion
+ self.runCmd("continue")
+
+ def thread_states_test(self):
+ """Test thread states (comprehensive)."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # This should create a breakpoint in the main thread.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_1, num_expected_locations=1)
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_2, num_expected_locations=1)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ '* thread #1',
+ 'stop reason = breakpoint'])
+
+ # Get the target process
+ target = self.dbg.GetSelectedTarget()
+ process = target.GetProcess()
+
+ # Get the number of threads
+ num_threads = process.GetNumThreads()
+
+ self.assertTrue(num_threads == 1, 'Number of expected threads and actual threads do not match.')
+
+ # Get the thread object
+ thread = process.GetThreadAtIndex(0)
+
+ # Make sure the thread is in the stopped state.
+ self.assertTrue(thread.IsStopped(), "Thread state isn't \'stopped\' during breakpoint 1.")
+ self.assertFalse(thread.IsSuspended(), "Thread state is \'suspended\' during breakpoint 1.")
+
+ # Continue, the inferior will go into an infinite loop waiting for 'g_test' to change.
+ self.dbg.SetAsync(True)
+ self.runCmd("continue")
+ self.wait_for_running_event()
+
+ # Check the thread state. It should be running.
+ self.assertFalse(thread.IsStopped(), "Thread state is \'stopped\' when it should be running.")
+ self.assertFalse(thread.IsSuspended(), "Thread state is \'suspended\' when it should be running.")
+
+ # Go back to synchronous interactions
+ self.dbg.SetAsync(False)
+
+ # Stop the process
+ self.runCmd("process interrupt")
+
+ # The stop reason of the thread should be signal.
+ self.expect("process status", STOPPED_DUE_TO_SIGNAL,
+ substrs = ['stopped',
+ '* thread #1',
+ 'stop reason = signal'])
+
+ # Check the thread state
+ self.assertTrue(thread.IsStopped(), "Thread state isn't \'stopped\' after process stop.")
+ self.assertFalse(thread.IsSuspended(), "Thread state is \'suspended\' after process stop.")
+
+ # Get the inferior out of its loop
+ self.runCmd("expression g_test = 1")
+
+ # Check the thread state
+ self.assertTrue(thread.IsStopped(), "Thread state isn't \'stopped\' after expression evaluation.")
+ self.assertFalse(thread.IsSuspended(), "Thread state is \'suspended\' after expression evaluation.")
+
+ # The stop reason of the thread should be signal.
+ self.expect("process status", STOPPED_DUE_TO_SIGNAL,
+ substrs = ['stopped',
+ '* thread #1',
+ 'stop reason = signal'])
+
+ # Run to breakpoint 2
+ self.runCmd("continue")
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ '* thread #1',
+ 'stop reason = breakpoint'])
+
+ # Make sure both threads are stopped
+ self.assertTrue(thread.IsStopped(), "Thread state isn't \'stopped\' during breakpoint 2.")
+ self.assertFalse(thread.IsSuspended(), "Thread state is \'suspended\' during breakpoint 2.")
+
+ # Run to completion
+ self.runCmd("continue")
+
+ # At this point, the inferior process should have exited.
+ self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED)
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/state/main.cpp b/packages/Python/lldbsuite/test/functionalities/thread/state/main.cpp
new file mode 100644
index 000000000000..081203da8da9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/state/main.cpp
@@ -0,0 +1,45 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+// This test is intended to verify that thread states are properly maintained
+// when transitional actions are performed in the debugger. Most of the logic
+// is in the test script. This program merely provides places where the test
+// can create the intended states.
+
+#include <chrono>
+#include <thread>
+
+volatile int g_test = 0;
+
+int addSomething(int a)
+{
+ return a + g_test;
+}
+
+int doNothing()
+{
+ int temp = 0; // Set first breakpoint here
+
+ while (!g_test && temp < 5)
+ {
+ ++temp;
+ std::this_thread::sleep_for(std::chrono::seconds(2));
+ }
+
+ return temp; // Set second breakpoint here
+}
+
+int main ()
+{
+ int result = doNothing();
+
+ int i = addSomething(result);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/step_out/Makefile b/packages/Python/lldbsuite/test/functionalities/thread/step_out/Makefile
new file mode 100644
index 000000000000..035413ff763d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/step_out/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+ENABLE_THREADS := YES
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/step_out/TestThreadStepOut.py b/packages/Python/lldbsuite/test/functionalities/thread/step_out/TestThreadStepOut.py
new file mode 100644
index 000000000000..b2d966c4c0f3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/step_out/TestThreadStepOut.py
@@ -0,0 +1,131 @@
+"""
+Test stepping out from a function in a multi-threaded program.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ThreadStepOutTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfLinux # Test occasionally times out on the Linux build bot
+ @expectedFailureLinux("llvm.org/pr23477") # Test occasionally times out on the Linux build bot
+ @expectedFailureFreeBSD("llvm.org/pr18066") # inferior does not exit
+ @expectedFailureWindows # Test crashes
+ def test_step_single_thread(self):
+ """Test thread step out on one thread via command interpreter. """
+ self.build(dictionary=self.getBuildFlags())
+ self.step_out_test(self.step_out_single_thread_with_cmd)
+
+ @skipIfLinux # Test occasionally times out on the Linux build bot
+ @expectedFailureLinux("llvm.org/pr23477") # Test occasionally times out on the Linux build bot
+ @expectedFailureFreeBSD("llvm.org/pr19347") # 2nd thread stops at breakpoint
+ @expectedFailureWindows # Test crashes
+ def test_step_all_threads(self):
+ """Test thread step out on all threads via command interpreter. """
+ self.build(dictionary=self.getBuildFlags())
+ self.step_out_test(self.step_out_all_threads_with_cmd)
+
+ @skipIfLinux # Test occasionally times out on the Linux build bot
+ @expectedFailureLinux("llvm.org/pr23477") # Test occasionally times out on the Linux build bot
+ @expectedFailureFreeBSD("llvm.org/pr19347")
+ @expectedFailureWindows("llvm.org/pr24681")
+ def test_python(self):
+ """Test thread step out on one thread via Python API (dwarf)."""
+ self.build(dictionary=self.getBuildFlags())
+ self.step_out_test(self.step_out_with_python)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number for our breakpoint.
+ self.breakpoint = line_number('main.cpp', '// Set breakpoint here')
+ if "gcc" in self.getCompiler() or self.isIntelCompiler():
+ self.step_out_destination = line_number('main.cpp', '// Expect to stop here after step-out (icc and gcc)')
+ else:
+ self.step_out_destination = line_number('main.cpp', '// Expect to stop here after step-out (clang)')
+
+ def step_out_single_thread_with_cmd(self):
+ self.step_out_with_cmd("this-thread")
+ self.expect("thread backtrace all", "Thread location after step out is correct",
+ substrs = ["main.cpp:%d" % self.step_out_destination,
+ "main.cpp:%d" % self.breakpoint])
+
+ def step_out_all_threads_with_cmd(self):
+ self.step_out_with_cmd("all-threads")
+ self.expect("thread backtrace all", "Thread location after step out is correct",
+ substrs = ["main.cpp:%d" % self.step_out_destination])
+
+ def step_out_with_cmd(self, run_mode):
+ self.runCmd("thread select %d" % self.step_out_thread.GetIndexID())
+ self.runCmd("thread step-out -m %s" % run_mode)
+ self.expect("process status", "Expected stop reason to be step-out",
+ substrs = ["stop reason = step out"])
+
+ self.expect("thread list", "Selected thread did not change during step-out",
+ substrs = ["* thread #%d" % self.step_out_thread.GetIndexID()])
+
+ def step_out_with_python(self):
+ self.step_out_thread.StepOut()
+
+ reason = self.step_out_thread.GetStopReason()
+ self.assertEqual(lldb.eStopReasonPlanComplete, reason,
+ "Expected thread stop reason 'plancomplete', but got '%s'" % lldbutil.stop_reason_to_str(reason))
+
+ # Verify location after stepping out
+ frame = self.step_out_thread.GetFrameAtIndex(0)
+ desc = lldbutil.get_description(frame.GetLineEntry())
+ expect = "main.cpp:%d" % self.step_out_destination
+ self.assertTrue(expect in desc, "Expected %s but thread stopped at %s" % (expect, desc))
+
+ def step_out_test(self, step_out_func):
+ """Test single thread step out of a function."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # This should create a breakpoint in the main thread.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.breakpoint, num_expected_locations=1)
+
+ # The breakpoint list should show 1 location.
+ self.expect("breakpoint list -f", "Breakpoint location shown correctly",
+ substrs = ["1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % self.breakpoint])
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Get the target process
+ self.inferior_target = self.dbg.GetSelectedTarget()
+ self.inferior_process = self.inferior_target.GetProcess()
+
+ # Get the number of threads, ensure we see all three.
+ num_threads = self.inferior_process.GetNumThreads()
+ self.assertEqual(num_threads, 3, 'Number of expected threads and actual threads do not match.')
+
+ (breakpoint_threads, other_threads) = ([], [])
+ lldbutil.sort_stopped_threads(self.inferior_process,
+ breakpoint_threads=breakpoint_threads,
+ other_threads=other_threads)
+
+ while len(breakpoint_threads) < 2:
+ self.runCmd("thread continue %s" % " ".join([str(x.GetIndexID()) for x in other_threads]))
+ lldbutil.sort_stopped_threads(self.inferior_process,
+ breakpoint_threads=breakpoint_threads,
+ other_threads=other_threads)
+
+ self.step_out_thread = breakpoint_threads[0]
+
+ # Step out of thread stopped at breakpoint
+ step_out_func()
+
+ # Run to completion
+ self.runCmd("continue")
+
+ # At this point, the inferior process should have exited.
+ self.assertTrue(self.inferior_process.GetState() == lldb.eStateExited, PROCESS_EXITED)
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/step_out/main.cpp b/packages/Python/lldbsuite/test/functionalities/thread/step_out/main.cpp
new file mode 100644
index 000000000000..b4c6216d6bfe
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/step_out/main.cpp
@@ -0,0 +1,63 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+// This test is intended to create a situation in which two threads are stopped
+// at a breakpoint and the debugger issues a step-out command.
+
+#include <atomic>
+#include <thread>
+
+// Note that although hogging the CPU while waiting for a variable to change
+// would be terrible in production code, it's great for testing since it
+// avoids a lot of messy context switching to get multiple threads synchronized.
+#define do_nothing()
+
+#define pseudo_barrier_wait(bar) \
+ --bar; \
+ while (bar > 0) \
+ do_nothing();
+
+#define pseudo_barrier_init(bar, count) (bar = count)
+
+std::atomic_int g_barrier;
+
+volatile int g_test = 0;
+
+void step_out_of_here() {
+ g_test += 5; // Set breakpoint here
+}
+
+void *
+thread_func ()
+{
+ // Wait until both threads are running
+ pseudo_barrier_wait(g_barrier);
+
+ // Do something
+ step_out_of_here(); // Expect to stop here after step-out (clang)
+
+ // Return
+ return NULL; // Expect to stop here after step-out (icc and gcc)
+}
+
+int main ()
+{
+ // Don't let either thread do anything until they're both ready.
+ pseudo_barrier_init(g_barrier, 2);
+
+ // Create two threads
+ std::thread thread_1(thread_func);
+ std::thread thread_2(thread_func);
+
+ // Wait for the threads to finish
+ thread_1.join();
+ thread_2.join();
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/Makefile b/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/Makefile
new file mode 100644
index 000000000000..d06a7d4685f3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+ENABLE_THREADS := YES
+CXX_SOURCES := main.cpp
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/TestThreadExit.py b/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/TestThreadExit.py
new file mode 100644
index 000000000000..f785401277a4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/TestThreadExit.py
@@ -0,0 +1,116 @@
+"""
+Test number of threads.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ThreadExitTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers for our breakpoints.
+ self.break_1 = line_number('main.cpp', '// Set first breakpoint here')
+ self.break_2 = line_number('main.cpp', '// Set second breakpoint here')
+ self.break_3 = line_number('main.cpp', '// Set third breakpoint here')
+ self.break_4 = line_number('main.cpp', '// Set fourth breakpoint here')
+
+ @expectedFailureWindows("llvm.org/pr24681")
+ def test(self):
+ """Test thread exit handling."""
+ self.build(dictionary=self.getBuildFlags())
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # This should create a breakpoint with 1 location.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_1, num_expected_locations=1)
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_2, num_expected_locations=1)
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_3, num_expected_locations=1)
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.break_4, num_expected_locations=1)
+
+ # The breakpoint list should show 1 locations.
+ self.expect("breakpoint list -f", "Breakpoint location shown correctly",
+ substrs = ["1: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % self.break_1,
+ "2: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % self.break_2,
+ "3: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % self.break_3,
+ "4: file = 'main.cpp', line = %d, exact_match = 0, locations = 1" % self.break_4])
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint 1.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT + " 1",
+ substrs = ['stopped',
+ '* thread #1',
+ 'stop reason = breakpoint 1',
+ 'thread #2'])
+
+ # Get the target process
+ target = self.dbg.GetSelectedTarget()
+ process = target.GetProcess()
+
+ # Get the number of threads
+ num_threads = process.GetNumThreads()
+
+ self.assertTrue(num_threads == 2, 'Number of expected threads and actual threads do not match at breakpoint 1.')
+
+ # Run to the second breakpoint
+ self.runCmd("continue")
+
+ # The stop reason of the thread should be breakpoint 1.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT + " 2",
+ substrs = ['stopped',
+ 'thread #1',
+ 'thread #2',
+ 'stop reason = breakpoint 2',
+ 'thread #3'])
+
+ # Update the number of threads
+ num_threads = process.GetNumThreads()
+
+ self.assertTrue(num_threads == 3, 'Number of expected threads and actual threads do not match at breakpoint 2.')
+
+ # Run to the third breakpoint
+ self.runCmd("continue")
+
+ # The stop reason of the thread should be breakpoint 3.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT + " 3",
+ substrs = ['stopped',
+ 'thread #1',
+ 'stop reason = breakpoint 3',
+ 'thread #3',
+ ])
+
+ # Update the number of threads
+ num_threads = process.GetNumThreads()
+
+ self.assertTrue(num_threads == 2, 'Number of expected threads and actual threads do not match at breakpoint 3.')
+
+ # Run to the fourth breakpoint
+ self.runCmd("continue")
+
+ # The stop reason of the thread should be breakpoint 4.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT + " 4",
+ substrs = ['stopped',
+ 'thread #1',
+ 'stop reason = breakpoint 4'])
+
+ # Update the number of threads
+ num_threads = process.GetNumThreads()
+
+ self.assertTrue(num_threads == 1, 'Number of expected threads and actual threads do not match at breakpoint 4.')
+
+ # Run to completion
+ self.runCmd("continue")
+
+ # At this point, the inferior process should have exited.
+ self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED)
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/main.cpp b/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/main.cpp
new file mode 100644
index 000000000000..e498db7895d2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/thread_exit/main.cpp
@@ -0,0 +1,85 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+// This test verifies the correct handling of child thread exits.
+
+#include <atomic>
+#include <thread>
+
+// Note that although hogging the CPU while waiting for a variable to change
+// would be terrible in production code, it's great for testing since it
+// avoids a lot of messy context switching to get multiple threads synchronized.
+#define do_nothing()
+
+#define pseudo_barrier_wait(bar) \
+ --bar; \
+ while (bar > 0) \
+ do_nothing();
+
+#define pseudo_barrier_init(bar, count) (bar = count)
+
+std::atomic_int g_barrier1;
+std::atomic_int g_barrier2;
+std::atomic_int g_barrier3;
+
+void *
+thread1 ()
+{
+ // Synchronize with the main thread.
+ pseudo_barrier_wait(g_barrier1);
+
+ // Synchronize with the main thread and thread2.
+ pseudo_barrier_wait(g_barrier2);
+
+ // Return
+ return NULL; // Set second breakpoint here
+}
+
+void *
+thread2 ()
+{
+ // Synchronize with thread1 and the main thread.
+ pseudo_barrier_wait(g_barrier2);
+
+ // Synchronize with the main thread.
+ pseudo_barrier_wait(g_barrier3);
+
+ // Return
+ return NULL;
+}
+
+int main ()
+{
+ pseudo_barrier_init(g_barrier1, 2);
+ pseudo_barrier_init(g_barrier2, 3);
+ pseudo_barrier_init(g_barrier3, 2);
+
+ // Create a thread.
+ std::thread thread_1(thread1);
+
+ // Wait for thread1 to start.
+ pseudo_barrier_wait(g_barrier1);
+
+ // Create another thread.
+ std::thread thread_2(thread2); // Set first breakpoint here
+
+ // Wait for thread2 to start.
+ pseudo_barrier_wait(g_barrier2);
+
+ // Wait for the first thread to finish
+ thread_1.join();
+
+ // Synchronize with the remaining thread
+ pseudo_barrier_wait(g_barrier3); // Set third breakpoint here
+
+ // Wait for the second thread to finish
+ thread_2.join();
+
+ return 0; // Set fourth breakpoint here
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/Makefile b/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/Makefile
new file mode 100644
index 000000000000..035413ff763d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+ENABLE_THREADS := YES
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/TestThreadSpecificBreakpoint.py b/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/TestThreadSpecificBreakpoint.py
new file mode 100644
index 000000000000..3c69b6667f7d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/TestThreadSpecificBreakpoint.py
@@ -0,0 +1,63 @@
+"""
+Test that we obey thread conditioned breakpoints.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ThreadSpecificBreakTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureWindows # Thread specific breakpoints cause the inferior to crash
+ def test_python(self):
+ """Test that we obey thread conditioned breakpoints."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # This test works by setting a breakpoint in a function conditioned to stop only on
+ # the main thread, and then calling this function on a secondary thread, joining,
+ # and then calling again on the main thread. If the thread specific breakpoint works
+ # then it should not be hit on the secondary thread, only on the main thread.
+
+ main_source_spec = lldb.SBFileSpec ("main.cpp")
+
+ main_breakpoint = target.BreakpointCreateBySourceRegex("Set main breakpoint here", main_source_spec);
+ thread_breakpoint = target.BreakpointCreateBySourceRegex("Set thread-specific breakpoint here", main_source_spec)
+
+ self.assertTrue(main_breakpoint.IsValid(), "Failed to set main breakpoint.")
+ self.assertGreater(main_breakpoint.GetNumLocations(), 0, "main breakpoint has no locations associated with it.")
+ self.assertTrue(thread_breakpoint.IsValid(), "Failed to set thread breakpoint.")
+ self.assertGreater(thread_breakpoint.GetNumLocations(), 0, "thread breakpoint has no locations associated with it.")
+
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ stopped_threads = lldbutil.get_threads_stopped_at_breakpoint(process, main_breakpoint)
+ self.assertEqual(len(stopped_threads), 1, "main breakpoint stopped at unexpected number of threads")
+ main_thread = stopped_threads[0]
+ main_thread_id = main_thread.GetThreadID()
+
+ # Set the thread-specific breakpoint to only stop on the main thread. The run the function
+ # on another thread and join on it. If the thread-specific breakpoint works, the next
+ # stop should be on the main thread.
+ thread_breakpoint.SetThreadID(main_thread_id)
+
+ process.Continue()
+ next_stop_state = process.GetState()
+ self.assertEqual(next_stop_state, lldb.eStateStopped, "We should have stopped at the thread breakpoint.")
+ stopped_threads = lldbutil.get_threads_stopped_at_breakpoint(process, thread_breakpoint)
+ self.assertEqual(len(stopped_threads), 1, "thread breakpoint stopped at unexpected number of threads")
+ self.assertEqual(stopped_threads[0].GetThreadID(), main_thread_id, "thread breakpoint stopped at the wrong thread")
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/main.cpp b/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/main.cpp
new file mode 100644
index 000000000000..7721b5d84322
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break/main.cpp
@@ -0,0 +1,20 @@
+#include <chrono>
+#include <thread>
+
+void
+thread_function ()
+{
+ // Set thread-specific breakpoint here.
+ std::this_thread::sleep_for(std::chrono::microseconds(100));
+}
+
+int
+main ()
+{
+ // Set main breakpoint here.
+ std::thread t(thread_function);
+ t.join();
+
+ thread_function();
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/Makefile b/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/Makefile
new file mode 100644
index 000000000000..035413ff763d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+ENABLE_THREADS := YES
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/TestThreadSpecificBpPlusCondition.py b/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/TestThreadSpecificBpPlusCondition.py
new file mode 100644
index 000000000000..b4a0b7a5dd4e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/TestThreadSpecificBpPlusCondition.py
@@ -0,0 +1,65 @@
+"""
+Test that we obey thread conditioned breakpoints and expression
+conditioned breakpoints simultaneously
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ThreadSpecificBreakPlusConditionTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfFreeBSD # test frequently times out or hangs
+ @expectedFailureFreeBSD('llvm.org/pr18522') # hits break in another thread in testrun
+ @add_test_categories(['pyapi'])
+ @expectedFailureWindows # Thread specific breakpoints cause the inferior to crash.
+ @expectedFlakeyLinux # this test fails 6/100 dosep runs
+ def test_python(self):
+ """Test that we obey thread conditioned breakpoints."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ main_source_spec = lldb.SBFileSpec ("main.cpp")
+
+ # Set a breakpoint in the thread body, and make it active for only the first thread.
+ break_thread_body = target.BreakpointCreateBySourceRegex ("Break here in thread body.", main_source_spec)
+ self.assertTrue (break_thread_body.IsValid() and break_thread_body.GetNumLocations() > 0, "Failed to set thread body breakpoint.")
+
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, break_thread_body)
+
+ victim_thread = threads[0]
+
+ # Pick one of the threads, and change the breakpoint so it ONLY stops for this thread,
+ # but add a condition that it won't stop for this thread's my_value. The other threads
+ # pass the condition, so they should stop, but if the thread-specification is working
+ # they should not stop. So nobody should hit the breakpoint anymore, and we should
+ # just exit cleanly.
+
+ frame = victim_thread.GetFrameAtIndex(0)
+ value = frame.FindVariable("my_value").GetValueAsSigned(0)
+ self.assertTrue (value > 0 and value < 11, "Got a reasonable value for my_value.")
+
+ cond_string = "my_value != %d"%(value)
+
+ break_thread_body.SetThreadID(victim_thread.GetThreadID())
+ break_thread_body.SetCondition (cond_string)
+
+ process.Continue()
+
+ next_stop_state = process.GetState()
+ self.assertTrue (next_stop_state == lldb.eStateExited, "We should have not hit the breakpoint again.")
diff --git a/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/main.cpp b/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/main.cpp
new file mode 100644
index 000000000000..af8ab84157fd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/thread/thread_specific_break_plus_condition/main.cpp
@@ -0,0 +1,39 @@
+#include <chrono>
+#include <thread>
+#include <vector>
+
+void *
+thread_function (void *thread_marker)
+{
+ int keep_going = 1;
+ int my_value = *((int *)thread_marker);
+ int counter = 0;
+
+ while (counter < 20)
+ {
+ counter++; // Break here in thread body.
+ std::this_thread::sleep_for(std::chrono::microseconds(10));
+ }
+ return NULL;
+}
+
+
+int
+main ()
+{
+ std::vector<std::thread> threads;
+
+ int thread_value = 0;
+ int i;
+
+ for (i = 0; i < 10; i++)
+ {
+ thread_value += 1;
+ threads.push_back(std::thread(thread_function, &thread_value));
+ }
+
+ for (i = 0; i < 10; i++)
+ threads[i].join();
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/tty/TestTerminal.py b/packages/Python/lldbsuite/test/functionalities/tty/TestTerminal.py
new file mode 100644
index 000000000000..5697c2c37283
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/tty/TestTerminal.py
@@ -0,0 +1,40 @@
+"""
+Test lldb command aliases.
+"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class LaunchInTerminalTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ # Darwin is the only platform that I know of that supports optionally launching
+ # a program in a separate terminal window. It would be great if other platforms
+ # added support for this.
+ @skipUnlessDarwin
+ @expectedFailureDarwin("llvm.org/pr25484")
+ # If the test is being run under sudo, the spawned terminal won't retain that elevated
+ # privilege so it can't open the socket to talk back to the test case
+ @unittest2.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0, "test cannot be run as root")
+ # Do we need to disable this test if the testsuite is being run on a remote system?
+ # This env var is only defined when the shell is running in a local mac terminal window
+ @unittest2.skipUnless('TERM_PROGRAM' in os.environ, "test must be run on local system")
+ @no_debug_info_test
+ def test_launch_in_terminal (self):
+ exe = "/bin/ls"
+ target = self.dbg.CreateTarget(exe)
+ launch_info = lldb.SBLaunchInfo(["-lAF", "/tmp/"])
+ launch_info.SetLaunchFlags(lldb.eLaunchFlagLaunchInTTY | lldb.eLaunchFlagCloseTTYOnExit)
+ error = lldb.SBError()
+ process = target.Launch (launch_info, error)
+ self.assertTrue(error.Success(), "Make sure launch happened successfully in a terminal window")
+ # Running in synchronous mode our process should have run and already exited by the time target.Launch() returns
+ self.assertTrue(process.GetState() == lldb.eStateExited)
diff --git a/packages/Python/lldbsuite/test/functionalities/type_completion/Makefile b/packages/Python/lldbsuite/test/functionalities/type_completion/Makefile
new file mode 100644
index 000000000000..b69775dc199a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/type_completion/Makefile
@@ -0,0 +1,12 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+# clang-3.5+ outputs FullDebugInfo by default for Darwin/FreeBSD
+# targets. Other targets do not, which causes this test to fail.
+# This flag enables FullDebugInfo for all targets.
+ifneq (,$(findstring clang,$(CC)))
+ CFLAGS_EXTRAS += -fno-limit-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/type_completion/TestTypeCompletion.py b/packages/Python/lldbsuite/test/functionalities/type_completion/TestTypeCompletion.py
new file mode 100644
index 000000000000..5a238b7d3542
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/type_completion/TestTypeCompletion.py
@@ -0,0 +1,108 @@
+"""
+Check that types only get completed when necessary.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TypeCompletionTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureIcc # often fails with 'NameAndAddress should be valid'
+ # Fails with gcc 4.8.1 with llvm.org/pr15301 LLDB prints incorrect sizes of STL containers
+ def test_with_run_command(self):
+ """Check that types only get completed when necessary."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_source_regexp (self, "// Set break point at this line.")
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type category enable -l c++', check=False)
+
+ self.runCmd('type category disable -l c++', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ p_vector = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('p')
+ p_type = p_vector.GetType()
+ self.assertFalse(p_type.IsTypeComplete(), 'vector<T> complete but it should not be')
+
+ self.runCmd("continue")
+
+ p_vector = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('p')
+ p_type = p_vector.GetType()
+ self.assertFalse(p_type.IsTypeComplete(), 'vector<T> complete but it should not be')
+
+ self.runCmd("continue")
+
+ self.runCmd("frame variable p --show-types")
+
+ p_vector = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('p')
+ p_type = p_vector.GetType()
+ self.assertTrue(p_type.IsTypeComplete(), 'vector<T> should now be complete')
+ name_address_type = p_type.GetTemplateArgumentType(0)
+ self.assertTrue(name_address_type.IsValid(), 'NameAndAddress should be valid')
+ self.assertFalse(name_address_type.IsTypeComplete(), 'NameAndAddress complete but it should not be')
+
+ self.runCmd("continue")
+
+ self.runCmd("frame variable guy --show-types")
+
+ p_vector = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('p')
+ p_type = p_vector.GetType()
+ self.assertTrue(p_type.IsTypeComplete(), 'vector<T> should now be complete')
+ name_address_type = p_type.GetTemplateArgumentType(0)
+ self.assertTrue(name_address_type.IsValid(), 'NameAndAddress should be valid')
+ self.assertTrue(name_address_type.IsTypeComplete(), 'NameAndAddress should now be complete')
+ field0 = name_address_type.GetFieldAtIndex(0)
+ self.assertTrue(field0.IsValid(), 'NameAndAddress::m_name should be valid')
+ string = field0.GetType().GetPointeeType()
+ self.assertTrue(string.IsValid(), 'CustomString should be valid')
+ self.assertFalse(string.IsTypeComplete(), 'CustomString complete but it should not be')
+
+ self.runCmd("continue")
+
+ p_vector = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('p')
+ p_type = p_vector.GetType()
+ self.assertTrue(p_type.IsTypeComplete(), 'vector<T> should now be complete')
+ name_address_type = p_type.GetTemplateArgumentType(0)
+ self.assertTrue(name_address_type.IsValid(), 'NameAndAddress should be valid')
+ self.assertTrue(name_address_type.IsTypeComplete(), 'NameAndAddress should now be complete')
+ field0 = name_address_type.GetFieldAtIndex(0)
+ self.assertTrue(field0.IsValid(), 'NameAndAddress::m_name should be valid')
+ string = field0.GetType().GetPointeeType()
+ self.assertTrue(string.IsValid(), 'CustomString should be valid')
+ self.assertFalse(string.IsTypeComplete(), 'CustomString complete but it should not be')
+
+ self.runCmd('type category enable -l c++', check=False)
+ self.runCmd('frame variable guy --show-types --ptr-depth=1')
+
+ p_vector = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('p')
+ p_type = p_vector.GetType()
+ self.assertTrue(p_type.IsTypeComplete(), 'vector<T> should now be complete')
+ name_address_type = p_type.GetTemplateArgumentType(0)
+ self.assertTrue(name_address_type.IsValid(), 'NameAndAddress should be valid')
+ self.assertTrue(name_address_type.IsTypeComplete(), 'NameAndAddress should now be complete')
+ field0 = name_address_type.GetFieldAtIndex(0)
+ self.assertTrue(field0.IsValid(), 'NameAndAddress::m_name should be valid')
+ string = field0.GetType().GetPointeeType()
+ self.assertTrue(string.IsValid(), 'CustomString should be valid')
+ self.assertTrue(string.IsTypeComplete(), 'CustomString should now be complete')
diff --git a/packages/Python/lldbsuite/test/functionalities/type_completion/main.cpp b/packages/Python/lldbsuite/test/functionalities/type_completion/main.cpp
new file mode 100644
index 000000000000..80329737928e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/type_completion/main.cpp
@@ -0,0 +1,81 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <string.h>
+#include <vector>
+#include <iostream>
+
+class CustomString
+{
+public:
+ CustomString (const char* buffer) :
+ m_buffer(nullptr)
+ {
+ if (buffer)
+ {
+ auto l = strlen(buffer);
+ m_buffer = new char[1 + l];
+ strcpy(m_buffer, buffer);
+ }
+ }
+
+ ~CustomString ()
+ {
+ delete[] m_buffer;
+ }
+
+ const char*
+ GetBuffer ()
+ {
+ return m_buffer;
+ }
+
+private:
+ char *m_buffer;
+};
+
+class NameAndAddress
+ {
+ public:
+ CustomString& GetName() { return *m_name; }
+ CustomString& GetAddress() { return *m_address; }
+ NameAndAddress(const char* N, const char* A) : m_name(new CustomString(N)), m_address(new CustomString(A))
+ {
+ }
+ ~NameAndAddress()
+ {
+ }
+
+ private:
+ CustomString* m_name;
+ CustomString* m_address;
+};
+
+typedef std::vector<NameAndAddress> People;
+
+int main (int argc, const char * argv[])
+{
+ People p;
+ p.push_back(NameAndAddress("Enrico","123 Main Street"));
+ p.push_back(NameAndAddress("Foo","10710 Johnson Avenue")); // Set break point at this line.
+ p.push_back(NameAndAddress("Arpia","6956 Florey Street"));
+ p.push_back(NameAndAddress("Apple","1 Infinite Loop")); // Set break point at this line.
+ p.push_back(NameAndAddress("Richard","9500 Gilman Drive"));
+ p.push_back(NameAndAddress("Bar","3213 Windsor Rd"));
+
+ for (int j = 0; j<p.size(); j++)
+ {
+ NameAndAddress guy = p[j];
+ std::cout << "Person " << j << " is named " << guy.GetName().GetBuffer() << " and lives at " << guy.GetAddress().GetBuffer() << std::endl; // Set break point at this line.
+ }
+
+ return 0;
+
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/type_lookup/Makefile b/packages/Python/lldbsuite/test/functionalities/type_lookup/Makefile
new file mode 100644
index 000000000000..31e57fe28a58
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/type_lookup/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../make
+
+OBJC_SOURCES := main.m
+
+CFLAGS_EXTRAS += -w
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/functionalities/type_lookup/TestTypeLookup.py b/packages/Python/lldbsuite/test/functionalities/type_lookup/TestTypeLookup.py
new file mode 100644
index 000000000000..ca0b1f1d1e53
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/type_lookup/TestTypeLookup.py
@@ -0,0 +1,43 @@
+"""
+Test type lookup command.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import datetime
+import lldbsuite.test.lldbutil as lldbutil
+
+class TypeLookupTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.m', '// break here')
+
+ @skipUnlessDarwin
+ def test_type_lookup(self):
+ """Test type lookup command."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ self.expect('type lookup NoSuchType', substrs=['@interface'], matching=False)
+ self.expect('type lookup NSURL', substrs=['NSURL'])
+ self.expect('type lookup NSArray', substrs=['NSArray'])
+ self.expect('type lookup NSObject', substrs=['NSObject', 'isa'])
diff --git a/packages/Python/lldbsuite/test/functionalities/type_lookup/main.m b/packages/Python/lldbsuite/test/functionalities/type_lookup/main.m
new file mode 100644
index 000000000000..058a0c00e92c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/type_lookup/main.m
@@ -0,0 +1,16 @@
+//===-- main.m ------------------------------------------------*- ObjC -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#import <Foundation/Foundation.h>
+
+int main (int argc, const char * argv[])
+{
+ return 0; // break here
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/Makefile b/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/Makefile
new file mode 100644
index 000000000000..ede25f029bcd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+CFLAGS ?= -g -Os
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/TestNoreturnUnwind.py b/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/TestNoreturnUnwind.py
new file mode 100644
index 000000000000..a419500f7a17
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/TestNoreturnUnwind.py
@@ -0,0 +1,76 @@
+"""
+Test that we can backtrace correctly with 'noreturn' functions on the stack
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class NoreturnUnwind(TestBase):
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailurei386 #xfail to get buildbot green, failing config: i386 binary running on ubuntu 14.04 x86_64
+ @skipIfWindows # clang-cl does not support gcc style attributes.
+ def test (self):
+ """Test that we can backtrace correctly with 'noreturn' functions on the stack"""
+ self.build()
+ self.setTearDownCleanup()
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ if not process:
+ self.fail("SBTarget.Launch() failed")
+
+ if process.GetState() != lldb.eStateStopped:
+ self.fail("Process should be in the 'stopped' state, "
+ "instead the actual state is: '%s'" %
+ lldbutil.state_type_to_str(process.GetState()))
+
+ thread = process.GetThreadAtIndex(0)
+ abort_frame_number = 0
+ for f in thread.frames:
+ # Some C libraries mangle the abort symbol into __GI_abort.
+ if f.GetFunctionName() in ["abort", "__GI_abort"]:
+ break
+ abort_frame_number = abort_frame_number + 1
+
+ if self.TraceOn():
+ print("Backtrace once we're stopped:")
+ for f in thread.frames:
+ print(" %d %s" % (f.GetFrameID(), f.GetFunctionName()))
+
+ # I'm going to assume that abort() ends up calling/invoking another
+ # function before halting the process. In which case if abort_frame_number
+ # equals 0, we didn't find abort() in the backtrace.
+ if abort_frame_number == len(thread.frames):
+ self.fail("Unable to find abort() in backtrace.")
+
+ func_c_frame_number = abort_frame_number + 1
+ if thread.GetFrameAtIndex (func_c_frame_number).GetFunctionName() != "func_c":
+ self.fail("Did not find func_c() above abort().")
+
+ # This depends on whether we see the func_b inlined function in the backtrace
+ # or not. I'm not interested in testing that aspect of the backtrace here
+ # right now.
+
+ if thread.GetFrameAtIndex (func_c_frame_number + 1).GetFunctionName() == "func_b":
+ func_a_frame_number = func_c_frame_number + 2
+ else:
+ func_a_frame_number = func_c_frame_number + 1
+
+ if thread.GetFrameAtIndex (func_a_frame_number).GetFunctionName() != "func_a":
+ self.fail("Did not find func_a() above func_c().")
+
+ main_frame_number = func_a_frame_number + 1
+
+ if thread.GetFrameAtIndex (main_frame_number).GetFunctionName() != "main":
+ self.fail("Did not find main() above func_a().")
diff --git a/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/main.c b/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/main.c
new file mode 100644
index 000000000000..7190e38f5d8c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/unwind/noreturn/main.c
@@ -0,0 +1,37 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+static void func_a (void) __attribute__((noinline));
+static void func_b (void) __attribute__((noreturn));
+static void func_c (void) __attribute__((noinline));
+
+static void
+func_c (void)
+{
+ abort ();
+}
+
+static void
+func_b (void)
+{
+ func_c ();
+ while (1)
+ ;
+}
+
+static void
+func_a (void)
+{
+ func_b ();
+}
+
+int
+main (int argc, char *argv[])
+{
+ sleep (2);
+
+ func_a ();
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/Makefile b/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/TestSigtrampUnwind.py b/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/TestSigtrampUnwind.py
new file mode 100644
index 000000000000..ddfb1122b6f1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/TestSigtrampUnwind.py
@@ -0,0 +1,81 @@
+"""
+Test that we can backtrace correctly with 'sigtramp' functions on the stack
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class SigtrampUnwind(TestBase):
+ mydir = TestBase.compute_mydir(__file__)
+
+ # On different platforms the "_sigtramp" and "__kill" frames are likely to be different.
+ # This test could probably be adapted to run on linux/*bsd easily enough.
+ @skipUnlessDarwin
+ def test (self):
+ """Test that we can backtrace correctly with _sigtramp on the stack"""
+ self.build()
+ self.setTearDownCleanup()
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", line_number('main.c', '// Set breakpoint here'), num_expected_locations=1)
+
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ if not process:
+ self.fail("SBTarget.Launch() failed")
+
+ if process.GetState() != lldb.eStateStopped:
+ self.fail("Process should be in the 'stopped' state, "
+ "instead the actual state is: '%s'" %
+ lldbutil.state_type_to_str(process.GetState()))
+
+ self.expect("pro handle -n false -p true -s false SIGUSR1", "Have lldb pass SIGUSR1 signals",
+ substrs = ["SIGUSR1", "true", "false", "false"])
+
+ lldbutil.run_break_set_by_symbol (self, "handler", num_expected_locations=1, module_name="a.out")
+
+ self.runCmd("continue")
+
+ thread = process.GetThreadAtIndex(0)
+
+ found_handler = False
+ found_sigtramp = False
+ found_kill = False
+ found_main = False
+
+ for f in thread.frames:
+ if f.GetFunctionName() == "handler":
+ found_handler = True
+ if f.GetFunctionName() == "_sigtramp":
+ found_sigtramp = True
+ if f.GetFunctionName() == "__kill":
+ found_kill = True
+ if f.GetFunctionName() == "main":
+ found_main = True
+
+ if self.TraceOn():
+ print("Backtrace once we're stopped:")
+ for f in thread.frames:
+ print(" %d %s" % (f.GetFrameID(), f.GetFunctionName()))
+
+ if found_handler == False:
+ self.fail("Unable to find handler() in backtrace.")
+
+ if found_sigtramp == False:
+ self.fail("Unable to find _sigtramp() in backtrace.")
+
+ if found_kill == False:
+ self.fail("Unable to find kill() in backtrace.")
+
+ if found_main == False:
+ self.fail("Unable to find main() in backtrace.")
diff --git a/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/main.c b/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/main.c
new file mode 100644
index 000000000000..aaa03e7aa843
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/unwind/sigtramp/main.c
@@ -0,0 +1,27 @@
+#include <stdlib.h>
+#include <signal.h>
+#include <stdio.h>
+#include <unistd.h>
+
+void handler (int in)
+{
+ puts ("in handler routine");
+ while (1)
+ ;
+}
+
+void
+foo ()
+{
+ puts ("in foo ()");
+ kill (getpid(), SIGUSR1);
+}
+int main ()
+{
+ puts ("in main"); // Set breakpoint here
+ signal (SIGUSR1, handler);
+ puts ("signal handler set up");
+ foo();
+ puts ("exiting");
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/unwind/standard/Makefile b/packages/Python/lldbsuite/test/functionalities/unwind/standard/Makefile
new file mode 100644
index 000000000000..146da30b12cb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/unwind/standard/Makefile
@@ -0,0 +1,3 @@
+LEVEL = ../../../make
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/unwind/standard/TestStandardUnwind.py b/packages/Python/lldbsuite/test/functionalities/unwind/standard/TestStandardUnwind.py
new file mode 100644
index 000000000000..3f88e7b6e1aa
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/unwind/standard/TestStandardUnwind.py
@@ -0,0 +1,145 @@
+"""
+Test that we can backtrace correctly from standard functions.
+
+This test suit is a collection of automatically generated tests from the source files in the
+directory. Please DON'T add individual test cases to this file.
+
+To add a new test case to this test suit please create a simple C/C++ application and put the
+source file into the directory of the test cases. The test suit will automatically pick the
+file up and generate a test case from it in run time (with name test_standard_unwind_<file_name>
+after escaping some special characters).
+"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+test_source_dirs = ["."]
+
+class StandardUnwindTest(TestBase):
+ mydir = TestBase.compute_mydir(__file__)
+
+ def standard_unwind_tests (self):
+ # The following variables have to be defined for each architecture and OS we testing for:
+ # base_function_names: List of function names where we accept that the stack unwinding is
+ # correct if they are on the stack. It should include the bottom most
+ # function on the stack and a list of functions where we know we can't
+ # unwind for any reason (list of expected failure functions)
+ # no_step_function_names: The list of functions where we don't want to step through
+ # instruction by instruction for any reason. (A valid reason is if
+ # it is impossible to step through a function instruction by
+ # instruction because it is special for some reason.) For these
+ # functions we will immediately do a step-out when we hit them.
+
+ triple = self.dbg.GetSelectedPlatform().GetTriple()
+ if re.match("arm-.*-.*-android", triple):
+ base_function_names = [
+ "_start", # Base function on the stack
+ "__memcpy_base", # Function reached by a fall through from the previous function
+ "__memcpy_base_aligned", # Function reached by a fall through from the previous function
+ ]
+ no_step_function_names = [
+ "__sync_fetch_and_add_4", # Calls into a special SO where we can't set a breakpoint
+ "pthread_mutex_lock", # Uses ldrex and strex what interferes with the software single stepping
+ "pthread_mutex_unlock", # Uses ldrex and strex what interferes with the software single stepping
+ "pthread_once", # Uses ldrex and strex what interferes with the software single stepping
+ ]
+ elif re.match("aarch64-.*-.*-android", triple):
+ base_function_names = [
+ "do_arm64_start", # Base function on the stack
+ ]
+ no_step_function_names = [
+ None,
+ "__cxa_guard_acquire", # Uses ldxr and stxr what interferes with the software single stepping
+ "__cxa_guard_release", # Uses ldxr and stxr what interferes with the software single stepping
+ "pthread_mutex_lock", # Uses ldxr and stxr what interferes with the software single stepping
+ "pthread_mutex_unlock", # Uses ldxr and stxr what interferes with the software single stepping
+ "pthread_once", # Uses ldxr and stxr what interferes with the software single stepping
+ ]
+ else:
+ self.skipTest("No expectations for the current architecture")
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ target.BreakpointCreateByName("main")
+
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process is not None, "SBTarget.Launch() failed")
+ self.assertEqual(process.GetState(), lldb.eStateStopped, "The process didn't hit main")
+
+ index = 0
+ while process.GetState() == lldb.eStateStopped:
+ index += 1
+ if process.GetNumThreads() > 1:
+ # In case of a multi threaded inferior if one of the thread is stopped in a blocking
+ # syscall and we try to step it then SBThread::StepInstruction() will block forever
+ self.skipTest("Multi threaded inferiors are not supported by this test")
+
+ thread = process.GetThreadAtIndex(0)
+
+ if self.TraceOn():
+ print("INDEX: %u" % index)
+ for f in thread.frames:
+ print(f)
+
+ if thread.GetFrameAtIndex(0).GetFunctionName() is not None:
+ found_main = False
+ for f in thread.frames:
+ if f.GetFunctionName() in base_function_names:
+ found_main = True
+ break
+ self.assertTrue(found_main, "Main function isn't found on the backtrace")
+
+ if thread.GetFrameAtIndex(0).GetFunctionName() in no_step_function_names:
+ thread.StepOut()
+ else:
+ thread.StepInstruction(False)
+
+# Collect source files in the specified directories
+test_source_files = set([])
+for d in test_source_dirs:
+ if os.path.isabs(d):
+ dirname = d
+ else:
+ dirname = os.path.join(os.path.dirname(__file__), d)
+
+ for root, _, files in os.walk(dirname):
+ test_source_files = test_source_files | set(os.path.abspath(os.path.join(root, f)) for f in files)
+
+# Generate test cases based on the collected source files
+for f in test_source_files:
+ if f.endswith(".cpp") or f.endswith(".c"):
+ @add_test_categories(["dwarf"])
+ @unittest2.skipIf(TestBase.skipLongRunningTest(), "Skip this long running test")
+ def test_function_dwarf(self, f=f):
+ if f.endswith(".cpp"):
+ d = {'CXX_SOURCES': f}
+ elif f.endswith(".c"):
+ d = {'C_SOURCES': f}
+
+ # If we can't compile the inferior just skip the test instead of failing it.
+ # It makes the test suit more robust when testing on several different architecture
+ # avoid the hassle of skipping tests manually.
+ try:
+ self.buildDwarf(dictionary=d)
+ self.setTearDownCleanup(d)
+ except:
+ if self.TraceOn():
+ print(sys.exc_info()[0])
+ self.skipTest("Inferior not supported")
+ self.standard_unwind_tests()
+
+ test_name = "test_unwind_" + str(f)
+ for c in ".=()/\\":
+ test_name = test_name.replace(c, '_')
+
+ test_function_dwarf.__name__ = test_name
+ setattr(StandardUnwindTest, test_function_dwarf.__name__, test_function_dwarf)
diff --git a/packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/divmod.cpp b/packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/divmod.cpp
new file mode 100644
index 000000000000..75df6ba89372
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/divmod.cpp
@@ -0,0 +1,15 @@
+//===-- divmod.cpp ----------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+int
+main(int argc, char const *argv[])
+{
+ signed long long a = 123456789, b = 12, c = a / b, d = a % b;
+ unsigned long long e = 123456789, f = 12, g = e / f, h = e % f;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/fprintf.cpp b/packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/fprintf.cpp
new file mode 100644
index 000000000000..188738cb9bab
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/fprintf.cpp
@@ -0,0 +1,16 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <cstdio>
+
+int
+main(int argc, char const *argv[])
+{
+ fprintf(stderr, "%d %p %s\n", argc, argv, argv[0]);
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/new_delete.cpp b/packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/new_delete.cpp
new file mode 100644
index 000000000000..d240b89e50ab
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/unwind/standard/hand_written/new_delete.cpp
@@ -0,0 +1,15 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+int
+main(int argc, char const *argv[])
+{
+ int* p = new int;
+ delete p;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/value_md5_crash/Makefile b/packages/Python/lldbsuite/test/functionalities/value_md5_crash/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/value_md5_crash/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/value_md5_crash/TestValueMD5Crash.py b/packages/Python/lldbsuite/test/functionalities/value_md5_crash/TestValueMD5Crash.py
new file mode 100644
index 000000000000..763ecc94c2eb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/value_md5_crash/TestValueMD5Crash.py
@@ -0,0 +1,52 @@
+"""
+Verify that the hash computing logic for ValueObject's values can't crash us.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ValueMD5CrashTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// break here')
+
+ @expectedFailureWindows("llvm.org/pr24663")
+ def test_with_run_command(self):
+ """Verify that the hash computing logic for ValueObject's values can't crash us."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ value = self.frame().FindVariable("a")
+ value.SetPreferDynamicValue(lldb.eDynamicCanRunTarget)
+
+ v = value.GetValue()
+ type_name = value.GetTypeName()
+ self.assertTrue(type_name == "B *", "a is a B*")
+
+ self.runCmd("next")
+ self.runCmd("process kill")
+
+ # now the process is dead, and value needs updating
+ v = value.GetValue()
+
+ # if we are here, instead of crashed, the test succeeded
diff --git a/packages/Python/lldbsuite/test/functionalities/value_md5_crash/main.cpp b/packages/Python/lldbsuite/test/functionalities/value_md5_crash/main.cpp
new file mode 100644
index 000000000000..ba596b8653cf
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/value_md5_crash/main.cpp
@@ -0,0 +1,29 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+class A {
+public:
+ virtual int foo() { return 1; }
+ virtual ~A () = default;
+ A() = default;
+};
+
+class B : public A {
+public:
+ virtual int foo() { return 2; }
+ virtual ~B () = default;
+ B() = default;
+};
+
+int main() {
+ A* a = new B();
+ a->foo(); // break here
+ return 0; // break here
+}
+
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchlocation/Makefile b/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchlocation/Makefile
new file mode 100644
index 000000000000..8817fff55e8c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchlocation/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+ENABLE_THREADS := YES
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchlocation/TestWatchLocation.py b/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchlocation/TestWatchLocation.py
new file mode 100644
index 000000000000..f0a0b5ab99d0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchlocation/TestWatchLocation.py
@@ -0,0 +1,98 @@
+"""
+Test lldb watchpoint that uses '-s size' to watch a pointed location with size.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class HelloWatchLocationTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Our simple source filename.
+ self.source = 'main.cpp'
+ # Find the line number to break inside main().
+ self.line = line_number(self.source, '// Set break point at this line.')
+ # This is for verifying that watch location works.
+ self.violating_func = "do_bad_thing_with_location";
+ # Build dictionary to have unique executable names for each test method.
+ self.exe_name = self.testMethodName
+ self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name}
+
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446") # WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows
+ @expectedFailureAll(archs=['mips', 'mipsel', 'mips64', 'mips64el']) # Most of the MIPS boards provide only one H/W watchpoints, and S/W watchpoints are not supported yet
+ def test_hello_watchlocation(self):
+ """Test watching a location with '-s size' option."""
+ self.build(dictionary=self.d)
+ self.setTearDownCleanup(dictionary=self.d)
+ exe = os.path.join(os.getcwd(), self.exe_name)
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Add a breakpoint to set a watchpoint when stopped on the breakpoint.
+ lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1, loc_exact=False)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # We should be stopped again due to the breakpoint.
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Now let's set a write-type watchpoint pointed to by 'g_char_ptr'.
+ # The main.cpp, by design, misbehaves by not following the agreed upon
+ # protocol of using a mutex while accessing the global pool and by not
+ # incrmenting the global pool by 2.
+ self.expect("watchpoint set expression -w write -s 1 -- g_char_ptr", WATCHPOINT_CREATED,
+ substrs = ['Watchpoint created', 'size = 1', 'type = w'])
+ # Get a hold of the watchpoint id just created, it is used later on to
+ # match the watchpoint id which is expected to be fired.
+ match = re.match("Watchpoint created: Watchpoint (.*):", self.res.GetOutput().splitlines()[0])
+ if match:
+ expected_wp_id = int(match.group(1), 0)
+ else:
+ self.fail("Grokking watchpoint id faailed!")
+
+ self.runCmd("expr unsigned val = *g_char_ptr; val")
+ self.expect(self.res.GetOutput().splitlines()[0], exe=False,
+ endstr = ' = 0')
+
+ self.runCmd("watchpoint set expression -w write -s 4 -- &threads[0]")
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should be 0 initially.
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = 0'])
+
+ self.runCmd("process continue")
+
+ # We should be stopped again due to the watchpoint (write type), but
+ # only once. The stop reason of the thread should be watchpoint.
+ self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT,
+ substrs = ['stopped',
+ 'stop reason = watchpoint %d' % expected_wp_id])
+
+ # Switch to the thread stopped due to watchpoint and issue some commands.
+ self.switch_to_thread_with_stop_reason(lldb.eStopReasonWatchpoint)
+ self.runCmd("thread backtrace")
+ self.expect("frame info",
+ substrs = [self.violating_func])
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should now be 1.
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = 1'])
+
+ self.runCmd("thread backtrace all")
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchlocation/main.cpp b/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchlocation/main.cpp
new file mode 100644
index 000000000000..59b0afc6d5f7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchlocation/main.cpp
@@ -0,0 +1,106 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <chrono>
+#include <condition_variable>
+#include <cstdio>
+#include <random>
+#include <thread>
+
+std::default_random_engine g_random_engine{std::random_device{}()};
+std::uniform_int_distribution<> g_distribution{0, 3000000};
+std::condition_variable g_condition_variable;
+std::mutex g_mutex;
+int g_count;
+
+char *g_char_ptr = nullptr;
+
+void
+barrier_wait()
+{
+ std::unique_lock<std::mutex> lock{g_mutex};
+ if (--g_count > 0)
+ g_condition_variable.wait(lock);
+ else
+ g_condition_variable.notify_all();
+}
+
+void
+do_bad_thing_with_location(char *char_ptr, char new_val)
+{
+ unsigned what = new_val;
+ printf("new value written to location(%p) = %u\n", char_ptr, what);
+ *char_ptr = new_val;
+}
+
+uint32_t
+access_pool (bool flag = false)
+{
+ static std::mutex g_access_mutex;
+ if (!flag)
+ g_access_mutex.lock();
+
+ char old_val = *g_char_ptr;
+ if (flag)
+ do_bad_thing_with_location(g_char_ptr, old_val + 1);
+
+ if (!flag)
+ g_access_mutex.unlock();
+ return *g_char_ptr;
+}
+
+void
+thread_func (uint32_t thread_index)
+{
+ printf ("%s (thread index = %u) startng...\n", __FUNCTION__, thread_index);
+
+ barrier_wait();
+
+ uint32_t count = 0;
+ uint32_t val;
+ while (count++ < 15)
+ {
+ // random micro second sleep from zero to 3 seconds
+ int usec = g_distribution(g_random_engine);
+ printf ("%s (thread = %u) doing a usleep (%d)...\n", __FUNCTION__, thread_index, usec);
+ std::this_thread::sleep_for(std::chrono::microseconds{usec});
+
+ if (count < 7)
+ val = access_pool ();
+ else
+ val = access_pool (true);
+
+ printf ("%s (thread = %u) after usleep access_pool returns %d (count=%d)...\n", __FUNCTION__, thread_index, val, count);
+ }
+ printf ("%s (thread index = %u) exiting...\n", __FUNCTION__, thread_index);
+}
+
+
+int main (int argc, char const *argv[])
+{
+ g_count = 4;
+ std::thread threads[3];
+
+ g_char_ptr = new char{};
+
+ // Create 3 threads
+ for (auto &thread : threads)
+ thread = std::thread{thread_func, std::distance(threads, &thread)};
+
+ printf ("Before turning all three threads loose...\n"); // Set break point at this line.
+ barrier_wait();
+
+ // Join all of our threads
+ for (auto &thread : threads)
+ thread.join();
+
+ delete g_char_ptr;
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchpoint/Makefile b/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchpoint/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchpoint/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchpoint/TestMyFirstWatchpoint.py b/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchpoint/TestMyFirstWatchpoint.py
new file mode 100644
index 000000000000..57467c38d5f8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchpoint/TestMyFirstWatchpoint.py
@@ -0,0 +1,84 @@
+"""
+Test my first lldb watchpoint.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class HelloWatchpointTestCase(TestBase):
+
+ def getCategories (self):
+ return ['basic_process']
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Our simple source filename.
+ self.source = 'main.c'
+ # Find the line number to break inside main().
+ self.line = line_number(self.source, '// Set break point at this line.')
+ # And the watchpoint variable declaration line number.
+ self.decl = line_number(self.source, '// Watchpoint variable declaration.')
+ self.exe_name = 'a.out'
+ self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name}
+
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446")
+ def test_hello_watchpoint_using_watchpoint_set(self):
+ """Test a simple sequence of watchpoint creation and watchpoint hit."""
+ self.build(dictionary=self.d)
+ self.setTearDownCleanup(dictionary=self.d)
+
+ exe = os.path.join(os.getcwd(), self.exe_name)
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Add a breakpoint to set a watchpoint when stopped on the breakpoint.
+ lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # We should be stopped again due to the breakpoint.
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Now let's set a write-type watchpoint for 'global'.
+ # There should be only one watchpoint hit (see main.c).
+ self.expect("watchpoint set variable -w write global", WATCHPOINT_CREATED,
+ substrs = ['Watchpoint created', 'size = 4', 'type = w',
+ '%s:%d' % (self.source, self.decl)])
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should be 0 initially.
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = 0'])
+
+ self.runCmd("process continue")
+
+ # We should be stopped again due to the watchpoint (write type), but
+ # only once. The stop reason of the thread should be watchpoint.
+ self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT,
+ substrs = ['stopped',
+ 'stop reason = watchpoint'])
+
+ self.runCmd("process continue")
+
+ # Don't expect the read of 'global' to trigger a stop exception.
+ process = self.dbg.GetSelectedTarget().GetProcess()
+ if process.GetState() == lldb.eStateStopped:
+ self.assertFalse(lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint))
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should now be 1.
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = 1'])
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchpoint/main.c b/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchpoint/main.c
new file mode 100644
index 000000000000..11a738a0de43
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/hello_watchpoint/main.c
@@ -0,0 +1,30 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+#include <stdint.h>
+
+int32_t global = 10; // Watchpoint variable declaration.
+char gchar1 = 'a';
+char gchar2 = 'b';
+
+int main(int argc, char** argv) {
+ int local = 0;
+ printf("&global=%p\n", &global);
+ printf("about to write to 'global'...\n"); // Set break point at this line.
+ // When stopped, watch 'global' for write.
+ global = 20;
+ gchar1 += 1;
+ gchar2 += 1;
+ local += argc;
+ ++local;
+ printf("local: %d\n", local);
+ printf("global=%d\n", global);
+ printf("gchar1='%c'\n", gchar1);
+ printf("gchar2='%c'\n", gchar2);
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/multiple_threads/Makefile b/packages/Python/lldbsuite/test/functionalities/watchpoint/multiple_threads/Makefile
new file mode 100644
index 000000000000..8817fff55e8c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/multiple_threads/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+ENABLE_THREADS := YES
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/multiple_threads/TestWatchpointMultipleThreads.py b/packages/Python/lldbsuite/test/functionalities/watchpoint/multiple_threads/TestWatchpointMultipleThreads.py
new file mode 100644
index 000000000000..2318214a0d5c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/multiple_threads/TestWatchpointMultipleThreads.py
@@ -0,0 +1,137 @@
+"""
+Test that lldb watchpoint works for multiple threads.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class WatchpointForMultipleThreadsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446") # WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows
+ def test_watchpoint_multiple_threads(self):
+ """Test that lldb watchpoint works for multiple threads."""
+ self.build()
+ self.setTearDownCleanup()
+ self.hello_multiple_threads()
+
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446") # WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows
+ def test_watchpoint_multiple_threads_wp_set_and_then_delete(self):
+ """Test that lldb watchpoint works for multiple threads, and after the watchpoint is deleted, the watchpoint event should no longer fires."""
+ self.build()
+ self.setTearDownCleanup()
+ self.hello_multiple_threads_wp_set_and_then_delete()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Our simple source filename.
+ self.source = 'main.cpp'
+ # Find the line number to break inside main().
+ self.first_stop = line_number(self.source, '// Set break point at this line')
+
+ def hello_multiple_threads(self):
+ """Test that lldb watchpoint works for multiple threads."""
+ self.runCmd("file %s" % os.path.join(os.getcwd(), 'a.out'), CURRENT_EXECUTABLE_SET)
+
+ # Add a breakpoint to set a watchpoint when stopped on the breakpoint.
+ lldbutil.run_break_set_by_file_and_line (self, None, self.first_stop, num_expected_locations=1)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # We should be stopped again due to the breakpoint.
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Now let's set a write-type watchpoint for variable 'g_val'.
+ # The main.cpp, by design, misbehaves by not following the agreed upon
+ # protocol of using a mutex while accessing the global pool and by not
+ # writing to the variable.
+ self.expect("watchpoint set variable -w write g_val", WATCHPOINT_CREATED,
+ substrs = ['Watchpoint created', 'size = 4', 'type = w'])
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should be 0 initially.
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = 0'])
+
+ while True:
+ self.runCmd("process continue")
+
+ self.runCmd("thread list")
+ if "stop reason = watchpoint" in self.res.GetOutput():
+ # Good, we verified that the watchpoint works!
+ self.runCmd("thread backtrace all")
+ break
+ else:
+ self.fail("The stop reason should be either break or watchpoint")
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should now be 1.
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = 1'])
+
+ def hello_multiple_threads_wp_set_and_then_delete(self):
+ """Test that lldb watchpoint works for multiple threads, and after the watchpoint is deleted, the watchpoint event should no longer fires."""
+ self.runCmd("file %s" % os.path.join(os.getcwd(), 'a.out'), CURRENT_EXECUTABLE_SET)
+
+ # Add a breakpoint to set a watchpoint when stopped on the breakpoint.
+ lldbutil.run_break_set_by_file_and_line (self, None, self.first_stop, num_expected_locations=1)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # We should be stopped again due to the breakpoint.
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Now let's set a write-type watchpoint for variable 'g_val'.
+ # The main.cpp, by design, misbehaves by not following the agreed upon
+ # protocol of using a mutex while accessing the global pool and by not
+ # writing to the variable.
+ self.expect("watchpoint set variable -w write g_val", WATCHPOINT_CREATED,
+ substrs = ['Watchpoint created', 'size = 4', 'type = w'])
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should be 0 initially.
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = 0'])
+
+ watchpoint_stops = 0
+ while True:
+ self.runCmd("process continue")
+ self.runCmd("process status")
+ if re.search("Process .* exited", self.res.GetOutput()):
+ # Great, we are done with this test!
+ break
+
+ self.runCmd("thread list")
+ if "stop reason = watchpoint" in self.res.GetOutput():
+ self.runCmd("thread backtrace all")
+ watchpoint_stops += 1
+ if watchpoint_stops > 1:
+ self.fail("Watchpoint hits not supposed to exceed 1 by design!")
+ # Good, we verified that the watchpoint works! Now delete the watchpoint.
+ if self.TraceOn():
+ print("watchpoint_stops=%d at the moment we delete the watchpoint" % watchpoint_stops)
+ self.runCmd("watchpoint delete 1")
+ self.expect("watchpoint list -v",
+ substrs = ['No watchpoints currently set.'])
+ continue
+ else:
+ self.fail("The stop reason should be either break or watchpoint")
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/multiple_threads/main.cpp b/packages/Python/lldbsuite/test/functionalities/watchpoint/multiple_threads/main.cpp
new file mode 100644
index 000000000000..8a31041f8fca
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/multiple_threads/main.cpp
@@ -0,0 +1,83 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <chrono>
+#include <cstdio>
+#include <mutex>
+#include <random>
+#include <thread>
+
+std::default_random_engine g_random_engine{std::random_device{}()};
+std::uniform_int_distribution<> g_distribution{0, 3000000};
+
+uint32_t g_val = 0;
+
+
+uint32_t
+access_pool (bool flag = false)
+{
+ static std::mutex g_access_mutex;
+ if (!flag)
+ g_access_mutex.lock();
+
+ uint32_t old_val = g_val;
+ if (flag)
+ {
+ printf("changing g_val to %d...\n", old_val + 1);
+ g_val = old_val + 1;
+ }
+
+ if (!flag)
+ g_access_mutex.unlock();
+ return g_val;
+}
+
+void
+thread_func (uint32_t thread_index)
+{
+ // Break here in order to allow the thread
+ // to inherit the global watchpoint state.
+ printf ("%s (thread index = %u) startng...\n", __FUNCTION__, thread_index);
+
+ uint32_t count = 0;
+ uint32_t val;
+ while (count++ < 15)
+ {
+ // random micro second sleep from zero to 3 seconds
+ int usec = g_distribution(g_random_engine);
+ printf ("%s (thread = %u) doing a usleep (%d)...\n", __FUNCTION__, thread_index, usec);
+ std::this_thread::sleep_for(std::chrono::microseconds{usec});
+
+ if (count < 7)
+ val = access_pool ();
+ else
+ val = access_pool (true);
+
+ printf ("%s (thread = %u) after usleep access_pool returns %d (count=%d)...\n", __FUNCTION__, thread_index, val, count);
+ }
+ printf ("%s (thread index = %u) exiting...\n", __FUNCTION__, thread_index);
+}
+
+
+int main (int argc, char const *argv[])
+{
+ std::thread threads[3];
+
+ printf ("Before turning all three threads loose...\n"); // Set break point at this line,
+ // in order to set our watchpoint.
+ // Create 3 threads
+ for (auto &thread : threads)
+ thread = std::thread{thread_func, std::distance(threads, &thread)};
+
+ // Join all of our threads
+ for (auto &thread : threads)
+ thread.join();
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/step_over_watchpoint/Makefile b/packages/Python/lldbsuite/test/functionalities/watchpoint/step_over_watchpoint/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/step_over_watchpoint/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/step_over_watchpoint/TestStepOverWatchpoint.py b/packages/Python/lldbsuite/test/functionalities/watchpoint/step_over_watchpoint/TestStepOverWatchpoint.py
new file mode 100644
index 000000000000..dd18a6482066
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/step_over_watchpoint/TestStepOverWatchpoint.py
@@ -0,0 +1,113 @@
+"""Test stepping over watchpoints."""
+
+from __future__ import print_function
+
+
+
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+
+class TestStepOverWatchpoint(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def getCategories(self):
+ return ['basic_process']
+
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446")
+ def test(self):
+ """Test stepping over watchpoints."""
+ self.build()
+ exe = os.path.join(os.getcwd(), 'a.out')
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(self.target, VALID_TARGET)
+
+ lldbutil.run_break_set_by_symbol(self, 'main')
+
+ process = target.LaunchSimple(None, None,
+ self.get_process_working_directory())
+ self.assertTrue(process.IsValid(), PROCESS_IS_VALID)
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+
+ thread = lldbutil.get_stopped_thread(process,
+ lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "Failed to get thread.")
+
+ frame = thread.GetFrameAtIndex(0)
+ self.assertTrue(frame.IsValid(), "Failed to get frame.")
+
+ read_value = frame.FindValue('g_watch_me_read',
+ lldb.eValueTypeVariableGlobal)
+ self.assertTrue(read_value.IsValid(), "Failed to find read value.")
+
+ error = lldb.SBError()
+
+ # resolve_location=True, read=True, write=False
+ read_watchpoint = read_value.Watch(True, True, False, error)
+ self.assertTrue(error.Success(),
+ "Error while setting watchpoint: %s" %
+ error.GetCString())
+ self.assertTrue(read_watchpoint, "Failed to set read watchpoint.")
+
+ thread.StepOver()
+ self.assertTrue(thread.GetStopReason() == lldb.eStopReasonWatchpoint,
+ STOPPED_DUE_TO_WATCHPOINT)
+ self.assertTrue(thread.GetStopDescription(20) == 'watchpoint 1')
+
+ process.Continue()
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+ self.assertTrue(thread.GetStopDescription(20) == 'step over')
+
+ self.step_inst_for_watchpoint(1)
+
+ write_value = frame.FindValue('g_watch_me_write',
+ lldb.eValueTypeVariableGlobal)
+ self.assertTrue(write_value, "Failed to find write value.")
+
+ # Most of the MIPS boards provide only one H/W watchpoints, and S/W watchpoints are not supported yet
+ arch = self.getArchitecture()
+ if arch in ['mips', 'mipsel', 'mips64', 'mips64el']:
+ self.runCmd("watchpoint delete 1")
+
+ # resolve_location=True, read=False, write=True
+ write_watchpoint = write_value.Watch(True, False, True, error)
+ self.assertTrue(read_watchpoint, "Failed to set write watchpoint.")
+ self.assertTrue(error.Success(),
+ "Error while setting watchpoint: %s" %
+ error.GetCString())
+
+ thread.StepOver()
+ self.assertTrue(thread.GetStopReason() == lldb.eStopReasonWatchpoint,
+ STOPPED_DUE_TO_WATCHPOINT)
+ self.assertTrue(thread.GetStopDescription(20) == 'watchpoint 2')
+
+ process.Continue()
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+ self.assertTrue(thread.GetStopDescription(20) == 'step over')
+
+ self.step_inst_for_watchpoint(2)
+
+ def step_inst_for_watchpoint(self, wp_id):
+ watchpoint_hit = False
+ current_line = self.frame().GetLineEntry().GetLine()
+ while self.frame().GetLineEntry().GetLine() == current_line:
+ self.thread().StepInstruction(False) # step_over=False
+ stop_reason = self.thread().GetStopReason()
+ if stop_reason == lldb.eStopReasonWatchpoint:
+ self.assertFalse(watchpoint_hit, "Watchpoint already hit.")
+ expected_stop_desc = "watchpoint %d" % wp_id
+ actual_stop_desc = self.thread().GetStopDescription(20)
+ self.assertTrue(actual_stop_desc == expected_stop_desc,
+ "Watchpoint ID didn't match.")
+ watchpoint_hit = True
+ else:
+ self.assertTrue(stop_reason == lldb.eStopReasonPlanComplete,
+ STOPPED_DUE_TO_STEP_IN)
+ self.assertTrue(watchpoint_hit, "Watchpoint never hit.")
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/step_over_watchpoint/main.c b/packages/Python/lldbsuite/test/functionalities/watchpoint/step_over_watchpoint/main.c
new file mode 100644
index 000000000000..2d87d9a2f73f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/step_over_watchpoint/main.c
@@ -0,0 +1,19 @@
+char g_watch_me_read;
+char g_watch_me_write;
+char g_temp;
+
+void watch_read() {
+ g_temp = g_watch_me_read;
+}
+
+void watch_write() {
+ g_watch_me_write = g_temp;
+}
+
+int main() {
+ watch_read();
+ g_temp = g_watch_me_read;
+ watch_write();
+ g_watch_me_write = g_temp;
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/variable_out_of_scope/Makefile b/packages/Python/lldbsuite/test/functionalities/watchpoint/variable_out_of_scope/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/variable_out_of_scope/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/variable_out_of_scope/TestWatchedVarHitWhenInScope.py b/packages/Python/lldbsuite/test/functionalities/watchpoint/variable_out_of_scope/TestWatchedVarHitWhenInScope.py
new file mode 100644
index 000000000000..21f1fb68426b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/variable_out_of_scope/TestWatchedVarHitWhenInScope.py
@@ -0,0 +1,83 @@
+"""
+Test that a variable watchpoint should only hit when in scope.
+"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class WatchedVariableHitWhenInScopeTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ #
+ # This test depends on not tracking watchpoint expression hits if we have
+ # left the watchpoint scope. We will provide such an ability at some point
+ # but the way this was done was incorrect, and it is unclear that for the
+ # most part that's not what folks mostly want, so we have to provide a
+ # clearer API to express this.
+ #
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Our simple source filename.
+ self.source = 'main.c'
+ self.exe_name = self.testMethodName
+ self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name}
+
+ @unittest2.expectedFailure("rdar://problem/18685649")
+ def test_watched_var_should_only_hit_when_in_scope(self):
+ """Test that a variable watchpoint should only hit when in scope."""
+ self.build(dictionary=self.d)
+ self.setTearDownCleanup(dictionary=self.d)
+
+ exe = os.path.join(os.getcwd(), self.exe_name)
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Add a breakpoint to set a watchpoint when stopped in main.
+ lldbutil.run_break_set_by_symbol (self, "main", num_expected_locations=-1)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # We should be stopped again due to the breakpoint.
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Now let's set a watchpoint for 'c.a'.
+ # There should be only one watchpoint hit (see main.c).
+ self.expect("watchpoint set variable c.a", WATCHPOINT_CREATED,
+ substrs = ['Watchpoint created', 'size = 4', 'type = w'])
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should be 0 initially.
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = 0'])
+
+ self.runCmd("process continue")
+
+ # We should be stopped again due to the watchpoint (write type), but
+ # only once. The stop reason of the thread should be watchpoint.
+ self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT,
+ substrs = ['stopped',
+ 'stop reason = watchpoint'])
+
+ self.runCmd("process continue")
+ # Don't expect the read of 'global' to trigger a stop exception.
+ # The process status should be 'exited'.
+ self.expect("process status",
+ substrs = ['exited'])
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should now be 1.
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = 1'])
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/variable_out_of_scope/main.c b/packages/Python/lldbsuite/test/functionalities/watchpoint/variable_out_of_scope/main.c
new file mode 100644
index 000000000000..1bf7a00ac837
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/variable_out_of_scope/main.c
@@ -0,0 +1,15 @@
+typedef struct
+{
+ int a;
+ float b;
+} mystruct;
+
+int main()
+{
+ mystruct c;
+
+ c.a = 5;
+ c.b = 3.6;
+
+ return 0;
+} \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/Makefile b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/TestWatchpointCommands.py b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/TestWatchpointCommands.py
new file mode 100644
index 000000000000..339de45a085a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/TestWatchpointCommands.py
@@ -0,0 +1,313 @@
+"""
+Test watchpoint list, enable, disable, and delete commands.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class WatchpointCommandsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Our simple source filename.
+ self.source = 'main.c'
+ # Find the line number to break inside main().
+ self.line = line_number(self.source, '// Set break point at this line.')
+ self.line2 = line_number(self.source, '// Set 2nd break point for disable_then_enable test case.')
+ # And the watchpoint variable declaration line number.
+ self.decl = line_number(self.source, '// Watchpoint variable declaration.')
+ # Build dictionary to have unique executable names for each test method.
+ self.exe_name = self.testMethodName
+ self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name}
+
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446") # WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows
+ def test_rw_watchpoint(self):
+ """Test read_write watchpoint and expect to stop two times."""
+ self.build(dictionary=self.d)
+ self.setTearDownCleanup(dictionary=self.d)
+
+ exe = os.path.join(os.getcwd(), self.exe_name)
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Add a breakpoint to set a watchpoint when stopped on the breakpoint.
+ lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # We should be stopped again due to the breakpoint.
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Now let's set a read_write-type watchpoint for 'global'.
+ # There should be two watchpoint hits (see main.c).
+ self.expect("watchpoint set variable -w read_write global", WATCHPOINT_CREATED,
+ substrs = ['Watchpoint created', 'size = 4', 'type = rw',
+ '%s:%d' % (self.source, self.decl)])
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should be 0 initially.
+ self.expect("watchpoint list -v",
+ substrs = ['Number of supported hardware watchpoints:',
+ 'hit_count = 0'])
+
+ self.runCmd("process continue")
+
+ # We should be stopped again due to the watchpoint (read_write type).
+ # The stop reason of the thread should be watchpoint.
+ self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT,
+ substrs = ['stop reason = watchpoint'])
+
+ self.runCmd("process continue")
+
+ # We should be stopped again due to the watchpoint (read_write type).
+ # The stop reason of the thread should be watchpoint.
+ self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT,
+ substrs = ['stop reason = watchpoint'])
+
+ self.runCmd("process continue")
+
+ # There should be no more watchpoint hit and the process status should
+ # be 'exited'.
+ self.expect("process status",
+ substrs = ['exited'])
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should now be 2.
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = 2'])
+
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446") # WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows
+ def test_rw_watchpoint_delete(self):
+ """Test delete watchpoint and expect not to stop for watchpoint."""
+ self.build(dictionary=self.d)
+ self.setTearDownCleanup(dictionary=self.d)
+
+ exe = os.path.join(os.getcwd(), self.exe_name)
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Add a breakpoint to set a watchpoint when stopped on the breakpoint.
+ lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # We should be stopped again due to the breakpoint.
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Now let's set a read_write-type watchpoint for 'global'.
+ # There should be two watchpoint hits (see main.c).
+ self.expect("watchpoint set variable -w read_write global", WATCHPOINT_CREATED,
+ substrs = ['Watchpoint created', 'size = 4', 'type = rw',
+ '%s:%d' % (self.source, self.decl)])
+
+ # Delete the watchpoint immediately, but set auto-confirm to true first.
+ self.runCmd("settings set auto-confirm true")
+ self.expect("watchpoint delete",
+ substrs = ['All watchpoints removed.'])
+ # Restore the original setting of auto-confirm.
+ self.runCmd("settings clear auto-confirm")
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ self.runCmd("watchpoint list -v")
+
+ self.runCmd("process continue")
+
+ # There should be no more watchpoint hit and the process status should
+ # be 'exited'.
+ self.expect("process status",
+ substrs = ['exited'])
+
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446") # WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows
+ def test_rw_watchpoint_set_ignore_count(self):
+ """Test watchpoint ignore count and expect to not to stop at all."""
+ self.build(dictionary=self.d)
+ self.setTearDownCleanup(dictionary=self.d)
+
+ exe = os.path.join(os.getcwd(), self.exe_name)
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Add a breakpoint to set a watchpoint when stopped on the breakpoint.
+ lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # We should be stopped again due to the breakpoint.
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Now let's set a read_write-type watchpoint for 'global'.
+ # There should be two watchpoint hits (see main.c).
+ self.expect("watchpoint set variable -w read_write global", WATCHPOINT_CREATED,
+ substrs = ['Watchpoint created', 'size = 4', 'type = rw',
+ '%s:%d' % (self.source, self.decl)])
+
+ # Set the ignore count of the watchpoint immediately.
+ self.expect("watchpoint ignore -i 2",
+ substrs = ['All watchpoints ignored.'])
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # Expect to find an ignore_count of 2.
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = 0', 'ignore_count = 2'])
+
+ self.runCmd("process continue")
+
+ # There should be no more watchpoint hit and the process status should
+ # be 'exited'.
+ self.expect("process status",
+ substrs = ['exited'])
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # Expect to find a hit_count of 2 as well.
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = 2', 'ignore_count = 2'])
+
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446") # WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows
+ def test_rw_disable_after_first_stop(self):
+ """Test read_write watchpoint but disable it after the first stop."""
+ self.build(dictionary=self.d)
+ self.setTearDownCleanup(dictionary=self.d)
+
+ exe = os.path.join(os.getcwd(), self.exe_name)
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Add a breakpoint to set a watchpoint when stopped on the breakpoint.
+ lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # We should be stopped again due to the breakpoint.
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Now let's set a read_write-type watchpoint for 'global'.
+ # There should be two watchpoint hits (see main.c).
+ self.expect("watchpoint set variable -w read_write global", WATCHPOINT_CREATED,
+ substrs = ['Watchpoint created', 'size = 4', 'type = rw',
+ '%s:%d' % (self.source, self.decl)])
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should be 0 initially.
+ self.expect("watchpoint list -v",
+ substrs = ['state = enabled', 'hit_count = 0'])
+
+ self.runCmd("process continue")
+
+ # We should be stopped again due to the watchpoint (read_write type).
+ # The stop reason of the thread should be watchpoint.
+ self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT,
+ substrs = ['stop reason = watchpoint'])
+
+ # Before continuing, we'll disable the watchpoint, which means we won't
+ # stop again after this.
+ self.runCmd("watchpoint disable")
+
+ self.expect("watchpoint list -v",
+ substrs = ['state = disabled', 'hit_count = 1'])
+
+ self.runCmd("process continue")
+
+ # There should be no more watchpoint hit and the process status should
+ # be 'exited'.
+ self.expect("process status",
+ substrs = ['exited'])
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should be 1.
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = 1'])
+
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446") # WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows
+ def test_rw_disable_then_enable(self):
+ """Test read_write watchpoint, disable initially, then enable it."""
+ self.build(dictionary=self.d)
+ self.setTearDownCleanup(dictionary=self.d)
+
+ exe = os.path.join(os.getcwd(), self.exe_name)
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Add a breakpoint to set a watchpoint when stopped on the breakpoint.
+ lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1)
+ lldbutil.run_break_set_by_file_and_line (self, None, self.line2, num_expected_locations=1)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # We should be stopped again due to the breakpoint.
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Now let's set a read_write-type watchpoint for 'global'.
+ # There should be two watchpoint hits (see main.c).
+ self.expect("watchpoint set variable -w read_write global", WATCHPOINT_CREATED,
+ substrs = ['Watchpoint created', 'size = 4', 'type = rw',
+ '%s:%d' % (self.source, self.decl)])
+
+ # Immediately, we disable the watchpoint. We won't be stopping due to a
+ # watchpoint after this.
+ self.runCmd("watchpoint disable")
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should be 0 initially.
+ self.expect("watchpoint list -v",
+ substrs = ['state = disabled', 'hit_count = 0'])
+
+ self.runCmd("process continue")
+
+ # We should be stopped again due to the breakpoint.
+ self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stop reason = breakpoint'])
+
+ # Before continuing, we'll enable the watchpoint, which means we will
+ # stop again after this.
+ self.runCmd("watchpoint enable")
+
+ self.expect("watchpoint list -v",
+ substrs = ['state = enabled', 'hit_count = 0'])
+
+ self.runCmd("process continue")
+
+ # We should be stopped again due to the watchpoint (read_write type).
+ # The stop reason of the thread should be watchpoint.
+ self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT,
+ substrs = ['stop reason = watchpoint'])
+
+ self.runCmd("process continue")
+
+ # There should be no more watchpoint hit and the process status should
+ # be 'exited'.
+ self.expect("process status",
+ substrs = ['exited'])
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should be 1.
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = 1'])
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/Makefile b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/Makefile
new file mode 100644
index 000000000000..ee6b9cc62b40
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/TestWatchpointCommandLLDB.py b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/TestWatchpointCommandLLDB.py
new file mode 100644
index 000000000000..f2bf90866330
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/TestWatchpointCommandLLDB.py
@@ -0,0 +1,139 @@
+"""
+Test 'watchpoint command'.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class WatchpointLLDBCommandTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Our simple source filename.
+ self.source = 'main.cpp'
+ # Find the line number to break inside main().
+ self.line = line_number(self.source, '// Set break point at this line.')
+ # And the watchpoint variable declaration line number.
+ self.decl = line_number(self.source, '// Watchpoint variable declaration.')
+ # Build dictionary to have unique executable names for each test method.
+ self.exe_name = 'a%d.out' % self.test_number
+ self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name}
+
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446") # WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows
+ def test_watchpoint_command(self):
+ """Test 'watchpoint command'."""
+ self.build(dictionary=self.d)
+ self.setTearDownCleanup(dictionary=self.d)
+
+ exe = os.path.join(os.getcwd(), self.exe_name)
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Add a breakpoint to set a watchpoint when stopped on the breakpoint.
+ lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # We should be stopped again due to the breakpoint.
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Now let's set a write-type watchpoint for 'global'.
+ self.expect("watchpoint set variable -w write global", WATCHPOINT_CREATED,
+ substrs = ['Watchpoint created', 'size = 4', 'type = w',
+ '%s:%d' % (self.source, self.decl)])
+
+ self.runCmd('watchpoint command add 1 -o "expr -- cookie = 777"')
+
+ # List the watchpoint command we just added.
+ self.expect("watchpoint command list 1",
+ substrs = ['expr -- cookie = 777'])
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should be 0 initially.
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = 0'])
+
+ self.runCmd("process continue")
+
+ # We should be stopped again due to the watchpoint (write type).
+ # The stop reason of the thread should be watchpoint.
+ self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT,
+ substrs = ['stop reason = watchpoint'])
+
+ # Check that the watchpoint snapshoting mechanism is working.
+ self.expect("watchpoint list -v",
+ substrs = ['old value:', ' = 0',
+ 'new value:', ' = 1'])
+
+ # The watchpoint command "forced" our global variable 'cookie' to become 777.
+ self.expect("frame variable --show-globals cookie",
+ substrs = ['(int32_t)', 'cookie = 777'])
+
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446") # WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows
+ def test_watchpoint_command_can_disable_a_watchpoint(self):
+ """Test that 'watchpoint command' action can disable a watchpoint after it is triggered."""
+ self.build(dictionary=self.d)
+ self.setTearDownCleanup(dictionary=self.d)
+
+ exe = os.path.join(os.getcwd(), self.exe_name)
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Add a breakpoint to set a watchpoint when stopped on the breakpoint.
+ lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # We should be stopped again due to the breakpoint.
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Now let's set a write-type watchpoint for 'global'.
+ self.expect("watchpoint set variable -w write global", WATCHPOINT_CREATED,
+ substrs = ['Watchpoint created', 'size = 4', 'type = w',
+ '%s:%d' % (self.source, self.decl)])
+
+ self.runCmd('watchpoint command add 1 -o "watchpoint disable 1"')
+
+ # List the watchpoint command we just added.
+ self.expect("watchpoint command list 1",
+ substrs = ['watchpoint disable 1'])
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should be 0 initially.
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = 0'])
+
+ self.runCmd("process continue")
+
+ # We should be stopped again due to the watchpoint (write type).
+ # The stop reason of the thread should be watchpoint.
+ self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT,
+ substrs = ['stop reason = watchpoint'])
+
+ # Check that the watchpoint has been disabled.
+ self.expect("watchpoint list -v",
+ substrs = ['disabled'])
+
+ self.runCmd("process continue")
+
+ # There should be no more watchpoint hit and the process status should
+ # be 'exited'.
+ self.expect("process status",
+ substrs = ['exited'])
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/TestWatchpointCommandPython.py b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/TestWatchpointCommandPython.py
new file mode 100644
index 000000000000..a476aebb8db9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/TestWatchpointCommandPython.py
@@ -0,0 +1,87 @@
+"""
+Test 'watchpoint command'.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class WatchpointPythonCommandTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Our simple source filename.
+ self.source = 'main.cpp'
+ # Find the line number to break inside main().
+ self.line = line_number(self.source, '// Set break point at this line.')
+ # And the watchpoint variable declaration line number.
+ self.decl = line_number(self.source, '// Watchpoint variable declaration.')
+ # Build dictionary to have unique executable names for each test method.
+ self.exe_name = self.testMethodName
+ self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name}
+
+ @skipIfFreeBSD # timing out on buildbot
+ @expectedFailureWindows("llvm.org/pr24446") # WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ def test_watchpoint_command(self):
+ """Test 'watchpoint command'."""
+ self.build(dictionary=self.d)
+ self.setTearDownCleanup(dictionary=self.d)
+
+ exe = os.path.join(os.getcwd(), self.exe_name)
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Add a breakpoint to set a watchpoint when stopped on the breakpoint.
+ lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1)
+# self.expect("breakpoint set -l %d" % self.line, BREAKPOINT_CREATED,
+# startstr = "Breakpoint created: 1: file ='%s', line = %d, locations = 1" %
+# (self.source, self.line))#
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # We should be stopped again due to the breakpoint.
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Now let's set a write-type watchpoint for 'global'.
+ self.expect("watchpoint set variable -w write global", WATCHPOINT_CREATED,
+ substrs = ['Watchpoint created', 'size = 4', 'type = w',
+ '%s:%d' % (self.source, self.decl)])
+
+ self.runCmd('watchpoint command add -s python 1 -o \'frame.EvaluateExpression("cookie = 777")\'')
+
+ # List the watchpoint command we just added.
+ self.expect("watchpoint command list 1",
+ substrs = ['frame.EvaluateExpression', 'cookie = 777'])
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should be 0 initially.
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = 0'])
+
+ self.runCmd("process continue")
+
+ # We should be stopped again due to the watchpoint (write type).
+ # The stop reason of the thread should be watchpoint.
+ self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT,
+ substrs = ['stop reason = watchpoint'])
+
+ # Check that the watchpoint snapshoting mechanism is working.
+ self.expect("watchpoint list -v",
+ substrs = ['old value:', ' = 0',
+ 'new value:', ' = 1'])
+
+ # The watchpoint command "forced" our global variable 'cookie' to become 777.
+ self.expect("frame variable --show-globals cookie",
+ substrs = ['(int32_t)', 'cookie = 777'])
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/main.cpp b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/main.cpp
new file mode 100644
index 000000000000..6cb80c62217e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/command/main.cpp
@@ -0,0 +1,28 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+#include <stdint.h>
+
+int32_t global = 0; // Watchpoint variable declaration.
+int32_t cookie = 0;
+
+static void modify(int32_t &var) {
+ ++var;
+}
+
+int main(int argc, char** argv) {
+ int local = 0;
+ printf("&global=%p\n", &global);
+ printf("about to write to 'global'...\n"); // Set break point at this line.
+ for (int i = 0; i < 10; ++i)
+ modify(global);
+
+ printf("global=%d\n", global);
+ printf("cookie=%d\n", cookie);
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/condition/Makefile b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/condition/Makefile
new file mode 100644
index 000000000000..ee6b9cc62b40
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/condition/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/condition/TestWatchpointConditionCmd.py b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/condition/TestWatchpointConditionCmd.py
new file mode 100644
index 000000000000..355204a4ce1e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/condition/TestWatchpointConditionCmd.py
@@ -0,0 +1,78 @@
+"""
+Test watchpoint modify command to set condition on a watchpoint.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class WatchpointConditionCmdTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Our simple source filename.
+ self.source = 'main.cpp'
+ # Find the line number to break inside main().
+ self.line = line_number(self.source, '// Set break point at this line.')
+ # And the watchpoint variable declaration line number.
+ self.decl = line_number(self.source, '// Watchpoint variable declaration.')
+ # Build dictionary to have unique executable names for each test method.
+ self.exe_name = self.testMethodName
+ self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name}
+
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446") # WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows
+ def test_watchpoint_cond(self):
+ """Test watchpoint condition."""
+ self.build(dictionary=self.d)
+ self.setTearDownCleanup(dictionary=self.d)
+
+ exe = os.path.join(os.getcwd(), self.exe_name)
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Add a breakpoint to set a watchpoint when stopped on the breakpoint.
+ lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # We should be stopped again due to the breakpoint.
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Now let's set a write-type watchpoint for 'global'.
+ # With a condition of 'global==5'.
+ self.expect("watchpoint set variable -w write global", WATCHPOINT_CREATED,
+ substrs = ['Watchpoint created', 'size = 4', 'type = w',
+ '%s:%d' % (self.source, self.decl)])
+
+ self.runCmd("watchpoint modify -c 'global==5'")
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should be 0 initially.
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = 0', 'global==5'])
+
+ self.runCmd("process continue")
+
+ # We should be stopped again due to the watchpoint (write type).
+ # The stop reason of the thread should be watchpoint.
+ self.expect("thread backtrace", STOPPED_DUE_TO_WATCHPOINT,
+ substrs = ['stop reason = watchpoint'])
+ self.expect("frame variable --show-globals global",
+ substrs = ['(int32_t)', 'global = 5'])
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should now be 2.
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = 5'])
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/condition/main.cpp b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/condition/main.cpp
new file mode 100644
index 000000000000..f4c3527f8af2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/condition/main.cpp
@@ -0,0 +1,28 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+#include <stdint.h>
+
+int32_t global = 0; // Watchpoint variable declaration.
+
+static void modify(int32_t &var) {
+ ++var;
+}
+
+int main(int argc, char** argv) {
+ int local = 0;
+ printf("&global=%p\n", &global);
+ printf("about to write to 'global'...\n"); // Set break point at this line.
+ // When stopped, watch 'global',
+ // for the condition "global == 5".
+ for (int i = 0; i < 10; ++i)
+ modify(global);
+
+ printf("global=%d\n", global);
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/main.c b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/main.c
new file mode 100644
index 000000000000..b20eaf494fbf
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_commands/main.c
@@ -0,0 +1,24 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+#include <stdint.h>
+
+int32_t global = 10; // Watchpoint variable declaration.
+
+int main(int argc, char** argv) {
+ int local = 0;
+ printf("&global=%p\n", &global);
+ printf("about to write to 'global'...\n"); // Set break point at this line.
+ // When stopped, watch 'global'.
+ global = 20;
+ local += argc;
+ ++local; // Set 2nd break point for disable_then_enable test case.
+ printf("local: %d\n", local);
+ printf("global=%d\n", global);
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_events/Makefile b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_events/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_events/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_events/TestWatchpointEvents.py b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_events/TestWatchpointEvents.py
new file mode 100644
index 000000000000..e4d6e019c20e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_events/TestWatchpointEvents.py
@@ -0,0 +1,89 @@
+"""Test that adding, deleting and modifying watchpoints sends the appropriate events."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TestWatchpointEvents (TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers that we will step to in main:
+ self.main_source = "main.c"
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446") # WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows
+ def test_with_python_api(self):
+ """Test that adding, deleting and modifying watchpoints sends the appropriate events."""
+ self.build()
+
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ self.main_source_spec = lldb.SBFileSpec (self.main_source)
+
+ break_in_main = target.BreakpointCreateBySourceRegex ('// Put a breakpoint here.', self.main_source_spec)
+ self.assertTrue(break_in_main, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, break_in_main)
+
+ if len(threads) != 1:
+ self.fail ("Failed to stop at first breakpoint in main.")
+
+ thread = threads[0]
+ frame = thread.GetFrameAtIndex(0)
+ local_var = frame.FindVariable ("local_var")
+ self.assertTrue (local_var.IsValid())
+
+ self.listener = lldb.SBListener("com.lldb.testsuite_listener")
+ self.target_bcast = target.GetBroadcaster()
+ self.target_bcast.AddListener (self.listener, lldb.SBTarget.eBroadcastBitWatchpointChanged)
+ self.listener.StartListeningForEvents (self.target_bcast, lldb.SBTarget.eBroadcastBitWatchpointChanged)
+
+ error = lldb.SBError()
+ local_watch = local_var.Watch(True, True, True, error)
+ if not error.Success():
+ self.fail ("Failed to make watchpoint for local_var: %s"%(error.GetCString()))
+
+ self.GetWatchpointEvent (lldb.eWatchpointEventTypeAdded)
+ # Now change some of the features of this watchpoint and make sure we get events:
+ local_watch.SetEnabled(False)
+ self.GetWatchpointEvent (lldb.eWatchpointEventTypeDisabled)
+
+ local_watch.SetIgnoreCount(10)
+ self.GetWatchpointEvent (lldb.eWatchpointEventTypeIgnoreChanged)
+
+ local_watch.SetCondition ("1 == 2")
+ self.GetWatchpointEvent (lldb.eWatchpointEventTypeConditionChanged)
+
+ def GetWatchpointEvent (self, event_type):
+ # We added a watchpoint so we should get a watchpoint added event.
+ event = lldb.SBEvent()
+ success = self.listener.WaitForEvent (1, event)
+ self.assertTrue(success == True, "Successfully got watchpoint event")
+ self.assertTrue (lldb.SBWatchpoint.EventIsWatchpointEvent(event), "Event is a watchpoint event.")
+ found_type = lldb.SBWatchpoint.GetWatchpointEventTypeFromEvent (event)
+ self.assertTrue (found_type == event_type, "Event is not correct type, expected: %d, found: %d"%(event_type, found_type))
+ # There shouldn't be another event waiting around:
+ found_event = self.listener.PeekAtNextEventForBroadcasterWithType (self.target_bcast, lldb.SBTarget.eBroadcastBitBreakpointChanged, event)
+ if found_event:
+ print("Found an event I didn't expect: ", event)
+
+ self.assertTrue (not found_event, "Only one event per change.")
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_events/main.c b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_events/main.c
new file mode 100644
index 000000000000..4b917536a161
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_events/main.c
@@ -0,0 +1,9 @@
+#include <stdio.h>
+
+int
+main (int argc, char **argv)
+{
+ int local_var = 10;
+ printf ("local_var is: %d.\n", local_var++); // Put a breakpoint here.
+ return local_var;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_on_vectors/Makefile b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_on_vectors/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_on_vectors/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_on_vectors/TestValueOfVectorVariable.py b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_on_vectors/TestValueOfVectorVariable.py
new file mode 100644
index 000000000000..73752d2d18d5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_on_vectors/TestValueOfVectorVariable.py
@@ -0,0 +1,47 @@
+"""
+Test displayed value of a vector variable while doing watchpoint operations
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TestValueOfVectorVariableTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446") # WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows
+ def test_value_of_vector_variable_using_watchpoint_set(self):
+ """Test verify displayed value of vector variable."""
+ self.build(dictionary=self.d)
+ self.setTearDownCleanup(dictionary=self.d)
+ self.value_of_vector_variable_with_watchpoint_set()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Our simple source filename.
+ self.source = 'main.c'
+ self.exe_name = 'a.out'
+ self.d = {'C_SOURCES': self.source, 'EXE': self.exe_name}
+
+ def value_of_vector_variable_with_watchpoint_set(self):
+ """Test verify displayed value of vector variable"""
+ exe = os.path.join(os.getcwd(), 'a.out')
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Set break to get a frame
+ self.runCmd("b main")
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Value of a vector variable should be displayed correctly
+ self.expect("watchpoint set variable global_vector", WATCHPOINT_CREATED,
+ substrs = ['new value: (1, 2, 3, 4)'])
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_on_vectors/main.c b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_on_vectors/main.c
new file mode 100644
index 000000000000..98f8c477eb31
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_on_vectors/main.c
@@ -0,0 +1,16 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+typedef char v4i8 __attribute__ ((vector_size(4)));
+v4i8 global_vector = {1, 2, 3, 4};
+
+int
+main ()
+{
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/Makefile b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/Makefile
new file mode 100644
index 000000000000..8817fff55e8c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+ENABLE_THREADS := YES
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/TestWatchLocationWithWatchSet.py b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/TestWatchLocationWithWatchSet.py
new file mode 100644
index 000000000000..6bdac7024847
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/TestWatchLocationWithWatchSet.py
@@ -0,0 +1,89 @@
+"""
+Test lldb watchpoint that uses 'watchpoint set -w write -s size' to watch a pointed location with size.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class WatchLocationUsingWatchpointSetTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Our simple source filename.
+ self.source = 'main.cpp'
+ # Find the line number to break inside main().
+ self.line = line_number(self.source, '// Set break point at this line.')
+ # This is for verifying that watch location works.
+ self.violating_func = "do_bad_thing_with_location";
+ # Build dictionary to have unique executable names for each test method.
+
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446") # WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows
+ def test_watchlocation_using_watchpoint_set(self):
+ """Test watching a location with 'watchpoint set expression -w write -s size' option."""
+ self.build()
+ self.setTearDownCleanup()
+
+ exe = os.path.join(os.getcwd(), 'a.out')
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Add a breakpoint to set a watchpoint when stopped on the breakpoint.
+ lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # We should be stopped again due to the breakpoint.
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Now let's set a write-type watchpoint pointed to by 'g_char_ptr' and
+ # with offset as 7.
+ # The main.cpp, by design, misbehaves by not following the agreed upon
+ # protocol of only accessing the allowable index range of [0, 6].
+ self.expect("watchpoint set expression -w write -s 1 -- g_char_ptr + 7", WATCHPOINT_CREATED,
+ substrs = ['Watchpoint created', 'size = 1', 'type = w'])
+ self.runCmd("expr unsigned val = g_char_ptr[7]; val")
+ self.expect(self.res.GetOutput().splitlines()[0], exe=False,
+ endstr = ' = 0')
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should be 0 initially.
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = 0'])
+
+ self.runCmd("process continue")
+
+ # We should be stopped again due to the watchpoint (write type), but
+ # only once. The stop reason of the thread should be watchpoint.
+ self.expect("thread list", STOPPED_DUE_TO_WATCHPOINT,
+ substrs = ['stopped',
+ 'stop reason = watchpoint',
+ self.violating_func])
+
+ # Switch to the thread stopped due to watchpoint and issue some commands.
+ self.switch_to_thread_with_stop_reason(lldb.eStopReasonWatchpoint)
+ self.runCmd("thread backtrace")
+ self.runCmd("expr unsigned val = g_char_ptr[7]; val")
+ self.expect(self.res.GetOutput().splitlines()[0], exe=False,
+ endstr = ' = 99')
+
+ # Use the '-v' option to do verbose listing of the watchpoint.
+ # The hit count should now be the same as the number of threads that
+ # stopped on a watchpoint.
+ threads = lldbutil.get_stopped_threads(self.process(), lldb.eStopReasonWatchpoint)
+ self.expect("watchpoint list -v",
+ substrs = ['hit_count = %d' % len(threads)])
+
+ self.runCmd("thread backtrace all")
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/TestWatchpointSetErrorCases.py b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/TestWatchpointSetErrorCases.py
new file mode 100644
index 000000000000..27c759e6fb64
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/TestWatchpointSetErrorCases.py
@@ -0,0 +1,67 @@
+"""
+Test error cases for the 'watchpoint set' command to make sure it errors out when necessary.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class WatchpointSetErrorTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Our simple source filename.
+ self.source = 'main.cpp'
+ # Find the line number to break inside main().
+ self.line = line_number(self.source, '// Set break point at this line.')
+ # Build dictionary to have unique executable names for each test method.
+
+ def test_error_cases_with_watchpoint_set(self):
+ """Test error cases with the 'watchpoint set' command."""
+ self.build()
+ self.setTearDownCleanup()
+
+ exe = os.path.join(os.getcwd(), 'a.out')
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Add a breakpoint to set a watchpoint when stopped on the breakpoint.
+ lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=1)
+
+ # Run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # We should be stopped again due to the breakpoint.
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Try some error conditions:
+
+ # 'watchpoint set' is now a multiword command.
+ self.expect("watchpoint set",
+ substrs = ['The following subcommands are supported:',
+ 'expression',
+ 'variable'])
+ self.runCmd("watchpoint set variable -w read_write", check=False)
+
+ # 'watchpoint set expression' with '-w' or '-s' specified now needs
+ # an option terminator and a raw expression after that.
+ self.expect("watchpoint set expression -w write --", error=True,
+ startstr = 'error: ')
+
+ # It's an error if the expression did not evaluate to an address.
+ self.expect("watchpoint set expression MyAggregateDataType", error=True,
+ startstr = 'error: expression did not evaluate to an address')
+
+ # Wrong size parameter is an error.
+ self.expect("watchpoint set variable -s -128", error=True,
+ substrs = ['invalid enumeration value'])
diff --git a/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/main.cpp b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/main.cpp
new file mode 100644
index 000000000000..796c0ef359df
--- /dev/null
+++ b/packages/Python/lldbsuite/test/functionalities/watchpoint/watchpoint_set_command/main.cpp
@@ -0,0 +1,121 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <chrono>
+#include <condition_variable>
+#include <cstdio>
+#include <random>
+#include <thread>
+
+std::default_random_engine g_random_engine{std::random_device{}()};
+std::uniform_int_distribution<> g_distribution{0, 3000000};
+std::condition_variable g_condition_variable;
+std::mutex g_mutex;
+int g_count;
+
+char *g_char_ptr = nullptr;
+
+void
+barrier_wait()
+{
+ std::unique_lock<std::mutex> lock{g_mutex};
+ if (--g_count > 0)
+ g_condition_variable.wait(lock);
+ else
+ g_condition_variable.notify_all();
+}
+
+void
+do_bad_thing_with_location(unsigned index, char *char_ptr, char new_val)
+{
+ unsigned what = new_val;
+ printf("new value written to array(%p) and index(%u) = %u\n", char_ptr, index, what);
+ char_ptr[index] = new_val;
+}
+
+uint32_t
+access_pool (bool flag = false)
+{
+ static std::mutex g_access_mutex;
+ static unsigned idx = 0; // Well-behaving thread only writes into indexs from 0..6.
+ if (!flag)
+ g_access_mutex.lock();
+
+ // idx valid range is [0, 6].
+ if (idx > 6)
+ idx = 0;
+
+ if (flag)
+ {
+ // Write into a forbidden area.
+ do_bad_thing_with_location(7, g_char_ptr, 99);
+ }
+
+ unsigned index = idx++;
+
+ if (!flag)
+ g_access_mutex.unlock();
+ return g_char_ptr[index];
+}
+
+void
+thread_func (uint32_t thread_index)
+{
+ printf ("%s (thread index = %u) startng...\n", __FUNCTION__, thread_index);
+
+ barrier_wait();
+
+ uint32_t count = 0;
+ uint32_t val;
+ while (count++ < 15)
+ {
+ // random micro second sleep from zero to 3 seconds
+ int usec = g_distribution(g_random_engine);
+ printf ("%s (thread = %u) doing a usleep (%d)...\n", __FUNCTION__, thread_index, usec);
+ std::this_thread::sleep_for(std::chrono::microseconds{usec});
+
+ if (count < 7)
+ val = access_pool ();
+ else
+ val = access_pool (true);
+
+ printf ("%s (thread = %u) after usleep access_pool returns %d (count=%d)...\n", __FUNCTION__, thread_index, val, count);
+ }
+ printf ("%s (thread index = %u) exiting...\n", __FUNCTION__, thread_index);
+}
+
+
+int main (int argc, char const *argv[])
+{
+ g_count = 4;
+ std::thread threads[3];
+
+ g_char_ptr = new char[10]{};
+
+ // Create 3 threads
+ for (auto &thread : threads)
+ thread = std::thread{thread_func, std::distance(threads, &thread)};
+
+ struct {
+ int a;
+ int b;
+ int c;
+ } MyAggregateDataType;
+
+ printf ("Before turning all three threads loose...\n"); // Set break point at this line.
+ barrier_wait();
+
+ // Join all of our threads
+ for (auto &thread : threads)
+ thread.join();
+
+ delete[] g_char_ptr;
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/help/TestHelp.py b/packages/Python/lldbsuite/test/help/TestHelp.py
new file mode 100644
index 000000000000..f51b6aa59f12
--- /dev/null
+++ b/packages/Python/lldbsuite/test/help/TestHelp.py
@@ -0,0 +1,165 @@
+"""
+Test some lldb help commands.
+
+See also CommandInterpreter::OutputFormattedHelpText().
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class HelpCommandTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @no_debug_info_test
+ def test_simplehelp(self):
+ """A simple test of 'help' command and its output."""
+ self.expect("help",
+ startstr = 'Debugger commands:')
+
+ self.expect("help -a", matching=False,
+ substrs = ['next'])
+
+ self.expect("help", matching=True,
+ substrs = ['next'])
+
+ @no_debug_info_test
+ def test_help_on_help(self):
+ """Testing the help on the help facility."""
+ self.expect("help help", matching=True,
+ substrs = ['--hide-aliases',
+ '--hide-user-commands'])
+
+ @no_debug_info_test
+ def version_number_string(self):
+ """Helper function to find the version number string of lldb."""
+ plist = os.path.join(os.environ["LLDB_SRC"], "resources", "LLDB-Info.plist")
+ try:
+ CFBundleVersionSegFound = False
+ with open(plist, 'r') as f:
+ for line in f:
+ if CFBundleVersionSegFound:
+ version_line = line.strip()
+ import re
+ m = re.match("<string>(.*)</string>", version_line)
+ if m:
+ version = m.group(1)
+ return version
+ else:
+ # Unsuccessful, let's juts break out of the for loop.
+ break
+
+ if line.find("<key>CFBundleVersion</key>") != -1:
+ # Found our match. The next line contains our version
+ # string, for example:
+ #
+ # <string>38</string>
+ CFBundleVersionSegFound = True
+
+ except:
+ # Just fallthrough...
+ import traceback
+ traceback.print_exc()
+ pass
+
+ # Use None to signify that we are not able to grok the version number.
+ return None
+
+ @no_debug_info_test
+ def test_help_arch(self):
+ """Test 'help arch' which should list of supported architectures."""
+ self.expect("help arch",
+ substrs = ['arm', 'x86_64', 'i386'])
+
+ @no_debug_info_test
+ def test_help_version(self):
+ """Test 'help version' and 'version' commands."""
+ self.expect("help version",
+ substrs = ['Show version of LLDB debugger.'])
+ version_str = self.version_number_string()
+ import re
+ match = re.match('[0-9]+', version_str)
+ if sys.platform.startswith("darwin"):
+ search_regexp = ['lldb-' + (version_str if match else '[0-9]+')]
+ else:
+ search_regexp = ['lldb version (\d|\.)+.*$']
+
+ self.expect("version",
+ patterns = search_regexp)
+
+ @no_debug_info_test
+ def test_help_should_not_crash_lldb(self):
+ """Command 'help disasm' should not crash lldb."""
+ self.runCmd("help disasm", check=False)
+ self.runCmd("help unsigned-integer")
+
+ @no_debug_info_test
+ def test_help_should_not_hang_emacsshell(self):
+ """Command 'settings set term-width 0' should not hang the help command."""
+ self.expect("settings set term-width 0",
+ COMMAND_FAILED_AS_EXPECTED, error=True,
+ substrs = ['error: 0 is out of range, valid values must be between'])
+ # self.runCmd("settings set term-width 0")
+ self.expect("help",
+ startstr = 'Debugger commands:')
+
+ @no_debug_info_test
+ def test_help_breakpoint_set(self):
+ """Test that 'help breakpoint set' does not print out redundant lines of:
+ 'breakpoint set [-s <shlib-name>] ...'."""
+ self.expect("help breakpoint set", matching=False,
+ substrs = ['breakpoint set [-s <shlib-name>]'])
+
+ @no_debug_info_test
+ def test_help_image_dump_symtab_should_not_crash(self):
+ """Command 'help image dump symtab' should not crash lldb."""
+ # 'image' is an alias for 'target modules'.
+ self.expect("help image dump symtab",
+ substrs = ['dump symtab',
+ 'sort-order'])
+
+ @no_debug_info_test
+ def test_help_image_du_sym_is_ambiguous(self):
+ """Command 'help image du sym' is ambiguous and spits out the list of candidates."""
+ self.expect("help image du sym",
+ COMMAND_FAILED_AS_EXPECTED, error=True,
+ substrs = ['error: ambiguous command image du sym',
+ 'symfile',
+ 'symtab'])
+
+ @no_debug_info_test
+ def test_help_image_du_line_should_work(self):
+ """Command 'help image du line-table' is not ambiguous and should work."""
+ # 'image' is an alias for 'target modules'.
+ self.expect("help image du line",
+ substrs = ['Dump the line table for one or more compilation units'])
+
+ @no_debug_info_test
+ def test_help_target_variable_syntax(self):
+ """Command 'help target variable' should display <variable-name> ..."""
+ self.expect("help target variable",
+ substrs = ['<variable-name> [<variable-name> [...]]'])
+
+ @no_debug_info_test
+ def test_help_watchpoint_and_its_args(self):
+ """Command 'help watchpoint', 'help watchpt-id', and 'help watchpt-id-list' should work."""
+ self.expect("help watchpoint",
+ substrs = ['delete', 'disable', 'enable', 'list'])
+ self.expect("help watchpt-id",
+ substrs = ['<watchpt-id>'])
+ self.expect("help watchpt-id-list",
+ substrs = ['<watchpt-id-list>'])
+
+ @no_debug_info_test
+ def test_help_watchpoint_set(self):
+ """Test that 'help watchpoint set' prints out 'expression' and 'variable'
+ as the possible subcommands."""
+ self.expect("help watchpoint set",
+ substrs = ['The following subcommands are supported:'],
+ patterns = ['expression +--',
+ 'variable +--'])
diff --git a/packages/Python/lldbsuite/test/issue_verification/Makefile b/packages/Python/lldbsuite/test/issue_verification/Makefile
new file mode 100644
index 000000000000..e7bd3f4dd792
--- /dev/null
+++ b/packages/Python/lldbsuite/test/issue_verification/Makefile
@@ -0,0 +1,4 @@
+LEVEL = ../make
+CXX_SOURCES := inline_rerun_inferior.cpp
+CXXFLAGS += -std=c++11
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/issue_verification/README.txt b/packages/Python/lldbsuite/test/issue_verification/README.txt
new file mode 100644
index 000000000000..0f1ae7f0ecfc
--- /dev/null
+++ b/packages/Python/lldbsuite/test/issue_verification/README.txt
@@ -0,0 +1,5 @@
+Tests in this directory are intentionally setup to
+fail, error, timeout, etc. to verify that the buildbots
+pick up errors. The tests in this directory will be
+parked/removed/renamed after verifying they trigger
+as expected.
diff --git a/packages/Python/lldbsuite/test/issue_verification/TestExpectedTimeout.py.park b/packages/Python/lldbsuite/test/issue_verification/TestExpectedTimeout.py.park
new file mode 100644
index 000000000000..67db8149f850
--- /dev/null
+++ b/packages/Python/lldbsuite/test/issue_verification/TestExpectedTimeout.py.park
@@ -0,0 +1,20 @@
+"""Tests that a timeout is detected by the testbot."""
+from __future__ import print_function
+
+import time
+
+import lldbsuite.test.lldbtest as lldbtest
+
+
+class ExpectedTimeoutTestCase(lldbtest.TestBase):
+ """Forces test timeout."""
+ mydir = lldbtest.TestBase.compute_mydir(__file__)
+
+ @lldbtest.expectedFailureAll()
+ def test_buildbot_sees_expected_timeout(self):
+ """Tests that expected timeout logic kicks in and is picked up."""
+ while True:
+ try:
+ time.sleep(1)
+ except:
+ print("ignoring exception during sleep")
diff --git a/packages/Python/lldbsuite/test/issue_verification/TestFail.py.park b/packages/Python/lldbsuite/test/issue_verification/TestFail.py.park
new file mode 100644
index 000000000000..da64bc0ea8c1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/issue_verification/TestFail.py.park
@@ -0,0 +1,16 @@
+"""Tests that a FAIL is detected by the testbot."""
+
+from __future__ import print_function
+
+import lldbsuite.test.lldbtest as lldbtest
+
+
+class FailTestCase(lldbtest.TestBase):
+ """Forces test failure."""
+ mydir = lldbtest.TestBase.compute_mydir(__file__)
+
+ def test_buildbot_catches_failure(self):
+ """Issues a failing test assertion."""
+ self.assertTrue(
+ False,
+ "This will always fail, buildbot should flag this.")
diff --git a/packages/Python/lldbsuite/test/issue_verification/TestRerunFail.py.park b/packages/Python/lldbsuite/test/issue_verification/TestRerunFail.py.park
new file mode 100644
index 000000000000..bcd1926d7404
--- /dev/null
+++ b/packages/Python/lldbsuite/test/issue_verification/TestRerunFail.py.park
@@ -0,0 +1,23 @@
+"""Tests that a flakey fail is rerun, and will pass on the rerun.
+Run this test with --rerun-all-issues specified to test that
+the tests fail on the first run, then pass on the second.
+Do not mark them as flakey as, at this time, flakey tests will
+run twice, thus causing the second run to succeed."""
+
+from __future__ import print_function
+
+import rerun_base
+
+import lldbsuite.test.lldbtest as lldbtest
+
+
+class RerunFailTestCase(rerun_base.RerunBaseTestCase):
+ """Forces test failure on first run, success on rerun."""
+ @lldbtest.no_debug_info_test
+ def test_buildbot_catches_failure(self):
+ """Issues a failing test assertion."""
+ if self.should_generate_issue():
+ self.assertTrue(
+ False,
+ "This will fail on the first call, succeed on rerun, and "
+ "alternate thereafter.")
diff --git a/packages/Python/lldbsuite/test/issue_verification/TestRerunInline.py.park b/packages/Python/lldbsuite/test/issue_verification/TestRerunInline.py.park
new file mode 100644
index 000000000000..4c50495a2ec4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/issue_verification/TestRerunInline.py.park
@@ -0,0 +1,13 @@
+"""Tests that the rerun mechanism respects lldbinline-created tests.
+
+The current implementation of this test is expected to fail both on
+the initial run and on the rerun, assuming --rerun-all-issues is provided
+to the dotest.py run.
+
+This test could be improved by doing something in the test inferior
+C++ program that could look for the "should an issue be raised" marker
+file, and then really pass on the rerun.
+"""
+import lldbsuite.test.lldbinline as lldbinline
+
+lldbinline.MakeInlineTest(__file__, globals())
diff --git a/packages/Python/lldbsuite/test/issue_verification/TestRerunTimeout.py.park b/packages/Python/lldbsuite/test/issue_verification/TestRerunTimeout.py.park
new file mode 100644
index 000000000000..1cf5373ac491
--- /dev/null
+++ b/packages/Python/lldbsuite/test/issue_verification/TestRerunTimeout.py.park
@@ -0,0 +1,22 @@
+"""Tests that a timeout is detected by the testbot."""
+from __future__ import print_function
+
+import time
+
+import lldbsuite.test.lldbtest as lldbtest
+import rerun_base
+
+
+class RerunTimeoutTestCase(rerun_base.RerunBaseTestCase):
+ @lldbtest.no_debug_info_test
+ def test_timeout_rerun_succeeds(self):
+ """Tests that timeout logic kicks in and is picked up."""
+ if not self.should_generate_issue():
+ # We pass this time.
+ return
+ # We time out this time.
+ while True:
+ try:
+ time.sleep(1)
+ except:
+ print("ignoring exception during sleep")
diff --git a/packages/Python/lldbsuite/test/issue_verification/TestSignal.py.park b/packages/Python/lldbsuite/test/issue_verification/TestSignal.py.park
new file mode 100644
index 000000000000..d73ac74b47b2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/issue_verification/TestSignal.py.park
@@ -0,0 +1,26 @@
+"""Tests that an exceptional exit is detected by the testbot."""
+
+from __future__ import print_function
+
+import os
+import signal
+import time
+
+import lldbsuite.test.lldbtest as lldbtest
+
+
+class ExceptionalExitTestCase(lldbtest.TestBase):
+ """Forces exceptional exit."""
+ mydir = lldbtest.TestBase.compute_mydir(__file__)
+
+ @lldbtest.skipIfWindows
+ def test_buildbot_catches_exceptional_exit(self):
+ """Force process to die with exceptional exit."""
+
+ # Sleep for a couple seconds
+ try:
+ time.sleep(5)
+ except:
+ pass
+
+ os.kill(os.getpid(), signal.SIGKILL)
diff --git a/packages/Python/lldbsuite/test/issue_verification/TestSignalOutsideTestMethod.py.park b/packages/Python/lldbsuite/test/issue_verification/TestSignalOutsideTestMethod.py.park
new file mode 100644
index 000000000000..7a5b2ba99f4b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/issue_verification/TestSignalOutsideTestMethod.py.park
@@ -0,0 +1,24 @@
+"""Tests that an exceptional exit is detected by the testbot."""
+
+from __future__ import print_function
+
+import atexit
+import os
+import signal
+import time
+
+import lldbsuite.test.lldbtest as lldbtest
+
+
+class ExceptionalExitOutOfTestMethodTestCase(lldbtest.TestBase):
+ """Forces exceptional exit."""
+ mydir = lldbtest.TestBase.compute_mydir(__file__)
+
+ @lldbtest.skipIfWindows
+ def test_buildbot_catches_exceptional_exit(self):
+ pass
+
+def cleanup():
+ os.kill(os.getpid(), signal.SIGKILL)
+
+atexit.register(cleanup)
diff --git a/packages/Python/lldbsuite/test/issue_verification/TestTimeout.py.park b/packages/Python/lldbsuite/test/issue_verification/TestTimeout.py.park
new file mode 100644
index 000000000000..ba7be454f9a9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/issue_verification/TestTimeout.py.park
@@ -0,0 +1,19 @@
+"""Tests that a timeout is detected by the testbot."""
+from __future__ import print_function
+
+import time
+
+import lldbsuite.test.lldbtest as lldbtest
+
+
+class TimeoutTestCase(lldbtest.TestBase):
+ """Forces test timeout."""
+ mydir = lldbtest.TestBase.compute_mydir(__file__)
+
+ def test_buildbot_catches_timeout(self):
+ """Tests that timeout logic kicks in and is picked up."""
+ while True:
+ try:
+ time.sleep(1)
+ except:
+ print("ignoring exception during sleep")
diff --git a/packages/Python/lldbsuite/test/issue_verification/disable.py b/packages/Python/lldbsuite/test/issue_verification/disable.py
new file mode 100755
index 000000000000..6d1f93e8b15d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/issue_verification/disable.py
@@ -0,0 +1,20 @@
+#!/usr/bin/env python
+"""Renames *.py files to *.py.park."""
+import os
+import sys
+
+
+def main():
+ """Drives the main script behavior."""
+ script_dir = os.path.dirname(os.path.realpath(__file__))
+ for filename in os.listdir(script_dir):
+ basename, extension = os.path.splitext(filename)
+ if basename.startswith("Test") and extension == '.py':
+ source_path = os.path.join(script_dir, filename)
+ dest_path = source_path + ".park"
+ sys.stdout.write("renaming {} to {}\n".format(
+ source_path, dest_path))
+ os.rename(source_path, dest_path)
+
+if __name__ == "__main__":
+ main()
diff --git a/packages/Python/lldbsuite/test/issue_verification/enable.py b/packages/Python/lldbsuite/test/issue_verification/enable.py
new file mode 100755
index 000000000000..eb19276de1f7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/issue_verification/enable.py
@@ -0,0 +1,20 @@
+#!/usr/bin/env python
+"""Renames *.py.park files to *.py."""
+import os
+import sys
+
+
+def main():
+ """Drives the main script behavior."""
+ script_dir = os.path.dirname(os.path.realpath(__file__))
+ for filename in os.listdir(script_dir):
+ basename, extension = os.path.splitext(filename)
+ if basename.startswith("Test") and extension == '.park':
+ source_path = os.path.join(script_dir, filename)
+ dest_path = os.path.join(script_dir, basename)
+ sys.stdout.write("renaming {} to {}\n".format(
+ source_path, dest_path))
+ os.rename(source_path, dest_path)
+
+if __name__ == "__main__":
+ main()
diff --git a/packages/Python/lldbsuite/test/issue_verification/inline_rerun_inferior.cpp b/packages/Python/lldbsuite/test/issue_verification/inline_rerun_inferior.cpp
new file mode 100644
index 000000000000..933911f7b28d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/issue_verification/inline_rerun_inferior.cpp
@@ -0,0 +1,14 @@
+//===-- main.cpp --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+typedef int Foo;
+
+int main() {
+ Foo array[3] = {1,2,3};
+ return 0; //% self.expect("frame variable array --show-types --", substrs = ['(Foo [3]) wrong_type_here = {','(Foo) [0] = 1','(Foo) [1] = 2','(Foo) [2] = 3'])
+}
diff --git a/packages/Python/lldbsuite/test/issue_verification/rerun_base.py b/packages/Python/lldbsuite/test/issue_verification/rerun_base.py
new file mode 100644
index 000000000000..2ce775dced13
--- /dev/null
+++ b/packages/Python/lldbsuite/test/issue_verification/rerun_base.py
@@ -0,0 +1,28 @@
+from __future__ import print_function
+
+import os
+
+import lldbsuite.test.lldbtest as lldbtest
+
+
+# pylint: disable=too-few-public-methods
+class RerunBaseTestCase(lldbtest.TestBase):
+ """Forces test failure."""
+ mydir = lldbtest.TestBase.compute_mydir(__file__)
+
+ def should_generate_issue(self):
+ """Returns whether a test issue should be generated.
+
+ @returns True on the first and every other call via a given
+ test method.
+ """
+ should_pass_filename = "{}.{}.succeed-marker".format(
+ __file__, self.id())
+ fail = not os.path.exists(should_pass_filename)
+ if fail:
+ # Create the marker so that next call to this passes.
+ open(should_pass_filename, 'w').close()
+ else:
+ # Delete the marker so next time we fail.
+ os.remove(should_pass_filename)
+ return fail
diff --git a/packages/Python/lldbsuite/test/lang/c/anonymous/Makefile b/packages/Python/lldbsuite/test/lang/c/anonymous/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/anonymous/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/anonymous/TestAnonymous.py b/packages/Python/lldbsuite/test/lang/c/anonymous/TestAnonymous.py
new file mode 100644
index 000000000000..7cb66ba8238b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/anonymous/TestAnonymous.py
@@ -0,0 +1,147 @@
+"""Test that anonymous structs/unions are transparent to member access"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class AnonymousTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfIcc # llvm.org/pr15036: LLDB generates an incorrect AST layout for an anonymous struct when DWARF is generated by ICC
+ def test_expr_nest(self):
+ self.build()
+ self.common_setup(self.line0)
+
+ # These should display correctly.
+ self.expect("expression n->foo.d", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["= 4"])
+
+ self.expect("expression n->b", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["= 2"])
+
+ def test_expr_child(self):
+ self.build()
+ self.common_setup(self.line1)
+
+ # These should display correctly.
+ self.expect("expression c->foo.d", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["= 4"])
+
+ self.expect("expression c->grandchild.b", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["= 2"])
+
+ @skipIfIcc # llvm.org/pr15036: This particular regression was introduced by r181498
+ def test_expr_grandchild(self):
+ self.build()
+ self.common_setup(self.line2)
+
+ # These should display correctly.
+ self.expect("expression g.child.foo.d", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["= 4"])
+
+ self.expect("expression g.child.b", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["= 2"])
+
+ def test_expr_parent(self):
+ self.build()
+ if "clang" in self.getCompiler() and "3.4" in self.getCompilerVersion():
+ self.skipTest("llvm.org/pr16214 -- clang emits partial DWARF for structures referenced via typedef")
+ self.common_setup(self.line2)
+
+ # These should display correctly.
+ self.expect("expression pz", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["(type_z *) $", " = 0x0000"])
+
+ self.expect("expression z.y", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["(type_y) $", "dummy = 2"])
+
+ @expectedFailureWindows('llvm.org/pr21550')
+ def test_expr_null(self):
+ self.build()
+ self.common_setup(self.line2)
+
+ # This should fail because pz is 0, but it succeeds on OS/X.
+ # This fails on Linux with an upstream error "Couldn't dematerialize struct", as does "p *n" with "int *n = 0".
+ # Note that this can also trigger llvm.org/pr15036 when run interactively at the lldb command prompt.
+ self.expect("expression *(type_z *)pz", error = True)
+
+ def test_child_by_name(self):
+ self.build()
+
+ # Set debugger into synchronous mode
+ self.dbg.SetAsync(False)
+
+ # Create a target
+ exe = os.path.join (os.getcwd(), "a.out")
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ break_in_main = target.BreakpointCreateBySourceRegex ('// Set breakpoint 2 here.', lldb.SBFileSpec(self.source))
+ self.assertTrue(break_in_main, VALID_BREAKPOINT)
+
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue (process, PROCESS_IS_VALID)
+
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, break_in_main)
+ if len(threads) != 1:
+ self.fail ("Failed to stop at breakpoint in main.")
+
+ thread = threads[0]
+ frame = thread.frames[0]
+
+ if not frame.IsValid():
+ self.fail ("Failed to get frame 0.")
+
+ var_n = frame.FindVariable("n")
+ if not var_n.IsValid():
+ self.fail ("Failed to get the variable 'n'")
+
+ elem_a = var_n.GetChildMemberWithName("a")
+ if not elem_a.IsValid():
+ self.fail ("Failed to get the element a in n")
+
+ error = lldb.SBError()
+ value = elem_a.GetValueAsSigned(error, 1000)
+ if not error.Success() or value != 0:
+ self.fail ("failed to get the correct value for element a in n")
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break in main.c.
+ self.source = 'main.c'
+ self.line0 = line_number(self.source, '// Set breakpoint 0 here.')
+ self.line1 = line_number(self.source, '// Set breakpoint 1 here.')
+ self.line2 = line_number(self.source, '// Set breakpoint 2 here.')
+
+ def common_setup(self, line):
+
+ # Set debugger into synchronous mode
+ self.dbg.SetAsync(False)
+
+ # Create a target
+ exe = os.path.join(os.getcwd(), "a.out")
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Set breakpoints inside and outside methods that take pointers to the containing struct.
+ lldbutil.run_break_set_by_file_and_line (self, self.source, line, num_expected_locations=1, loc_exact=True)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
diff --git a/packages/Python/lldbsuite/test/lang/c/anonymous/main.c b/packages/Python/lldbsuite/test/lang/c/anonymous/main.c
new file mode 100644
index 000000000000..58ac85b7d431
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/anonymous/main.c
@@ -0,0 +1,82 @@
+#include <stdio.h>
+
+struct anonymous_nest {
+ struct {
+ struct {
+ int a;
+ int b;
+ }; // anonymous
+ struct {
+ int c;
+ int d;
+ } foo;
+ }; // anonymous
+};
+
+struct anonymous_child {
+ struct {
+ struct {
+ int a;
+ int b;
+ } grandchild;
+ struct {
+ int c;
+ int d;
+ } foo;
+ }; // anonymous
+};
+
+struct anonymous_grandchild {
+ struct {
+ struct {
+ int a;
+ int b;
+ }; // anonymous
+ struct {
+ int c;
+ int d;
+ } foo;
+ } child;
+};
+
+int processor_nest (struct anonymous_nest *n)
+{
+ return n->foo.d + n->b; // Set breakpoint 0 here.
+}
+
+int processor_child (struct anonymous_child *c)
+{
+ return c->foo.d + c->grandchild.b; // Set breakpoint 1 here.
+}
+
+int processor_grandchild (struct anonymous_grandchild *g)
+{
+ return g->child.foo.d + g->child.b;
+}
+
+
+
+typedef struct {
+ int dummy;
+} type_y;
+
+typedef struct {
+ type_y y;
+} type_z;
+
+
+
+int main()
+{
+ struct anonymous_nest n = { 0, 2, 0, 4 };
+ struct anonymous_child c = { 0, 2, 0, 4 };
+ struct anonymous_grandchild g = { 0, 2, 0, 4 };
+ type_z *pz = 0;
+ type_z z = {{2}};
+
+ printf("%d\n", processor_nest(&n));
+ printf("%d\n", processor_child(&c));
+ printf("%d\n", processor_grandchild(&g)); // Set breakpoint 2 here.
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/array_types/Makefile b/packages/Python/lldbsuite/test/lang/c/array_types/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/array_types/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/array_types/TestArrayTypes.py b/packages/Python/lldbsuite/test/lang/c/array_types/TestArrayTypes.py
new file mode 100644
index 000000000000..e835fb096496
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/array_types/TestArrayTypes.py
@@ -0,0 +1,198 @@
+"""Test breakpoint by file/line number; and list variables with array types."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ArrayTypesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.c', '// Set break point at this line.')
+
+ def test_and_run_command(self):
+ """Test 'frame variable var_name' on some variables with array types."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=False)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The test suite sometimes shows that the process has exited without stopping.
+ #
+ # CC=clang ./dotest.py -v -t array_types
+ # ...
+ # Process 76604 exited with status = 0 (0x00000000)
+ self.runCmd("process status")
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = ['resolved, hit count = 1'])
+
+ # Issue 'variable list' command on several array-type variables.
+
+ self.expect("frame variable --show-types strings", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = '(char *[4])',
+ substrs = ['(char *) [0]',
+ '(char *) [1]',
+ '(char *) [2]',
+ '(char *) [3]',
+ 'Hello',
+ 'Hola',
+ 'Bonjour',
+ 'Guten Tag'])
+
+ self.expect("frame variable --show-types --raw -- char_16", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['(char) [0]',
+ '(char) [15]'])
+
+ self.expect("frame variable --show-types ushort_matrix", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = '(unsigned short [2][3])')
+
+ self.expect("frame variable --show-types long_6", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = '(long [6])')
+
+ @add_test_categories(['pyapi'])
+ def test_and_python_api(self):
+ """Use Python APIs to inspect variables with array types."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByLocation("main.c", self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Sanity check the print representation of breakpoint.
+ bp = str(breakpoint)
+ self.expect(bp, msg="Breakpoint looks good", exe=False,
+ substrs = ["file = 'main.c'",
+ "line = %d" % self.line,
+ "locations = 1"])
+ self.expect(bp, msg="Breakpoint is not resolved as yet", exe=False, matching=False,
+ substrs = ["resolved = 1"])
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Sanity check the print representation of process.
+ proc = str(process)
+ self.expect(proc, msg="Process looks good", exe=False,
+ substrs = ["state = stopped",
+ "executable = a.out"])
+
+ # The stop reason of the thread should be breakpoint.
+ thread = process.GetThreadAtIndex(0)
+ if thread.GetStopReason() != lldb.eStopReasonBreakpoint:
+ from lldbsuite.test.lldbutil import stop_reason_to_str
+ self.fail(STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS %
+ stop_reason_to_str(thread.GetStopReason()))
+
+ # Sanity check the print representation of thread.
+ thr = str(thread)
+ # TODO(zturner): Whether the TID is printed in hex or decimal should be controlled by a setting,
+ # and this test should read the value of the setting. This check is currently hardcoded to
+ # match the check in Core/FormatEntity.cpp in the function FormatEntity::Format() for
+ # the Entry::Type::ThreadID case of the switch statement.
+ if self.getPlatform() == "linux" or self.getPlatform() == "freebsd":
+ tidstr = "tid = %u" % thread.GetThreadID()
+ else:
+ tidstr = "tid = 0x%4.4x" % thread.GetThreadID()
+ self.expect(thr, "Thread looks good with stop reason = breakpoint", exe=False,
+ substrs = [tidstr])
+
+ # The breakpoint should have a hit count of 1.
+ self.assertTrue(breakpoint.GetHitCount() == 1, BREAKPOINT_HIT_ONCE)
+
+ # The breakpoint should be resolved by now.
+ bp = str(breakpoint)
+ self.expect(bp, "Breakpoint looks good and is resolved", exe=False,
+ substrs = ["file = 'main.c'",
+ "line = %d" % self.line,
+ "locations = 1"])
+
+ # Sanity check the print representation of frame.
+ frame = thread.GetFrameAtIndex(0)
+ frm = str(frame)
+ self.expect(frm,
+ "Frame looks good with correct index %d" % frame.GetFrameID(),
+ exe=False,
+ substrs = ["#%d" % frame.GetFrameID()])
+
+ # Lookup the "strings" string array variable and sanity check its print
+ # representation.
+ variable = frame.FindVariable("strings")
+ var = str(variable)
+ self.expect(var, "Variable for 'strings' looks good with correct name", exe=False,
+ substrs = ["%s" % variable.GetName()])
+ self.DebugSBValue(variable)
+ self.assertTrue(variable.GetNumChildren() == 4,
+ "Variable 'strings' should have 4 children")
+
+ child3 = variable.GetChildAtIndex(3)
+ self.DebugSBValue(child3)
+ self.assertTrue(child3.GetSummary() == '"Guten Tag"',
+ 'strings[3] == "Guten Tag"')
+
+ # Lookup the "char_16" char array variable.
+ variable = frame.FindVariable("char_16")
+ self.DebugSBValue(variable)
+ self.assertTrue(variable.GetNumChildren() == 16,
+ "Variable 'char_16' should have 16 children")
+
+ # Lookup the "ushort_matrix" ushort[] array variable.
+ # Notice the pattern of int(child0_2.GetValue(), 0). We pass a
+ # base of 0 so that the proper radix is determined based on the contents
+ # of the string. Same applies to long().
+ variable = frame.FindVariable("ushort_matrix")
+ self.DebugSBValue(variable)
+ self.assertTrue(variable.GetNumChildren() == 2,
+ "Variable 'ushort_matrix' should have 2 children")
+ child0 = variable.GetChildAtIndex(0)
+ self.DebugSBValue(child0)
+ self.assertTrue(child0.GetNumChildren() == 3,
+ "Variable 'ushort_matrix[0]' should have 3 children")
+ child0_2 = child0.GetChildAtIndex(2)
+ self.DebugSBValue(child0_2)
+ self.assertTrue(int(child0_2.GetValue(), 0) == 3,
+ "ushort_matrix[0][2] == 3")
+
+ # Lookup the "long_6" char array variable.
+ variable = frame.FindVariable("long_6")
+ self.DebugSBValue(variable)
+ self.assertTrue(variable.GetNumChildren() == 6,
+ "Variable 'long_6' should have 6 children")
+ child5 = variable.GetChildAtIndex(5)
+ self.DebugSBValue(child5)
+ self.assertTrue(int(child5.GetValue(), 0) == 6,
+ "long_6[5] == 6")
+
+ # Last, check that "long_6" has a value type of eValueTypeVariableLocal
+ # and "argc" has eValueTypeVariableArgument.
+ from lldbsuite.test.lldbutil import value_type_to_str
+ self.assertTrue(variable.GetValueType() == lldb.eValueTypeVariableLocal,
+ "Variable 'long_6' should have '%s' value type." %
+ value_type_to_str(lldb.eValueTypeVariableLocal))
+ argc = frame.FindVariable("argc")
+ self.DebugSBValue(argc)
+ self.assertTrue(argc.GetValueType() == lldb.eValueTypeVariableArgument,
+ "Variable 'argc' should have '%s' value type." %
+ value_type_to_str(lldb.eValueTypeVariableArgument))
diff --git a/packages/Python/lldbsuite/test/lang/c/array_types/cmds.txt b/packages/Python/lldbsuite/test/lang/c/array_types/cmds.txt
new file mode 100644
index 000000000000..8feebe212044
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/array_types/cmds.txt
@@ -0,0 +1,3 @@
+break main.c:42
+continue
+var
diff --git a/packages/Python/lldbsuite/test/lang/c/array_types/main.c b/packages/Python/lldbsuite/test/lang/c/array_types/main.c
new file mode 100644
index 000000000000..5f0680a43b84
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/array_types/main.c
@@ -0,0 +1,51 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+int main (int argc, char const *argv[])
+{
+ struct point_tag {
+ int x;
+ int y;
+ };
+
+ struct rect_tag {
+ struct point_tag bottom_left;
+ struct point_tag top_right;
+ };
+ char char_16[16] = "Hello World\n";
+ char *strings[] = { "Hello", "Hola", "Bonjour", "Guten Tag" };
+ char char_matrix[3][3] = {{'a', 'b', 'c' }, {'d', 'e', 'f' }, {'g', 'h', 'i' }};
+ char char_matrix_matrix[3][2][3] =
+ { {{'a', 'b', 'c' }, {'d', 'e', 'f' }},
+ {{'A', 'B', 'C' }, {'D', 'E', 'F' }},
+ {{'1', '2', '3' }, {'4', '5', '6' }}};
+ short short_4[4] = { 1,2,3,4 };
+ short short_matrix[1][2] = { {1,2} };
+ unsigned short ushort_4[4] = { 1,2,3,4 };
+ unsigned short ushort_matrix[2][3] = {
+ { 1, 2, 3},
+ {11,22,33}
+ };
+ int int_2[2] = { 1, 2 };
+ unsigned int uint_2[2] = { 1, 2 };
+ long long_6[6] = { 1, 2, 3, 4, 5, 6 };
+ unsigned long ulong_6[6] = { 1, 2, 3, 4, 5, 6 };
+ struct point_tag points_2[2] = {
+ {1,2},
+ {3,4}
+ };
+ struct point_tag points_2_4_matrix[2][4] = { // Set break point at this line.
+ {{ 1, 2}, { 3, 4}, { 5, 6}, { 7, 8}},
+ {{11,22}, {33,44}, {55,66}, {77,88}}
+ };
+ struct rect_tag rects_2[2] = {
+ {{1,2}, {3,4}},
+ {{5,6}, {7,8}}
+ };
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/bitfields/Makefile b/packages/Python/lldbsuite/test/lang/c/bitfields/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/bitfields/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/bitfields/TestBitfields.py b/packages/Python/lldbsuite/test/lang/c/bitfields/TestBitfields.py
new file mode 100644
index 000000000000..de7a333a18fa
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/bitfields/TestBitfields.py
@@ -0,0 +1,162 @@
+"""Show bitfields and check that they display correctly."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class BitfieldsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.c', '// Set break point at this line.')
+
+ @skipIfWindows # BitFields exhibit crashes in record layout on Windows (http://llvm.org/pr21800)
+ def test_and_run_command(self):
+ """Test 'frame variable ...' on a variable with bitfields."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break inside the main.
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ # This should display correctly.
+ self.expect("frame variable --show-types bits", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['(uint32_t:1) b1 = 1',
+ '(uint32_t:2) b2 = 3',
+ '(uint32_t:3) b3 = 7',
+ '(uint32_t) b4 = 15',
+ '(uint32_t:5) b5 = 31',
+ '(uint32_t:6) b6 = 63',
+ '(uint32_t:7) b7 = 127',
+ '(uint32_t:4) four = 15'])
+
+ # And so should this.
+ # rdar://problem/8348251
+ self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['(uint32_t:1) b1 = 1',
+ '(uint32_t:2) b2 = 3',
+ '(uint32_t:3) b3 = 7',
+ '(uint32_t) b4 = 15',
+ '(uint32_t:5) b5 = 31',
+ '(uint32_t:6) b6 = 63',
+ '(uint32_t:7) b7 = 127',
+ '(uint32_t:4) four = 15'])
+
+ self.expect("expr (bits.b1)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['uint32_t', '1'])
+ self.expect("expr (bits.b2)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['uint32_t', '3'])
+ self.expect("expr (bits.b3)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['uint32_t', '7'])
+ self.expect("expr (bits.b4)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['uint32_t', '15'])
+ self.expect("expr (bits.b5)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['uint32_t', '31'])
+ self.expect("expr (bits.b6)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['uint32_t', '63'])
+ self.expect("expr (bits.b7)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['uint32_t', '127'])
+ self.expect("expr (bits.four)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['uint32_t', '15'])
+
+ self.expect("frame variable --show-types more_bits", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['(uint32_t:3) a = 3',
+ '(uint8_t:1) b = \'\\0\'',
+ '(uint8_t:1) c = \'\\x01\'',
+ '(uint8_t:1) d = \'\\0\''])
+
+ self.expect("expr (more_bits.a)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['uint32_t', '3'])
+ self.expect("expr (more_bits.b)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['uint8_t', '\\0'])
+ self.expect("expr (more_bits.c)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['uint8_t', '\\x01'])
+ self.expect("expr (more_bits.d)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['uint8_t', '\\0'])
+
+ @add_test_categories(['pyapi'])
+ @skipIfWindows # BitFields exhibit crashes in record layout on Windows (http://llvm.org/pr21800)
+ def test_and_python_api(self):
+ """Use Python APIs to inspect a bitfields variable."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByLocation("main.c", self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ thread = target.GetProcess().GetThreadAtIndex(0)
+ if thread.GetStopReason() != lldb.eStopReasonBreakpoint:
+ from lldbsuite.test.lldbutil import stop_reason_to_str
+ self.fail(STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS %
+ stop_reason_to_str(thread.GetStopReason()))
+
+ # The breakpoint should have a hit count of 1.
+ self.assertTrue(breakpoint.GetHitCount() == 1, BREAKPOINT_HIT_ONCE)
+
+ # Lookup the "bits" variable which contains 8 bitfields.
+ frame = thread.GetFrameAtIndex(0)
+ bits = frame.FindVariable("bits")
+ self.DebugSBValue(bits)
+ self.assertTrue(bits.GetTypeName() == 'Bits', "bits.GetTypeName() == 'Bits'");
+ self.assertTrue(bits.GetNumChildren() == 10, "bits.GetNumChildren() == 10");
+ test_compiler = self.getCompiler()
+ self.assertTrue(bits.GetByteSize() == 32, "bits.GetByteSize() == 32");
+
+ # Notice the pattern of int(b1.GetValue(), 0). We pass a base of 0
+ # so that the proper radix is determined based on the contents of the
+ # string.
+ b1 = bits.GetChildMemberWithName("b1")
+ self.DebugSBValue(b1)
+ self.assertTrue(b1.GetName() == "b1" and
+ b1.GetTypeName() == "uint32_t:1" and
+ b1.IsInScope() and
+ int(b1.GetValue(), 0) == 1,
+ 'bits.b1 has type uint32_t:1, is in scope, and == 1')
+
+ b7 = bits.GetChildMemberWithName("b7")
+ self.DebugSBValue(b7)
+ self.assertTrue(b7.GetName() == "b7" and
+ b7.GetTypeName() == "uint32_t:7" and
+ b7.IsInScope() and
+ int(b7.GetValue(), 0) == 127,
+ 'bits.b7 has type uint32_t:7, is in scope, and == 127')
+
+ four = bits.GetChildMemberWithName("four")
+ self.DebugSBValue(four)
+ self.assertTrue(four.GetName() == "four" and
+ four.GetTypeName() == "uint32_t:4" and
+ four.IsInScope() and
+ int(four.GetValue(), 0) == 15,
+ 'bits.four has type uint32_t:4, is in scope, and == 15')
+
+ # Now kill the process, and we are done.
+ rc = target.GetProcess().Kill()
+ self.assertTrue(rc.Success())
diff --git a/packages/Python/lldbsuite/test/lang/c/bitfields/main.c b/packages/Python/lldbsuite/test/lang/c/bitfields/main.c
new file mode 100644
index 000000000000..26c0176d759c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/bitfields/main.c
@@ -0,0 +1,67 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdint.h>
+#include <stdio.h>
+int main (int argc, char const *argv[])
+{
+ struct Bits
+ {
+ uint32_t : 1, // Unnamed bitfield
+ b1 : 1,
+ b2 : 2,
+ : 2, // Unnamed bitfield
+ b3 : 3,
+ : 2, // Unnamed bitfield (this will get removed)
+ b4 __attribute__ ((aligned(16))),
+ b5 : 5,
+ b6 : 6,
+ b7 : 7,
+ four : 4;
+ };
+
+ printf("%lu", sizeof(struct Bits));
+
+ struct Bits bits;
+ int i;
+ for (i=0; i<(1<<1); i++)
+ bits.b1 = i; //// break $source:$line
+ for (i=0; i<(1<<2); i++)
+ bits.b2 = i; //// break $source:$line
+ for (i=0; i<(1<<3); i++)
+ bits.b3 = i; //// break $source:$line
+ for (i=0; i<(1<<4); i++)
+ bits.b4 = i; //// break $source:$line
+ for (i=0; i<(1<<5); i++)
+ bits.b5 = i; //// break $source:$line
+ for (i=0; i<(1<<6); i++)
+ bits.b6 = i; //// break $source:$line
+ for (i=0; i<(1<<7); i++)
+ bits.b7 = i; //// break $source:$line
+ for (i=0; i<(1<<4); i++)
+ bits.four = i; //// break $source:$line
+
+ struct MoreBits
+ {
+ uint32_t a : 3;
+ uint8_t : 1;
+ uint8_t b : 1;
+ uint8_t c : 1;
+ uint8_t d : 1;
+ };
+
+ struct MoreBits more_bits;
+
+ more_bits.a = 3;
+ more_bits.b = 0;
+ more_bits.c = 1;
+ more_bits.d = 0;
+
+ return 0; //// Set break point at this line.
+
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/blocks/Makefile b/packages/Python/lldbsuite/test/lang/c/blocks/Makefile
new file mode 100644
index 000000000000..752b7aed3970
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/blocks/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+CFLAGS_EXTRAS += -fblocks
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/blocks/TestBlocks.py b/packages/Python/lldbsuite/test/lang/c/blocks/TestBlocks.py
new file mode 100644
index 000000000000..8f1c3be22836
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/blocks/TestBlocks.py
@@ -0,0 +1,61 @@
+"""Test that lldb can invoke blocks and access variables inside them"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class BlocksTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+ lines = []
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break at.
+ self.lines.append(line_number('main.c', '// Set breakpoint 0 here.'))
+ self.lines.append(line_number('main.c', '// Set breakpoint 1 here.'))
+
+ @unittest2.expectedFailure("rdar://problem/10413887 - Call blocks in expressions")
+ def test_expr(self):
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ self.is_started = False
+
+ # Break inside the foo function which takes a bar_ptr argument.
+ for line in self.lines:
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", line, num_expected_locations=1, loc_exact=True)
+
+ self.wait_for_breakpoint()
+
+ self.expect("expression a + b", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["= 7"])
+
+ self.expect("expression c", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["= 1"])
+
+ self.wait_for_breakpoint()
+
+ # This should display correctly.
+ self.expect("expression (int)neg (-12)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["= 12"])
+
+ def wait_for_breakpoint(self):
+ if self.is_started == False:
+ self.is_started = True
+ self.runCmd("process launch", RUN_SUCCEEDED)
+ else:
+ self.runCmd("process continue", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
diff --git a/packages/Python/lldbsuite/test/lang/c/blocks/main.c b/packages/Python/lldbsuite/test/lang/c/blocks/main.c
new file mode 100644
index 000000000000..415e6c6d033d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/blocks/main.c
@@ -0,0 +1,21 @@
+#include <stdio.h>
+
+int main()
+{
+ int c = 1;
+
+ int (^add)(int, int) = ^int(int a, int b)
+ {
+ return a + b + c; // Set breakpoint 0 here.
+ };
+
+ int (^neg)(int) = ^int(int a)
+ {
+ return -a;
+ };
+
+ printf("%d\n", add(3, 4));
+ printf("%d\n", neg(-5)); // Set breakpoint 1 here.
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/const_variables/Makefile b/packages/Python/lldbsuite/test/lang/c/const_variables/Makefile
new file mode 100644
index 000000000000..51adad1d0622
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/const_variables/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c functions.c
+
+CFLAGS_EXTRAS += -O3
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/const_variables/TestConstVariables.py b/packages/Python/lldbsuite/test/lang/c/const_variables/TestConstVariables.py
new file mode 100644
index 000000000000..a112b2a1777c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/const_variables/TestConstVariables.py
@@ -0,0 +1,64 @@
+"""Check that compiler-generated constant values work correctly"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ConstVariableTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureAll(
+ oslist=["freebsd", "linux"],
+ compiler="clang", compiler_version=["<", "3.5"])
+ @expectedFailureAll(
+ oslist=["freebsd", "linux"],
+ compiler="clang", compiler_version=["=", "3.7"])
+ @expectedFailureAll(
+ oslist=["freebsd", "linux"],
+ compiler="clang", compiler_version=["=", "3.8"])
+ @expectedFailureAll(oslist=["freebsd", "linux"], compiler="icc")
+ @expectedFailureAll(archs=['mips', 'mipsel', 'mips64', 'mips64el'])
+ @expectedFailureWindows("llvm.org/pr24489: Name lookup not working correctly on Windows")
+ @expectedFailureWindows("llvm.org/pr24490: We shouldn't be using platform-specific names like `getpid` in tests")
+ def test_and_run_command(self):
+ """Test interpreted and JITted expressions on constant values."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break inside the main.
+ lldbutil.run_break_set_by_symbol (self, "main", num_expected_locations=1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ self.runCmd("next")
+ self.runCmd("next")
+
+ # Try frame variable.
+ self.expect("frame variable index", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['(int32_t) index = 512'])
+
+ # Try an interpreted expression.
+ self.expect("expr (index + 512)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['1024'])
+
+ # Try a JITted expression.
+ self.expect("expr (int)getpid(); (index - 256)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['256'])
+
+ self.runCmd("kill")
diff --git a/packages/Python/lldbsuite/test/lang/c/const_variables/functions.c b/packages/Python/lldbsuite/test/lang/c/const_variables/functions.c
new file mode 100644
index 000000000000..c9ea63837c8b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/const_variables/functions.c
@@ -0,0 +1,18 @@
+#include <stdio.h>
+
+void foo()
+{
+ printf("foo()\n");
+}
+
+int bar()
+{
+ int ret = 3;
+ printf("bar()->%d\n", ret);
+ return ret;
+}
+
+void baaz(int i)
+{
+ printf("baaz(%d)\n", i);
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/const_variables/main.c b/packages/Python/lldbsuite/test/lang/c/const_variables/main.c
new file mode 100644
index 000000000000..50a924e01d94
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/const_variables/main.c
@@ -0,0 +1,23 @@
+#include <stdint.h>
+#include <stdio.h>
+
+extern int foo();
+extern int bar();
+extern int baaz(int i);
+
+int main()
+{
+ int32_t index;
+
+ foo();
+
+ index = 512;
+
+ if (bar())
+ {
+ printf("COMPILER PLEASE STOP HERE\n");
+ index = 256;
+ }
+
+ baaz(index);
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/enum_types/Makefile b/packages/Python/lldbsuite/test/lang/c/enum_types/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/enum_types/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/enum_types/TestEnumTypes.py b/packages/Python/lldbsuite/test/lang/c/enum_types/TestEnumTypes.py
new file mode 100644
index 000000000000..b0c5c882f6a9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/enum_types/TestEnumTypes.py
@@ -0,0 +1,71 @@
+"""Look up enum type information and check for correct display."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class EnumTypesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.c', '// Set break point at this line.')
+
+ def test(self):
+ """Test 'image lookup -t days' and check for correct display and enum value printing."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break inside the main.
+ bkpt_id = lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ # Look up information about the 'days' enum type.
+ # Check for correct display.
+ self.expect("image lookup -t days", DATA_TYPES_DISPLAYED_CORRECTLY,
+ substrs = ['enum days {',
+ 'Monday',
+ 'Tuesday',
+ 'Wednesday',
+ 'Thursday',
+ 'Friday',
+ 'Saturday',
+ 'Sunday',
+ 'kNumDays',
+ '}'])
+
+ enum_values = [ '-4',
+ 'Monday',
+ 'Tuesday',
+ 'Wednesday',
+ 'Thursday',
+ 'Friday',
+ 'Saturday',
+ 'Sunday',
+ 'kNumDays',
+ '5'];
+
+ bkpt = self.target().FindBreakpointByID(bkpt_id)
+ for enum_value in enum_values:
+ self.expect("frame variable day", 'check for valid enumeration value',
+ substrs = [enum_value])
+ lldbutil.continue_to_breakpoint (self.process(), bkpt)
diff --git a/packages/Python/lldbsuite/test/lang/c/enum_types/main.c b/packages/Python/lldbsuite/test/lang/c/enum_types/main.c
new file mode 100644
index 000000000000..3d59654eff69
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/enum_types/main.c
@@ -0,0 +1,29 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+int main (int argc, char const *argv[])
+{
+ enum days {
+ Monday = -3,
+ Tuesday,
+ Wednesday,
+ Thursday,
+ Friday,
+ Saturday,
+ Sunday,
+ kNumDays
+ };
+ enum days day;
+ for (day = Monday - 1; day <= kNumDays + 1; day++)
+ {
+ printf("day as int is %i\n", (int)day); // Set break point at this line.
+ }
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/forward/Makefile b/packages/Python/lldbsuite/test/lang/c/forward/Makefile
new file mode 100644
index 000000000000..1db43ab479b2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/forward/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c foo.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/forward/README.txt b/packages/Python/lldbsuite/test/lang/c/forward/README.txt
new file mode 100644
index 000000000000..b7b66f75162b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/forward/README.txt
@@ -0,0 +1,5 @@
+This example has a function call in foo.c named "foo" that takes a forward
+declaration to "struct bar" and uses it as a pointer argument. In main.c
+we have a real declaration for "struct bar". We want to be able to find the
+real definition of "struct bar" when we are stopped in foo in foo.c such that
+when we stop in "foo" we see the contents of the "bar_ptr".
diff --git a/packages/Python/lldbsuite/test/lang/c/forward/TestForwardDeclaration.py b/packages/Python/lldbsuite/test/lang/c/forward/TestForwardDeclaration.py
new file mode 100644
index 000000000000..33c0de2d72d3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/forward/TestForwardDeclaration.py
@@ -0,0 +1,47 @@
+"""Test that forward declaration of a data structure gets resolved correctly."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ForwardDeclarationTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test_and_run_command(self):
+ """Display *bar_ptr when stopped on a function with forward declaration of struct bar."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break inside the foo function which takes a bar_ptr argument.
+ lldbutil.run_break_set_by_symbol (self, "foo", num_expected_locations=1, sym_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ # This should display correctly.
+ # Note that the member fields of a = 1 and b = 2 is by design.
+ self.expect("frame variable --show-types *bar_ptr", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['(bar) *bar_ptr = ',
+ '(int) a = 1',
+ '(int) b = 2'])
+
+ # And so should this.
+ self.expect("expression --show-types -- *bar_ptr", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['(bar)',
+ '(int) a = 1',
+ '(int) b = 2'])
diff --git a/packages/Python/lldbsuite/test/lang/c/forward/foo.c b/packages/Python/lldbsuite/test/lang/c/forward/foo.c
new file mode 100644
index 000000000000..2e050e77778d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/forward/foo.c
@@ -0,0 +1,8 @@
+#include <stdio.h>
+#include "foo.h"
+
+int
+foo (struct bar *bar_ptr)
+{
+ return printf ("bar_ptr = %p\n", bar_ptr);
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/forward/foo.h b/packages/Python/lldbsuite/test/lang/c/forward/foo.h
new file mode 100644
index 000000000000..3040927cb47a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/forward/foo.h
@@ -0,0 +1,4 @@
+
+struct bar;
+
+int foo (struct bar *bar_ptr);
diff --git a/packages/Python/lldbsuite/test/lang/c/forward/main.c b/packages/Python/lldbsuite/test/lang/c/forward/main.c
new file mode 100644
index 000000000000..6f9787c30a36
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/forward/main.c
@@ -0,0 +1,18 @@
+#include <stdio.h>
+#include "foo.h"
+
+struct bar
+{
+ int a;
+ int b;
+};
+
+int
+main (int argc, char const *argv[])
+{
+ struct bar b= { 1, 2 };
+
+ foo (&b);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/function_types/Makefile b/packages/Python/lldbsuite/test/lang/c/function_types/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/function_types/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/function_types/TestFunctionTypes.py b/packages/Python/lldbsuite/test/lang/c/function_types/TestFunctionTypes.py
new file mode 100644
index 000000000000..2f9f1d10b58c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/function_types/TestFunctionTypes.py
@@ -0,0 +1,76 @@
+"""Test variable with function ptr type and that break on the function works."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class FunctionTypesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.c', '// Set break point at this line.')
+
+ def test(self):
+ """Test 'callback' has function ptr type, then break on the function."""
+ self.build()
+ self.runToBreakpoint()
+
+ # Check that the 'callback' variable display properly.
+ self.expect("frame variable --show-types callback", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = '(int (*)(const char *)) callback =')
+
+ # And that we can break on the callback function.
+ lldbutil.run_break_set_by_symbol (self, "string_not_empty", num_expected_locations=1, sym_exact=True)
+ self.runCmd("continue")
+
+ # Check that we do indeed stop on the string_not_empty function.
+ self.expect("process status", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['a.out`string_not_empty',
+ 'stop reason = breakpoint'])
+
+ @expectedFailureWindows("llvm.org/pr21765")
+ def test_pointers(self):
+ """Test that a function pointer to 'printf' works and can be called."""
+ self.build()
+ self.runToBreakpoint()
+
+ self.expect("expr string_not_empty",
+ substrs = ['(int (*)(const char *)) $0 = ', '(a.out`'])
+
+ if self.platformIsDarwin():
+ regexps = ['lib.*\.dylib`printf']
+ else:
+ regexps = ['printf']
+ self.expect("expr (int (*)(const char*, ...))printf",
+ substrs = ['(int (*)(const char *, ...)) $1 = '],
+ patterns = regexps)
+
+ self.expect("expr $1(\"Hello world\\n\")",
+ startstr = '(int) $2 = 12')
+
+ def runToBreakpoint(self):
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break inside the main.
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
diff --git a/packages/Python/lldbsuite/test/lang/c/function_types/main.c b/packages/Python/lldbsuite/test/lang/c/function_types/main.c
new file mode 100644
index 000000000000..8be3c4d46b3c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/function_types/main.c
@@ -0,0 +1,22 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+int string_not_empty (const char *s)
+{
+ if (s && s[0])
+ return 1;
+ return 0;
+}
+
+int main (int argc, char const *argv[])
+{
+ int (*callback)(const char *) = string_not_empty;
+
+ return callback(0); // Set break point at this line.
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/global_variables/Makefile b/packages/Python/lldbsuite/test/lang/c/global_variables/Makefile
new file mode 100644
index 000000000000..b1b77dacc01e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/global_variables/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+DYLIB_NAME := a
+DYLIB_C_SOURCES := a.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/global_variables/TestGlobalVariables.py b/packages/Python/lldbsuite/test/lang/c/global_variables/TestGlobalVariables.py
new file mode 100644
index 000000000000..1f91cd1660c3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/global_variables/TestGlobalVariables.py
@@ -0,0 +1,76 @@
+"""Show global variables and check that they do indeed have global scopes."""
+
+from __future__ import print_function
+
+
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class GlobalVariablesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.source = 'main.c'
+ self.line = line_number(self.source, '// Set break point at this line.')
+ self.shlib_names = ["a"]
+
+ @expectedFailureWindows("llvm.org/pr24764")
+ @expectedFailureAll("llvm.org/pr25872", oslist=["macosx"], debug_info="dwarf")
+ def test_c_global_variables(self):
+ """Test 'frame variable --scope --no-args' which omits args and shows scopes."""
+ self.build()
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget("a.out")
+ self.assertTrue(target, VALID_TARGET)
+
+ # Break inside the main.
+ lldbutil.run_break_set_by_file_and_line (self, self.source, self.line, num_expected_locations=1, loc_exact=True)
+
+ # Register our shared libraries for remote targets so they get automatically uploaded
+ environment = self.registerSharedLibrariesWithTarget(target, self.shlib_names)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, environment, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ # Check that GLOBAL scopes are indicated for the variables.
+ self.expect("frame variable --show-types --scope --show-globals --no-args", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['GLOBAL: (int) g_file_global_int = 42',
+ 'STATIC: (const int) g_file_static_int = 2',
+ 'GLOBAL: (const char *) g_file_global_cstr',
+ '"g_file_global_cstr"',
+ 'STATIC: (const char *) g_file_static_cstr',
+ '"g_file_static_cstr"',
+ 'GLOBAL: (int) g_common_1 = 21'])
+
+ # 'frame variable' should support address-of operator.
+ self.runCmd("frame variable &g_file_global_int")
+
+ # Exercise the 'target variable' command to display globals in a.c file.
+ self.expect("target variable g_a", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['g_a', '123'])
+ self.expect("target variable g_marked_spot.x", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['g_marked_spot.x', '20'])
+
+ # rdar://problem/9747668
+ # runCmd: target variable g_marked_spot.y
+ # output: (int) g_marked_spot.y = <a.o[0x214] can't be resolved, in not currently loaded.
+ # >
+ self.expect("target variable g_marked_spot.y", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['g_marked_spot.y', '21'])
+ self.expect("target variable g_marked_spot.y", VARIABLES_DISPLAYED_CORRECTLY, matching=False,
+ substrs = ["can't be resolved"])
diff --git a/packages/Python/lldbsuite/test/lang/c/global_variables/a.c b/packages/Python/lldbsuite/test/lang/c/global_variables/a.c
new file mode 100644
index 000000000000..d169d5d63240
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/global_variables/a.c
@@ -0,0 +1,15 @@
+//===-- a.c -----------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+int g_a = 123;
+struct Point {
+ int x;
+ int y;
+};
+struct Point g_marked_spot = { 20, 21 };
+
diff --git a/packages/Python/lldbsuite/test/lang/c/global_variables/cmds.txt b/packages/Python/lldbsuite/test/lang/c/global_variables/cmds.txt
new file mode 100644
index 000000000000..6906a0729aeb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/global_variables/cmds.txt
@@ -0,0 +1,3 @@
+break main.c:5
+continue
+var -global g_a -global g_global_int
diff --git a/packages/Python/lldbsuite/test/lang/c/global_variables/main.c b/packages/Python/lldbsuite/test/lang/c/global_variables/main.c
new file mode 100644
index 000000000000..499b2504774f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/global_variables/main.c
@@ -0,0 +1,24 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+int g_common_1; // Not initialized on purpose to cause it to be undefined external in .o file
+int g_file_global_int = 42;
+static const int g_file_static_int = 2;
+const char *g_file_global_cstr = "g_file_global_cstr";
+static const char *g_file_static_cstr = "g_file_static_cstr";
+
+extern int g_a;
+int main (int argc, char const *argv[])
+{
+ g_common_1 = g_file_global_int / g_file_static_int;
+ static const char *g_func_static_cstr = "g_func_static_cstr";
+ printf ("%s %s\n", g_file_global_cstr, g_file_static_cstr);
+ return g_file_global_int + g_a + g_common_1; // Set break point at this line. //// break $source:$line; continue; var -global g_a -global g_global_int
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/inlines/Makefile b/packages/Python/lldbsuite/test/lang/c/inlines/Makefile
new file mode 100644
index 000000000000..c5b0d18f995d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/inlines/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := inlines.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/inlines/inlines.c b/packages/Python/lldbsuite/test/lang/c/inlines/inlines.c
new file mode 100644
index 000000000000..1e920f1ef2f6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/inlines/inlines.c
@@ -0,0 +1,53 @@
+#include <stdio.h>
+#include "inlines.h"
+
+#define INLINE_ME __inline__ __attribute__((always_inline))
+
+int
+not_inlined_2 (int input)
+{
+ printf ("Called in not_inlined_2 with : %d.\n", input);
+ return input;
+}
+
+int
+not_inlined_1 (int input)
+{
+ printf ("Called in not_inlined_1 with %d.\n", input);
+ return not_inlined_2(input);
+}
+
+INLINE_ME int
+inner_inline (int inner_input, int mod_value)
+{
+ int inner_result;
+ inner_result = inner_input % mod_value;
+ printf ("Returning: %d.\n", inner_result);
+ return not_inlined_1 (inner_result);
+}
+
+INLINE_ME int
+outer_inline (int outer_input)
+{
+ int outer_result;
+
+ outer_result = inner_inline (outer_input, outer_input % 3);
+ return outer_result;
+}
+
+int
+main (int argc, char **argv)
+{
+ printf ("Starting...\n");
+
+ int (*func_ptr) (int);
+ func_ptr = outer_inline;
+
+ outer_inline (argc);
+
+ func_ptr (argc);
+
+ return 0;
+}
+
+
diff --git a/packages/Python/lldbsuite/test/lang/c/inlines/inlines.h b/packages/Python/lldbsuite/test/lang/c/inlines/inlines.h
new file mode 100644
index 000000000000..265d7b4966ed
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/inlines/inlines.h
@@ -0,0 +1,4 @@
+int inner_inline (int inner_input, int mod_value);
+int outer_inline (int outer_input);
+int not_inlined_2 (int input);
+int not_inlined_1 (int input);
diff --git a/packages/Python/lldbsuite/test/lang/c/modules/Makefile b/packages/Python/lldbsuite/test/lang/c/modules/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/modules/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/modules/TestCModules.py b/packages/Python/lldbsuite/test/lang/c/modules/TestCModules.py
new file mode 100644
index 000000000000..cd31f9dbacfe
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/modules/TestCModules.py
@@ -0,0 +1,65 @@
+"""Test that importing modules in C works as expected."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import platform
+import lldbsuite.test.lldbutil as lldbutil
+
+from distutils.version import StrictVersion
+
+from lldbsuite.test.lldbtest import *
+
+class CModulesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfFreeBSD
+ @expectedFailureDarwin('http://llvm.org/pr24302')
+ @expectedFailureLinux('http://llvm.org/pr23456') # 'fopen' has unknown return type
+ @expectedFailureWindows("llvm.org/pr24489: Name lookup not working correctly on Windows")
+ def test_expr(self):
+ if platform.system() == "Darwin" and platform.release() < StrictVersion('12.0.0'):
+ self.skipTest()
+
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break inside the foo function which takes a bar_ptr argument.
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ self.expect("expr @import Darwin; 3", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["int", "3"])
+
+ self.expect("expr *fopen(\"/dev/zero\", \"w\")", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["FILE", "_close", "__sclose"])
+
+ self.expect("expr *myFile", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["a", "5", "b", "9"])
+
+ self.expect("expr MIN((uint64_t)2, (uint64_t)3)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["uint64_t", "2"])
+
+ self.expect("expr stdin", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["(FILE *)", "0x"])
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.c', '// Set breakpoint 0 here.')
diff --git a/packages/Python/lldbsuite/test/lang/c/modules/main.c b/packages/Python/lldbsuite/test/lang/c/modules/main.c
new file mode 100644
index 000000000000..2b244bc38d02
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/modules/main.c
@@ -0,0 +1,20 @@
+#include <stdlib.h>
+
+int printf(const char * __restrict format, ...);
+
+typedef struct {
+ int a;
+ int b;
+} FILE;
+
+int main()
+{
+ FILE *myFile = malloc(sizeof(FILE));
+
+ myFile->a = 5;
+ myFile->b = 9;
+
+ printf("%d\n", myFile->a + myFile->b); // Set breakpoint 0 here.
+
+ free(myFile);
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/recurse/Makefile b/packages/Python/lldbsuite/test/lang/c/recurse/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/recurse/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/recurse/main.c b/packages/Python/lldbsuite/test/lang/c/recurse/main.c
new file mode 100644
index 000000000000..1159669ebf15
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/recurse/main.c
@@ -0,0 +1,28 @@
+#include <stdint.h>
+#include <stdio.h>
+
+uint32_t
+recurse_crash (uint32_t depth)
+{
+ if (depth > 0)
+ return recurse_crash (depth - 1);
+ return 0;
+}
+
+int
+main (int argc, char const *argv[])
+{
+ // If we have more than one argument, then it should a depth to recurse to.
+ // If we have just the program name as an argument, use UINT32_MAX so we
+ // eventually crash the program by overflowing the stack
+ uint32_t depth = UINT32_MAX;
+ if (argc > 1)
+ {
+ char *end = NULL;
+ depth = strtoul (argv[1], &end, 0);
+ if (end == NULL || *end != '\0')
+ depth = UINT32_MAX;
+ }
+ recurse_crash (depth);
+ return 0;
+} \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/lang/c/register_variables/Makefile b/packages/Python/lldbsuite/test/lang/c/register_variables/Makefile
new file mode 100644
index 000000000000..12e55616b540
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/register_variables/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../make
+
+C_SOURCES := test.c
+
+CFLAGS ?= -g -O1
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/register_variables/TestRegisterVariables.py b/packages/Python/lldbsuite/test/lang/c/register_variables/TestRegisterVariables.py
new file mode 100644
index 000000000000..7ef1f246bfd3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/register_variables/TestRegisterVariables.py
@@ -0,0 +1,70 @@
+"""Check that compiler-generated register values work correctly"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class RegisterVariableTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureAll(oslist=['macosx'], compiler='clang', compiler_version=['<', '7.0.0'], debug_info="dsym")
+ @expectedFailureClang(None, ['<', '3.5'])
+ @expectedFailureGcc(None, ['is', '4.8.2'])
+ def test_and_run_command(self):
+ """Test expressions on register values."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break inside the main.
+ lldbutil.run_break_set_by_source_regexp(self, "break", num_expected_locations=2)
+
+ ####################
+ # First breakpoint
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ # Try some variables that should be visible
+ self.expect("expr a", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['(int) $0 = 2'])
+
+ self.expect("expr b->m1", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['(int) $1 = 3'])
+
+ #####################
+ # Second breakpoint
+
+ self.runCmd("continue")
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ # Try some variables that should be visible
+ self.expect("expr b->m2", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['(int) $2 = 5'])
+
+ self.expect("expr c", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['(int) $3 = 5'])
+
+ self.runCmd("kill")
diff --git a/packages/Python/lldbsuite/test/lang/c/register_variables/test.c b/packages/Python/lldbsuite/test/lang/c/register_variables/test.c
new file mode 100644
index 000000000000..e467ac48f745
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/register_variables/test.c
@@ -0,0 +1,27 @@
+#include <stdio.h>
+
+struct bar {
+ int m1;
+ int m2;
+};
+
+void f1(int a, struct bar *b) __attribute__ ((noinline));
+void f1(int a, struct bar *b)
+{
+ b->m2 = b->m1 + a; // set breakpoint here
+}
+
+void f2(struct bar *b) __attribute__ ((noinline));
+void f2(struct bar *b)
+{
+ int c = b->m2;
+ printf("%d\n", c); // set breakpoint here
+}
+
+int main()
+{
+ struct bar myBar = { 3, 4 };
+ f1(2, &myBar);
+ f2(&myBar);
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/set_values/Makefile b/packages/Python/lldbsuite/test/lang/c/set_values/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/set_values/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/set_values/TestSetValues.py b/packages/Python/lldbsuite/test/lang/c/set_values/TestSetValues.py
new file mode 100644
index 000000000000..ab8102496091
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/set_values/TestSetValues.py
@@ -0,0 +1,111 @@
+"""Test settings and readings of program variables."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class SetValuesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break inside main().
+ self.line1 = line_number('main.c', '// Set break point #1.')
+ self.line2 = line_number('main.c', '// Set break point #2.')
+ self.line3 = line_number('main.c', '// Set break point #3.')
+ self.line4 = line_number('main.c', '// Set break point #4.')
+ self.line5 = line_number('main.c', '// Set break point #5.')
+
+ @expectedFailureWindows("llvm.org/pr21765")
+ def test(self):
+ """Test settings and readings of program variables."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Set breakpoints on several places to set program variables.
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line1, num_expected_locations=1, loc_exact=True)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line2, num_expected_locations=1, loc_exact=True)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line3, num_expected_locations=1, loc_exact=True)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line4, num_expected_locations=1, loc_exact=True)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line5, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ # main.c:15
+ # Check that 'frame variable --show-types' displays the correct data type and value.
+ self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = "(char) i = 'a'")
+
+ # Now set variable 'i' and check that it is correctly displayed.
+ self.runCmd("expression i = 'b'")
+ self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = "(char) i = 'b'")
+
+ self.runCmd("continue")
+
+ # main.c:36
+ # Check that 'frame variable --show-types' displays the correct data type and value.
+ self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY,
+ patterns = ["\((short unsigned int|unsigned short)\) i = 33"])
+
+ # Now set variable 'i' and check that it is correctly displayed.
+ self.runCmd("expression i = 333")
+ self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY,
+ patterns = ["\((short unsigned int|unsigned short)\) i = 333"])
+
+ self.runCmd("continue")
+
+ # main.c:57
+ # Check that 'frame variable --show-types' displays the correct data type and value.
+ self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = "(long) i = 33")
+
+ # Now set variable 'i' and check that it is correctly displayed.
+ self.runCmd("expression i = 33333")
+ self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = "(long) i = 33333")
+
+ self.runCmd("continue")
+
+ # main.c:78
+ # Check that 'frame variable --show-types' displays the correct data type and value.
+ self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = "(double) i = 2.25")
+
+ # Now set variable 'i' and check that it is correctly displayed.
+ self.runCmd("expression i = 1.5")
+ self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = "(double) i = 1.5")
+
+ self.runCmd("continue")
+
+ # main.c:85
+ # Check that 'frame variable --show-types' displays the correct data type and value.
+ self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = "(long double) i = 2.25")
+
+ # Now set variable 'i' and check that it is correctly displayed.
+ self.runCmd("expression i = 1.5")
+ self.expect("frame variable --show-types", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = "(long double) i = 1.5")
diff --git a/packages/Python/lldbsuite/test/lang/c/set_values/main.c b/packages/Python/lldbsuite/test/lang/c/set_values/main.c
new file mode 100644
index 000000000000..64f01a97a286
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/set_values/main.c
@@ -0,0 +1,116 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+void set_char(void)
+{
+ char i = 'a';
+ printf("before (char) i = %c\n", i);
+ printf("after (char) i = %c\n", i); // Set break point #1. //// break $source:$line
+}
+
+void set_uchar(void)
+{
+ unsigned char i = 'a';
+ printf("before (unsigned char) i = %c\n", i);
+ printf("after (unsigned char) i = %c\n", i); //// break $source:$line
+}
+
+void set_short(void)
+{
+ short i = 33;
+ printf("before (short) i = %i\n", i);
+ printf("after (short) i = %i\n", i); //// break $source:$line
+}
+
+void set_ushort(void)
+{
+ unsigned short i = 33;
+ printf("before (unsigned short) i = %i\n", i);
+ printf("after (unsigned short) i = %i\n", i); // Set break point #2. //// break $source:$line
+}
+
+void set_int(void)
+{
+ int i = 33;
+ printf("before (int) i = %i\n", i);
+ printf("after (int) i = %i\n", i); //// break $source:$line
+}
+
+void set_uint(void)
+{
+ unsigned int i = 33;
+ printf("before (unsigned int) i = %u\n", i);
+ printf("after (unsigned int) i = %u\n", i); //// break $source:$line
+}
+
+void set_long(void)
+{
+ long i = 33;
+ printf("before (long) i = %li\n", i);
+ printf("after (long) i = %li\n", i); // Set break point #3. //// break $source:$line
+}
+
+void set_ulong(void)
+{
+ unsigned long i = 33;
+ printf("before (unsigned long) i = %lu\n", i);
+ printf("after (unsigned long) i = %lu\n", i); //// break $source:$line
+}
+
+void set_float(void)
+{
+ float i = 2.25;
+ printf("before (float) i = %g\n", i);
+ printf("after (float) i = %g\n", i); //// break $source:$line
+}
+
+void set_double(void)
+{
+ double i = 2.25;
+ printf("before (double) i = %g\n", i);
+ printf("after (double) i = %g\n", i); // Set break point #4. //// break $source:$line
+}
+
+void set_long_double(void)
+{
+ long double i = 2.25;
+ printf("before (long double) i = %Lg\n", i);
+ printf("after (long double) i = %Lg\n", i); // Set break point #5. //// break $source:$line
+}
+
+void set_point (void)
+{
+ struct point_tag {
+ int x;
+ int y;
+ };
+ struct point_tag points_2[2] = {
+ {1,2},
+ {3,4}
+ };
+}
+
+int main (int argc, char const *argv[])
+{
+ // Continue to the breakpoint in set_char()
+ set_char(); //// continue; var i; val -set 99 1
+ set_uchar(); //// continue; var i; val -set 99 2
+ set_short(); //// continue; var i; val -set -42 3
+ set_ushort(); //// continue; var i; val -set 42 4
+ set_int(); //// continue; var i; val -set -42 5
+ set_uint(); //// continue; var i; val -set 42 6
+ set_long(); //// continue; var i; val -set -42 7
+ set_ulong(); //// continue; var i; val -set 42 8
+ set_float(); //// continue; var i; val -set 123.456 9
+ set_double(); //// continue; var i; val -set 123.456 10
+ set_long_double(); //// continue; var i; val -set 123.456 11
+ set_point (); //// continue
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/shared_lib/Makefile b/packages/Python/lldbsuite/test/lang/c/shared_lib/Makefile
new file mode 100644
index 000000000000..854002e64708
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/shared_lib/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../../make
+
+DYLIB_NAME := foo
+DYLIB_C_SOURCES := foo.c
+C_SOURCES := main.c
+CFLAGS_EXTRAS += -fPIC
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/shared_lib/TestSharedLib.py b/packages/Python/lldbsuite/test/lang/c/shared_lib/TestSharedLib.py
new file mode 100644
index 000000000000..954d1bac6362
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/shared_lib/TestSharedLib.py
@@ -0,0 +1,71 @@
+"""Test that types defined in shared libraries work correctly."""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class SharedLibTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test_expr(self):
+ """Test that types work when defined in a shared library and forward-declared in the main executable"""
+ if "clang" in self.getCompiler() and "3.4" in self.getCompilerVersion():
+ self.skipTest("llvm.org/pr16214 -- clang emits partial DWARF for structures referenced via typedef")
+
+ self.build()
+ self.common_setup()
+
+ # This should display correctly.
+ self.expect("expression --show-types -- *my_foo_ptr", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["(foo)", "(sub_foo)", "other_element = 3"])
+
+ @unittest2.expectedFailure("rdar://problem/10704639")
+ def test_frame_variable(self):
+ """Test that types work when defined in a shared library and forward-declared in the main executable"""
+ self.build()
+ self.common_setup()
+
+ # This should display correctly.
+ self.expect("frame variable --show-types -- *my_foo_ptr", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["(foo)", "(sub_foo)", "other_element = 3"])
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.source = 'main.c'
+ self.line = line_number(self.source, '// Set breakpoint 0 here.')
+ self.shlib_names = ["foo"]
+
+ def common_setup(self):
+ # Run in synchronous mode
+ self.dbg.SetAsync(False)
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget("a.out")
+ self.assertTrue(target, VALID_TARGET)
+
+ # Break inside the foo function which takes a bar_ptr argument.
+ lldbutil.run_break_set_by_file_and_line (self, self.source, self.line, num_expected_locations=1, loc_exact=True)
+
+ # Register our shared libraries for remote targets so they get automatically uploaded
+ environment = self.registerSharedLibrariesWithTarget(target, self.shlib_names)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, environment, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
diff --git a/packages/Python/lldbsuite/test/lang/c/shared_lib/foo.c b/packages/Python/lldbsuite/test/lang/c/shared_lib/foo.c
new file mode 100644
index 000000000000..6431bc496c30
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/shared_lib/foo.c
@@ -0,0 +1,22 @@
+#include "foo.h"
+#include <stdlib.h>
+
+struct foo
+{
+ struct sub_foo sub_element;
+ int other_element;
+};
+
+struct foo *
+GetMeAFoo()
+{
+ struct foo *ret_val = (struct foo *) malloc (sizeof (struct foo));
+ ret_val->other_element = 3;
+ return ret_val;
+}
+
+struct sub_foo *
+GetMeASubFoo (struct foo *in_foo)
+{
+ return &(in_foo->sub_element);
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/shared_lib/foo.h b/packages/Python/lldbsuite/test/lang/c/shared_lib/foo.h
new file mode 100644
index 000000000000..78b9e3f9c0d9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/shared_lib/foo.h
@@ -0,0 +1,10 @@
+struct foo;
+
+struct sub_foo
+{
+ int sub_1;
+ char *sub_2;
+};
+
+LLDB_TEST_API struct foo *GetMeAFoo();
+LLDB_TEST_API struct sub_foo *GetMeASubFoo(struct foo *in_foo);
diff --git a/packages/Python/lldbsuite/test/lang/c/shared_lib/main.c b/packages/Python/lldbsuite/test/lang/c/shared_lib/main.c
new file mode 100644
index 000000000000..b4377de18c16
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/shared_lib/main.c
@@ -0,0 +1,13 @@
+#include <stdio.h>
+#include "foo.h"
+
+int
+main ()
+{
+ struct foo *my_foo_ptr;
+ my_foo_ptr = GetMeAFoo();
+
+ printf ("My sub foo has: %d.\n", GetMeASubFoo(my_foo_ptr)->sub_1); // Set breakpoint 0 here.
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/Makefile b/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/Makefile
new file mode 100644
index 000000000000..51347d73f09c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/Makefile
@@ -0,0 +1,10 @@
+LEVEL = ../../../make
+
+DYLIB_NAME := foo
+DYLIB_C_SOURCES := foo.c
+C_SOURCES := main.c
+CFLAGS_EXTRAS += -fPIC
+
+SPLIT_DEBUG_SYMBOLS = YES
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/TestSharedLibStrippedSymbols.py b/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/TestSharedLibStrippedSymbols.py
new file mode 100644
index 000000000000..a9cb46ca137b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/TestSharedLibStrippedSymbols.py
@@ -0,0 +1,73 @@
+"""Test that types defined in shared libraries with stripped symbols work correctly."""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class SharedLibStrippedTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureWindows # Test crashes
+ def test_expr(self):
+ """Test that types work when defined in a shared library and forward-declared in the main executable"""
+ if "clang" in self.getCompiler() and "3.4" in self.getCompilerVersion():
+ self.skipTest("llvm.org/pr16214 -- clang emits partial DWARF for structures referenced via typedef")
+
+ self.build()
+ self.common_setup()
+
+ # This should display correctly.
+ self.expect("expression --show-types -- *my_foo_ptr", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["(foo)", "(sub_foo)", "other_element = 3"])
+
+ @expectedFailureWindows # Test crashes
+ @unittest2.expectedFailure("rdar://problem/10381325")
+ def test_frame_variable(self):
+ """Test that types work when defined in a shared library and forward-declared in the main executable"""
+ self.build()
+ self.common_setup()
+
+ # This should display correctly.
+ self.expect("frame variable --show-types -- *my_foo_ptr", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["(foo)", "(sub_foo)", "other_element = 3"])
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.source = 'main.c'
+ self.line = line_number(self.source, '// Set breakpoint 0 here.')
+ self.shlib_names = ["foo"]
+
+ def common_setup(self):
+ # Run in synchronous mode
+ self.dbg.SetAsync(False)
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget("a.out")
+ self.assertTrue(target, VALID_TARGET)
+
+ # Break inside the foo function which takes a bar_ptr argument.
+ lldbutil.run_break_set_by_file_and_line (self, self.source, self.line, num_expected_locations=1, loc_exact=True)
+
+ # Register our shared libraries for remote targets so they get automatically uploaded
+ environment = self.registerSharedLibrariesWithTarget(target, self.shlib_names)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, environment, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
diff --git a/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/foo.c b/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/foo.c
new file mode 100644
index 000000000000..6431bc496c30
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/foo.c
@@ -0,0 +1,22 @@
+#include "foo.h"
+#include <stdlib.h>
+
+struct foo
+{
+ struct sub_foo sub_element;
+ int other_element;
+};
+
+struct foo *
+GetMeAFoo()
+{
+ struct foo *ret_val = (struct foo *) malloc (sizeof (struct foo));
+ ret_val->other_element = 3;
+ return ret_val;
+}
+
+struct sub_foo *
+GetMeASubFoo (struct foo *in_foo)
+{
+ return &(in_foo->sub_element);
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/foo.h b/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/foo.h
new file mode 100644
index 000000000000..78b3c1245387
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/foo.h
@@ -0,0 +1,12 @@
+struct foo;
+
+struct sub_foo
+{
+ int sub_1;
+ char *sub_2;
+};
+
+struct foo *GetMeAFoo();
+struct sub_foo *GetMeASubFoo (struct foo *in_foo);
+
+
diff --git a/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/main.c b/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/main.c
new file mode 100644
index 000000000000..b4377de18c16
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/shared_lib_stripped_symbols/main.c
@@ -0,0 +1,13 @@
+#include <stdio.h>
+#include "foo.h"
+
+int
+main ()
+{
+ struct foo *my_foo_ptr;
+ my_foo_ptr = GetMeAFoo();
+
+ printf ("My sub foo has: %d.\n", GetMeASubFoo(my_foo_ptr)->sub_1); // Set breakpoint 0 here.
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/stepping/Makefile b/packages/Python/lldbsuite/test/lang/c/stepping/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/stepping/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/stepping/TestStepAndBreakpoints.py b/packages/Python/lldbsuite/test/lang/c/stepping/TestStepAndBreakpoints.py
new file mode 100644
index 000000000000..c7a3de4b6846
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/stepping/TestStepAndBreakpoints.py
@@ -0,0 +1,242 @@
+"""Test stepping over vrs. hitting breakpoints & subsequent stepping in various forms."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TestCStepping(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def getCategories(self):
+ return ['basic_process']
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers that we will step to in main:
+ self.main_source = "main.c"
+
+ @expectedFailureFreeBSD('llvm.org/pr17932')
+ @expectedFailureLinux # llvm.org/pr14437
+ @expectedFailureWindows("llvm.org/pr24777")
+ @add_test_categories(['pyapi'])
+ def test_and_python_api(self):
+ """Test stepping over vrs. hitting breakpoints & subsequent stepping in various forms."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ self.main_source_spec = lldb.SBFileSpec (self.main_source)
+
+ breakpoints_to_disable = []
+
+ break_1_in_main = target.BreakpointCreateBySourceRegex ('// frame select 2, thread step-out while stopped at .c.1..', self.main_source_spec)
+ self.assertTrue(break_1_in_main, VALID_BREAKPOINT)
+ breakpoints_to_disable.append (break_1_in_main)
+
+ break_in_a = target.BreakpointCreateBySourceRegex ('// break here to stop in a before calling b', self.main_source_spec)
+ self.assertTrue(break_in_a, VALID_BREAKPOINT)
+ breakpoints_to_disable.append (break_in_a)
+
+ break_in_b = target.BreakpointCreateBySourceRegex ('// thread step-out while stopped at .c.2..', self.main_source_spec)
+ self.assertTrue(break_in_b, VALID_BREAKPOINT)
+ breakpoints_to_disable.append (break_in_b)
+
+ break_in_c = target.BreakpointCreateBySourceRegex ('// Find the line number of function .c. here.', self.main_source_spec)
+ self.assertTrue(break_in_c, VALID_BREAKPOINT)
+ breakpoints_to_disable.append (break_in_c)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, break_1_in_main)
+
+ if len(threads) != 1:
+ self.fail ("Failed to stop at first breakpoint in main.")
+
+ thread = threads[0]
+
+ # Get the stop id and for fun make sure it increases:
+ old_stop_id = process.GetStopID()
+
+ # Now step over, which should cause us to hit the breakpoint in "a"
+ thread.StepOver()
+
+ # The stop reason of the thread should be breakpoint.
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, break_in_a)
+ if len(threads) != 1:
+ self.fail ("Failed to stop at breakpoint in a.")
+
+ # Check that the stop ID increases:
+ new_stop_id = process.GetStopID()
+ self.assertTrue(new_stop_id > old_stop_id, "Stop ID increases monotonically.")
+
+ thread = threads[0]
+
+ # Step over, and we should hit the breakpoint in b:
+ thread.StepOver()
+
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, break_in_b)
+ if len(threads) != 1:
+ self.fail ("Failed to stop at breakpoint in b.")
+ thread = threads[0]
+
+ # Now try running some function, and make sure that we still end up in the same place
+ # and with the same stop reason.
+ frame = thread.GetFrameAtIndex(0)
+ current_line = frame.GetLineEntry().GetLine()
+ current_file = frame.GetLineEntry().GetFileSpec()
+ current_bp = []
+ current_bp.append(thread.GetStopReasonDataAtIndex(0))
+ current_bp.append(thread.GetStopReasonDataAtIndex(1))
+
+ stop_id_before_expression = process.GetStopID()
+ stop_id_before_including_expressions = process.GetStopID(True)
+
+ frame.EvaluateExpression ("(int) printf (print_string)")
+
+ frame = thread.GetFrameAtIndex(0)
+ self.assertTrue (current_line == frame.GetLineEntry().GetLine(), "The line stayed the same after expression.")
+ self.assertTrue (current_file == frame.GetLineEntry().GetFileSpec(), "The file stayed the same after expression.")
+ self.assertTrue (thread.GetStopReason() == lldb.eStopReasonBreakpoint, "We still say we stopped for a breakpoint.")
+ self.assertTrue (thread.GetStopReasonDataAtIndex(0) == current_bp[0] and thread.GetStopReasonDataAtIndex(1) == current_bp[1], "And it is the same breakpoint.")
+
+ # Also make sure running the expression didn't change the public stop id
+ # but did change if we are asking for expression stops as well.
+ stop_id_after_expression = process.GetStopID()
+ stop_id_after_including_expressions = process.GetStopID(True)
+
+ self.assertTrue (stop_id_before_expression == stop_id_after_expression, "Expression calling doesn't change stop ID")
+
+ self.assertTrue (stop_id_after_including_expressions > stop_id_before_including_expressions, "Stop ID including expressions increments over expression call.")
+
+ # Do the same thing with an expression that's going to crash, and make sure we are still unchanged.
+
+ frame.EvaluateExpression ("((char *) 0)[0] = 'a'")
+
+ frame = thread.GetFrameAtIndex(0)
+ self.assertTrue (current_line == frame.GetLineEntry().GetLine(), "The line stayed the same after expression.")
+ self.assertTrue (current_file == frame.GetLineEntry().GetFileSpec(), "The file stayed the same after expression.")
+ self.assertTrue (thread.GetStopReason() == lldb.eStopReasonBreakpoint, "We still say we stopped for a breakpoint.")
+ self.assertTrue (thread.GetStopReasonDataAtIndex(0) == current_bp[0] and thread.GetStopReasonDataAtIndex(1) == current_bp[1], "And it is the same breakpoint.")
+
+ # Now continue and make sure we just complete the step:
+ # Disable all our breakpoints first - sometimes the compiler puts two line table entries in for the
+ # breakpoint a "b" and we don't want to hit that.
+ for bkpt in breakpoints_to_disable:
+ bkpt.SetEnabled(False)
+
+ process.Continue()
+
+ self.assertTrue (thread.GetFrameAtIndex(0).GetFunctionName() == "a")
+ self.assertTrue (thread.GetStopReason() == lldb.eStopReasonPlanComplete)
+
+ # And one more time should get us back to main:
+ process.Continue()
+
+ self.assertTrue (thread.GetFrameAtIndex(0).GetFunctionName() == "main")
+ self.assertTrue (thread.GetStopReason() == lldb.eStopReasonPlanComplete)
+
+ # Now make sure we can call a function, break in the called function, then have "continue" get us back out again:
+ frame = thread.GetFrameAtIndex(0)
+ frame = thread.GetFrameAtIndex(0)
+ current_line = frame.GetLineEntry().GetLine()
+ current_file = frame.GetLineEntry().GetFileSpec()
+
+ break_in_b.SetEnabled(True)
+ frame.EvaluateExpression ("b (4)", lldb.eNoDynamicValues, False)
+
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, break_in_b)
+ if len(threads) != 1:
+ self.fail ("Failed to stop at breakpoint in b when calling b.")
+ thread = threads[0]
+
+ # So do a step over here to make sure we can still do that:
+
+ thread.StepOver()
+
+ # See that we are still in b:
+ func_name = thread.GetFrameAtIndex(0).GetFunctionName()
+ self.assertTrue (func_name == "b", "Should be in 'b', were in %s"%(func_name))
+
+ # Okay, now if we continue, we will finish off our function call and we should end up back in "a" as if nothing had happened:
+ process.Continue ()
+
+ self.assertTrue (thread.GetFrameAtIndex(0).GetLineEntry().GetLine() == current_line)
+ self.assertTrue (thread.GetFrameAtIndex(0).GetLineEntry().GetFileSpec() == current_file)
+
+ # Now we are going to test step in targeting a function:
+
+ break_in_b.SetEnabled (False)
+
+ break_before_complex_1 = target.BreakpointCreateBySourceRegex ('// Stop here to try step in targeting b.', self.main_source_spec)
+ self.assertTrue(break_before_complex_1, VALID_BREAKPOINT)
+
+ break_before_complex_2 = target.BreakpointCreateBySourceRegex ('// Stop here to try step in targeting complex.', self.main_source_spec)
+ self.assertTrue(break_before_complex_2, VALID_BREAKPOINT)
+
+ break_before_complex_3 = target.BreakpointCreateBySourceRegex ('// Stop here to step targeting b and hitting breakpoint.', self.main_source_spec)
+ self.assertTrue(break_before_complex_3, VALID_BREAKPOINT)
+
+ break_before_complex_4 = target.BreakpointCreateBySourceRegex ('// Stop here to make sure bogus target steps over.', self.main_source_spec)
+ self.assertTrue(break_before_complex_4, VALID_BREAKPOINT)
+
+ threads = lldbutil.continue_to_breakpoint(process, break_before_complex_1)
+ self.assertTrue (len(threads) == 1)
+ thread = threads[0]
+ break_before_complex_1.SetEnabled(False)
+
+ thread.StepInto ("b")
+ self.assertTrue (thread.GetFrameAtIndex(0).GetFunctionName() == "b")
+
+ # Now continue out and stop at the next call to complex. This time step all the way into complex:
+ threads = lldbutil.continue_to_breakpoint (process, break_before_complex_2)
+ self.assertTrue (len(threads) == 1)
+ thread = threads[0]
+ break_before_complex_2.SetEnabled(False)
+
+ thread.StepInto ("complex")
+ self.assertTrue (thread.GetFrameAtIndex(0).GetFunctionName() == "complex")
+
+ # Now continue out and stop at the next call to complex. This time enable breakpoints in a and c and then step targeting b:
+ threads = lldbutil.continue_to_breakpoint (process, break_before_complex_3)
+ self.assertTrue (len(threads) == 1)
+ thread = threads[0]
+ break_before_complex_3.SetEnabled(False)
+
+ break_at_start_of_a = target.BreakpointCreateByName ('a')
+ break_at_start_of_c = target.BreakpointCreateByName ('c')
+
+ thread.StepInto ("b")
+ threads = lldbutil.get_stopped_threads(process, lldb.eStopReasonBreakpoint);
+
+ self.assertTrue (len(threads) == 1)
+ thread = threads[0]
+ stop_break_id = thread.GetStopReasonDataAtIndex(0)
+ self.assertTrue(stop_break_id == break_at_start_of_a.GetID() or stop_break_id == break_at_start_of_c.GetID())
+
+ break_at_start_of_a.SetEnabled(False)
+ break_at_start_of_c.SetEnabled(False)
+
+ process.Continue()
+ self.assertTrue (thread.GetFrameAtIndex(0).GetFunctionName() == "b")
+
+ # Now continue out and stop at the next call to complex. This time enable breakpoints in a and c and then step targeting b:
+ threads = lldbutil.continue_to_breakpoint (process, break_before_complex_4)
+ self.assertTrue (len(threads) == 1)
+ thread = threads[0]
+ break_before_complex_4.SetEnabled(False)
+
+ thread.StepInto("NoSuchFunction")
+ self.assertTrue (thread.GetFrameAtIndex(0).GetFunctionName() == "main")
diff --git a/packages/Python/lldbsuite/test/lang/c/stepping/TestThreadStepping.py b/packages/Python/lldbsuite/test/lang/c/stepping/TestThreadStepping.py
new file mode 100644
index 000000000000..c3ed3f933ab0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/stepping/TestThreadStepping.py
@@ -0,0 +1,81 @@
+"""
+Test thread stepping features in combination with frame select.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ThreadSteppingTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to of function 'c'.
+ self.line1 = line_number('main.c', '// Find the line number of function "c" here.')
+ self.line2 = line_number('main.c', '// frame select 2, thread step-out while stopped at "c(1)"')
+ self.line3 = line_number('main.c', '// thread step-out while stopped at "c(2)"')
+ self.line4 = line_number('main.c', '// frame select 1, thread step-out while stopped at "c(3)"')
+
+ def test_step_out_with_run_command(self):
+ """Exercise thread step-out and frame select followed by thread step-out."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Create a breakpoint inside function 'c'.
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line1, num_expected_locations=1, loc_exact=True)
+
+ # Now run the program.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The process should be stopped at this point.
+ self.expect("process status", PROCESS_STOPPED,
+ patterns = ['Process .* stopped'])
+
+ # The frame #0 should correspond to main.c:32, the executable statement
+ # in function name 'c'. And frame #3 should point to main.c:37.
+ self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ["stop reason = breakpoint"],
+ patterns = ["frame #0.*main.c:%d" % self.line1,
+ "frame #3.*main.c:%d" % self.line2])
+
+ # We want to move the pc to frame #3. This can be accomplished by
+ # 'frame select 2', followed by 'thread step-out'.
+ self.runCmd("frame select 2")
+ self.runCmd("thread step-out")
+ self.expect("thread backtrace", STEP_OUT_SUCCEEDED,
+ substrs = ["stop reason = step out"],
+ patterns = ["frame #0.*main.c:%d" % self.line2])
+
+ # Let's move on to a single step-out case.
+ self.runCmd("process continue")
+
+ # The process should be stopped at this point.
+ self.expect("process status", PROCESS_STOPPED,
+ patterns = ['Process .* stopped'])
+ self.runCmd("thread step-out")
+ self.expect("thread backtrace", STEP_OUT_SUCCEEDED,
+ substrs = ["stop reason = step out"],
+ patterns = ["frame #0.*main.c:%d" % self.line3])
+
+ # Do another frame selct, followed by thread step-out.
+ self.runCmd("process continue")
+
+ # The process should be stopped at this point.
+ self.expect("process status", PROCESS_STOPPED,
+ patterns = ['Process .* stopped'])
+ self.runCmd("frame select 1")
+ self.runCmd("thread step-out")
+ self.expect("thread backtrace", STEP_OUT_SUCCEEDED,
+ substrs = ["stop reason = step out"],
+ patterns = ["frame #0.*main.c:%d" % self.line4])
diff --git a/packages/Python/lldbsuite/test/lang/c/stepping/main.c b/packages/Python/lldbsuite/test/lang/c/stepping/main.c
new file mode 100644
index 000000000000..d8b4a2da761e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/stepping/main.c
@@ -0,0 +1,69 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+int a(int);
+int b(int);
+int c(int);
+const char *print_string = "aaaaaaaaaa\n";
+
+int a(int val)
+{
+ int return_value = val; // basic break at the start of b
+
+ if (val <= 1)
+ {
+ return_value = b(val); // break here to stop in a before calling b
+ }
+ else if (val >= 3)
+ {
+ return_value = c(val);
+ }
+
+ return return_value;
+}
+
+int b(int val)
+{
+ int rc = c(val); // thread step-out while stopped at "c(2)"
+ return rc;
+}
+
+int c(int val)
+{
+ return val + 3; // Find the line number of function "c" here.
+}
+
+int complex (int first, int second, int third)
+{
+ return first + second + third; // Step in targeting complex should stop here
+}
+
+int main (int argc, char const *argv[])
+{
+ int A1 = a(1); // frame select 2, thread step-out while stopped at "c(1)"
+ printf("a(1) returns %d\n", A1);
+
+ int B2 = b(2);
+ printf("b(2) returns %d\n", B2);
+
+ int A3 = a(3); // frame select 1, thread step-out while stopped at "c(3)"
+ printf("a(3) returns %d\n", A3);
+
+ int A4 = complex (a(1), b(2), c(3)); // Stop here to try step in targeting b.
+
+ int A5 = complex (a(2), b(3), c(4)); // Stop here to try step in targeting complex.
+
+ int A6 = complex (a(4), b(5), c(6)); // Stop here to step targeting b and hitting breakpoint.
+
+ int A7 = complex (a(5), b(6), c(7)); // Stop here to make sure bogus target steps over.
+
+ printf ("I am using print_string: %s.\n", print_string);
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/strings/Makefile b/packages/Python/lldbsuite/test/lang/c/strings/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/strings/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/strings/TestCStrings.py b/packages/Python/lldbsuite/test/lang/c/strings/TestCStrings.py
new file mode 100644
index 000000000000..6f2a9ff03be0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/strings/TestCStrings.py
@@ -0,0 +1,54 @@
+"""
+Tests that C strings work as expected in expressions
+"""
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class CStringsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureWindows("llvm.org/pr21765")
+ def test_with_run_command(self):
+ """Tests that C strings work as expected in expressions"""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ line = line_number('main.c', '// breakpoint 1')
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("process launch", RUN_SUCCEEDED)
+
+ self.expect("expression -- a[2]",
+ patterns = ["\((const )?char\) \$0 = 'c'"])
+
+ self.expect("expression -- z[2]",
+ startstr = "(const char) $1 = 'x'")
+
+ # On Linux, the expression below will test GNU indirect function calls.
+ self.expect("expression -- (int)strlen(\"hello\")",
+ startstr = "(int) $2 = 5")
+
+ self.expect("expression -- \"world\"[2]",
+ startstr = "(const char) $3 = 'r'")
+
+ self.expect("expression -- \"\"[0]",
+ startstr = "(const char) $4 = '\\0'")
+
+ self.expect("expr --raw -- \"hello\"",
+ substrs = ['[0] = \'h\'',
+ '[5] = \'\\0\''])
+
+ self.expect("p \"hello\"",
+ substrs = ['[6]) $', 'hello'])
+
+ self.expect("p (char*)\"hello\"",
+ substrs = ['(char *) $', ' = 0x',
+ 'hello'])
+
+ self.expect("p (int)strlen(\"\")",
+ substrs = ['(int) $', ' = 0'])
+
+ self.expect("expression !z",
+ substrs = ['false'])
diff --git a/packages/Python/lldbsuite/test/lang/c/strings/main.c b/packages/Python/lldbsuite/test/lang/c/strings/main.c
new file mode 100644
index 000000000000..e02580b407f5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/strings/main.c
@@ -0,0 +1,18 @@
+//===-- main.c ----------------------------------------------------*- C -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+
+int main()
+{
+ const char a[] = "abcde";
+ const char *z = "vwxyz";
+
+ printf("%s %s", a, z); // breakpoint 1
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/struct_types/Makefile b/packages/Python/lldbsuite/test/lang/c/struct_types/Makefile
new file mode 100644
index 000000000000..cd9ca5c86d84
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/struct_types/Makefile
@@ -0,0 +1,3 @@
+LEVEL = ../../../make
+C_SOURCES := main.c
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/struct_types/TestStructTypes.py b/packages/Python/lldbsuite/test/lang/c/struct_types/TestStructTypes.py
new file mode 100644
index 000000000000..87ad326f3181
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/struct_types/TestStructTypes.py
@@ -0,0 +1,4 @@
+import lldbsuite.test.lldbinline as lldbinline
+import lldbsuite.test.lldbtest as lldbtest
+
+lldbinline.MakeInlineTest(__file__, globals(), [lldbtest.expectedFailureWindows("llvm.org/pr24764")] )
diff --git a/packages/Python/lldbsuite/test/lang/c/struct_types/main.c b/packages/Python/lldbsuite/test/lang/c/struct_types/main.c
new file mode 100644
index 000000000000..29ac10cb94a8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/struct_types/main.c
@@ -0,0 +1,43 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+struct things_to_sum {
+ int a;
+ int b;
+ int c;
+};
+
+int sum_things(struct things_to_sum tts)
+{
+ return tts.a + tts.b + tts.c;
+}
+
+int main (int argc, char const *argv[])
+{
+ struct point_tag {
+ int x;
+ int y;
+ char padding[0];
+ }; //% self.expect("frame variable pt.padding[0]", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["pt.padding[0] = "])
+ //% self.expect("frame variable pt.padding[1]", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["pt.padding[1] = "])
+ //% self.expect("expression -- (pt.padding[0])", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["(char)", " = "])
+ //% self.expect("image lookup -t point_tag", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ['padding[]']) # Once rdar://problem/12566646 is fixed, this should display correctly
+
+ struct rect_tag {
+ struct point_tag bottom_left;
+ struct point_tag top_right;
+ };
+ struct point_tag pt = { 2, 3, {} };
+ struct rect_tag rect = {{1, 2, {}}, {3, 4, {}}};
+ struct things_to_sum tts = { 2, 3, 4 };
+
+ int sum = sum_things(tts); //% self.expect("expression -- &pt == (struct point_tag*)0", substrs = ['false'])
+ //% self.expect("expression -- sum_things(tts)", substrs = ['9'])
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/tls_globals/Makefile b/packages/Python/lldbsuite/test/lang/c/tls_globals/Makefile
new file mode 100644
index 000000000000..90affed8e3ad
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/tls_globals/Makefile
@@ -0,0 +1,11 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+CFLAGS_EXTRAS += -fPIC
+
+DYLIB_NAME := a
+DYLIB_C_SOURCES := a.c
+
+ENABLE_THREADS := YES
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/tls_globals/TestTlsGlobals.py b/packages/Python/lldbsuite/test/lang/c/tls_globals/TestTlsGlobals.py
new file mode 100644
index 000000000000..0d9e22ec3adf
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/tls_globals/TestTlsGlobals.py
@@ -0,0 +1,75 @@
+"""Test that thread-local storage can be read correctly."""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TlsGlobalTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ TestBase.setUp(self)
+
+ if self.getPlatform() == "freebsd" or self.getPlatform() == "linux":
+ # LD_LIBRARY_PATH must be set so the shared libraries are found on startup
+ if "LD_LIBRARY_PATH" in os.environ:
+ self.runCmd("settings set target.env-vars " + self.dylibPath + "=" + os.environ["LD_LIBRARY_PATH"] + ":" + os.getcwd())
+ else:
+ self.runCmd("settings set target.env-vars " + self.dylibPath + "=" + os.getcwd())
+ self.addTearDownHook(lambda: self.runCmd("settings remove target.env-vars " + self.dylibPath))
+
+ @unittest2.expectedFailure("rdar://7796742")
+ @skipIfWindows # TLS works differently on Windows, this would need to be implemented separately.
+ def test(self):
+ """Test thread-local storage."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ line1 = line_number('main.c', '// thread breakpoint')
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", line1, num_expected_locations=1, loc_exact=True)
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.runCmd("process status", "Get process status")
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # BUG: sometimes lldb doesn't change threads to the stopped thread.
+ # (unrelated to this test).
+ self.runCmd("thread select 2", "Change thread")
+
+ # Check that TLS evaluates correctly within the thread.
+ self.expect("expr var_static", VARIABLES_DISPLAYED_CORRECTLY,
+ patterns = ["\(int\) \$.* = 88"])
+ self.expect("expr var_shared", VARIABLES_DISPLAYED_CORRECTLY,
+ patterns = ["\(int\) \$.* = 66"])
+
+ # Continue on the main thread
+ line2 = line_number('main.c', '// main breakpoint')
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", line2, num_expected_locations=1, loc_exact=True)
+ self.runCmd("continue", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.runCmd("process status", "Get process status")
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # BUG: sometimes lldb doesn't change threads to the stopped thread.
+ # (unrelated to this test).
+ self.runCmd("thread select 1", "Change thread")
+
+ # Check that TLS evaluates correctly within the main thread.
+ self.expect("expr var_static", VARIABLES_DISPLAYED_CORRECTLY,
+ patterns = ["\(int\) \$.* = 44"])
+ self.expect("expr var_shared", VARIABLES_DISPLAYED_CORRECTLY,
+ patterns = ["\(int\) \$.* = 33"])
diff --git a/packages/Python/lldbsuite/test/lang/c/tls_globals/a.c b/packages/Python/lldbsuite/test/lang/c/tls_globals/a.c
new file mode 100644
index 000000000000..b9a85902d117
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/tls_globals/a.c
@@ -0,0 +1,18 @@
+//===-- a.c -----------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <unistd.h>
+
+__thread int var_shared = 33;
+
+void shared_check()
+{
+ var_shared *= 2;
+ usleep(1); // shared thread breakpoint
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/tls_globals/main.c b/packages/Python/lldbsuite/test/lang/c/tls_globals/main.c
new file mode 100644
index 000000000000..cbe01b89b7ef
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/tls_globals/main.c
@@ -0,0 +1,36 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+#include <pthread.h>
+#include <unistd.h>
+
+void shared_check();
+
+// Create some TLS storage within the static executable.
+__thread int var_static = 44;
+
+void *fn_static(void *param)
+{
+ var_static *= 2;
+ shared_check();
+ usleep(1); // thread breakpoint
+ for(;;)
+ usleep(1);
+}
+
+int main (int argc, char const *argv[])
+{
+ pthread_t handle;
+ pthread_create(&handle, NULL, &fn_static, NULL);
+
+ for(;;)
+ usleep(1); // main breakpoint
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/c/typedef/Makefile b/packages/Python/lldbsuite/test/lang/c/typedef/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/typedef/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/c/typedef/Testtypedef.py b/packages/Python/lldbsuite/test/lang/c/typedef/Testtypedef.py
new file mode 100644
index 000000000000..a4870de1d177
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/typedef/Testtypedef.py
@@ -0,0 +1,40 @@
+"""Look up type information for typedefs of same name at different lexical scope and check for correct display."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TypedefTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureAll(bugnumber="llvm.org/pr19238", compiler="clang")
+ @expectedFailureAll(bugnumber="llvm.org/pr25626 expectedFailureClang fails on FreeBSD", oslist=["freebsd"])
+ def test_typedef(self):
+ """Test 'image lookup -t a' and check for correct display at different scopes."""
+ self.build()
+ self.image_lookup_for_multiple_typedefs()
+
+ def image_lookup_for_multiple_typedefs(self):
+ """Test 'image lookup -t a' at different scopes and check for correct display."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+ typearray = ("float", "float", "char", "double *", "float", "int", "double", "float", "float")
+ arraylen = len(typearray)+1
+ for i in range(1,arraylen):
+ loc_line = line_number('main.c', '// Set break point ' + str(i) + '.')
+ lldbutil.run_break_set_by_file_and_line (self, "main.c",loc_line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ for t in typearray:
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped', 'stop reason = breakpoint'])
+ self.expect("image lookup -t a", DATA_TYPES_DISPLAYED_CORRECTLY,
+ substrs = ['name = "' + t + '"'])
+ self.runCmd("continue")
diff --git a/packages/Python/lldbsuite/test/lang/c/typedef/main.c b/packages/Python/lldbsuite/test/lang/c/typedef/main.c
new file mode 100644
index 000000000000..62f8a00e6644
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/c/typedef/main.c
@@ -0,0 +1,46 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+void test()
+{
+ typedef double * a;
+ a b = 0; // Set break point 4.
+}
+int main (int argc, char const *argv[])
+{
+ typedef float a;
+ int i = 0; // Set break point 1.
+ i++;
+ a floatvariable = 2.7; // Set break point 2.
+ {
+ typedef char a;
+ i++;
+ a charvariable = 'a'; // Set break point 3.
+ test();
+ }
+ {
+ int c = 0;
+ c++; // Set break point 5.
+ for(i = 0 ; i < 1 ; i++)
+ {
+ typedef int a;
+ a b;
+ b = 7; // Set break point 6.
+ }
+ for(i = 0 ; i < 1 ; i++)
+ {
+ typedef double a;
+ a b;
+ b = 3.14; // Set break point 7.
+ }
+ c = 1; // Set break point 8.
+ }
+ floatvariable = 2.5;
+ floatvariable = 2.8; // Set break point 9.
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/auto/Makefile b/packages/Python/lldbsuite/test/lang/cpp/auto/Makefile
new file mode 100644
index 000000000000..194af7b32398
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/auto/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+CFLAGS_EXTRAS += $(NO_LIMIT_DEBUG_INFO_FLAGS)
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/auto/TestCPPAuto.py b/packages/Python/lldbsuite/test/lang/cpp/auto/TestCPPAuto.py
new file mode 100644
index 000000000000..9746dec2fa3d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/auto/TestCPPAuto.py
@@ -0,0 +1,25 @@
+"""
+Tests that auto types work
+"""
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class CPPAutoTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureGcc("GCC does not generate complete debug info")
+ def test_with_run_command(self):
+ """Test that auto types work in the expression parser"""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ line = line_number('main.cpp', '// break here')
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", line, num_expected_locations=-1, loc_exact=False)
+
+ self.runCmd("process launch", RUN_SUCCEEDED)
+
+ self.expect('expr auto f = 123456; f', substrs=['int', '123456'])
+ self.expect('expr struct Test { int x; int y; Test() : x(123), y(456) {} }; auto t = Test(); t', substrs=['Test', '123', '456'])
+ self.expect('expr auto s = helloworld; s', substrs=['string', 'hello world'])
diff --git a/packages/Python/lldbsuite/test/lang/cpp/auto/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/auto/main.cpp
new file mode 100644
index 000000000000..76fb95e0a34c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/auto/main.cpp
@@ -0,0 +1,16 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <string>
+
+int main()
+{
+ std::string helloworld("hello world");
+ return 0; // break here
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/bool/Makefile b/packages/Python/lldbsuite/test/lang/cpp/bool/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/bool/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/bool/TestCPPBool.py b/packages/Python/lldbsuite/test/lang/cpp/bool/TestCPPBool.py
new file mode 100644
index 000000000000..ef7135cfaa07
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/bool/TestCPPBool.py
@@ -0,0 +1,26 @@
+"""
+Tests that bool types work
+"""
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class CPPBoolTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test_with_run_command(self):
+ """Test that bool types work in the expression parser"""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ line = line_number('main.cpp', '// breakpoint 1')
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", line, num_expected_locations=-1, loc_exact=False)
+
+ self.runCmd("process launch", RUN_SUCCEEDED)
+
+ self.expect("expression -- bool second_bool = my_bool; second_bool",
+ startstr = "(bool) $0 = false")
+
+ self.expect("expression -- my_bool = true",
+ startstr = "(bool) $1 = true")
diff --git a/packages/Python/lldbsuite/test/lang/cpp/bool/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/bool/main.cpp
new file mode 100644
index 000000000000..88d02d5b2894
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/bool/main.cpp
@@ -0,0 +1,17 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+
+int main()
+{
+ bool my_bool = false;
+
+ printf("%s\n", my_bool ? "true" : "false"); // breakpoint 1
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/Makefile b/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/Makefile
new file mode 100644
index 000000000000..1d1f38f7fd0e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := nested.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/TestCPPBreakpointCommands.py b/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/TestCPPBreakpointCommands.py
new file mode 100644
index 000000000000..6c06f3750d13
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/TestCPPBreakpointCommands.py
@@ -0,0 +1,84 @@
+"""
+Test lldb breakpoint command for CPP methods & functions in a namespace.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class CPPBreakpointCommandsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureWindows
+ def test(self):
+ """Test a sequence of breakpoint command add, list, and delete."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target from the debugger.
+
+ target = self.dbg.CreateTarget (exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ a_out_module = lldb.SBFileSpecList()
+ a_out_module.Append(lldb.SBFileSpec(exe))
+
+ nested_comp_unit = lldb.SBFileSpecList()
+ nested_comp_unit.Append (lldb.SBFileSpec("nested.cpp"))
+
+ # First provide ONLY the method name. This should get everybody...
+ auto_break = target.BreakpointCreateByName ("Function",
+ lldb.eFunctionNameTypeAuto,
+ a_out_module,
+ nested_comp_unit)
+ self.assertTrue (auto_break.GetNumLocations() == 5)
+
+ # Now add the Baz class specifier. This should get the version contained in Bar,
+ # AND the one contained in ::
+ auto_break = target.BreakpointCreateByName ("Baz::Function",
+ lldb.eFunctionNameTypeAuto,
+ a_out_module,
+ nested_comp_unit)
+ self.assertTrue (auto_break.GetNumLocations() == 2)
+
+ # Then add the Bar::Baz specifier. This should get the version contained in Bar only
+ auto_break = target.BreakpointCreateByName ("Bar::Baz::Function",
+ lldb.eFunctionNameTypeAuto,
+ a_out_module,
+ nested_comp_unit)
+ self.assertTrue (auto_break.GetNumLocations() == 1)
+
+ plain_method_break = target.BreakpointCreateByName ("Function",
+ lldb.eFunctionNameTypeMethod,
+ a_out_module,
+ nested_comp_unit)
+ self.assertTrue (plain_method_break.GetNumLocations() == 3)
+
+ plain_method_break = target.BreakpointCreateByName ("Baz::Function",
+ lldb.eFunctionNameTypeMethod,
+ a_out_module,
+ nested_comp_unit)
+ self.assertTrue (plain_method_break.GetNumLocations() == 2)
+
+ plain_method_break = target.BreakpointCreateByName ("Bar::Baz::Function",
+ lldb.eFunctionNameTypeMethod,
+ a_out_module,
+ nested_comp_unit)
+ self.assertTrue (plain_method_break.GetNumLocations() == 1)
+
+ plain_method_break = target.BreakpointCreateByName ("Function",
+ lldb.eFunctionNameTypeBase,
+ a_out_module,
+ nested_comp_unit)
+ self.assertTrue (plain_method_break.GetNumLocations() == 2)
+
+ plain_method_break = target.BreakpointCreateByName ("Bar::Function",
+ lldb.eFunctionNameTypeBase,
+ a_out_module,
+ nested_comp_unit)
+ self.assertTrue (plain_method_break.GetNumLocations() == 1)
diff --git a/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/nested.cpp b/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/nested.cpp
new file mode 100644
index 000000000000..29d4b4cb19e7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/breakpoint-commands/nested.cpp
@@ -0,0 +1,76 @@
+#include <stdio.h>
+
+namespace Foo
+{
+ namespace Bar
+ {
+ class Baz
+ {
+ public:
+ Baz (int value):m_value(value) {}
+ int Function ()
+ {
+ printf ("%s returning: %d.\n", __FUNCTION__, m_value);
+ return m_value;
+ }
+ private:
+ int m_value;
+ };
+
+ class Baz2
+ {
+ public:
+ Baz2 (int value):m_value(value) {}
+ int Function ()
+ {
+ printf ("%s returning: %d.\n", __FUNCTION__, m_value);
+ return m_value;
+ }
+ private:
+ int m_value;
+ };
+
+ static int bar_value = 20;
+ int Function ()
+ {
+ printf ("%s returning: %d.\n", __FUNCTION__, bar_value);
+ return bar_value;
+ }
+ }
+}
+
+class Baz
+{
+public:
+ Baz (int value):m_value(value) {}
+ int Function ()
+ {
+ printf ("%s returning: %d.\n", __FUNCTION__, m_value);
+ return m_value;
+ }
+private:
+ int m_value;
+};
+
+int
+Function ()
+{
+ printf ("I am a global function, I return 333.\n");
+ return 333;
+}
+
+int main ()
+{
+ Foo::Bar::Baz mine(200);
+ Foo::Bar::Baz2 mine2(300);
+ ::Baz bare_baz (500);
+
+ printf ("Yup, got %d from Baz.\n", mine.Function());
+ printf ("Yup, got %d from Baz.\n", mine2.Function());
+ printf ("Yup, got %d from Baz.\n", bare_baz.Function());
+ printf ("And got %d from Bar.\n", Foo::Bar::Function());
+ printf ("And got %d from ::.\n", ::Function());
+
+ return 0;
+
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/call-function/Makefile b/packages/Python/lldbsuite/test/lang/cpp/call-function/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/call-function/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/call-function/TestCallCPPFunction.py b/packages/Python/lldbsuite/test/lang/cpp/call-function/TestCallCPPFunction.py
new file mode 100644
index 000000000000..3aa97af68819
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/call-function/TestCallCPPFunction.py
@@ -0,0 +1,33 @@
+"""
+Tests calling a function by basename
+"""
+
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class CallCPPFunctionTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ TestBase.setUp(self)
+ self.line = line_number('main.cpp', '// breakpoint')
+
+ @expectedFailureWindows("llvm.org/pr24489: Name lookup not working correctly on Windows")
+ def test_with_run_command(self):
+ """Test calling a function by basename"""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("process launch", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list",
+ STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped', 'stop reason = breakpoint'])
+
+ self.expect("expression -- a_function_to_call()",
+ startstr = "(int) $0 = 0")
diff --git a/packages/Python/lldbsuite/test/lang/cpp/call-function/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/call-function/main.cpp
new file mode 100644
index 000000000000..61a5e9d21abb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/call-function/main.cpp
@@ -0,0 +1,11 @@
+#include <stdio.h>
+
+int a_function_to_call()
+{
+ return 0;
+}
+
+int main()
+{
+ printf("%d\n", a_function_to_call()); // breakpoint
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/chained-calls/Makefile b/packages/Python/lldbsuite/test/lang/cpp/chained-calls/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/chained-calls/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/chained-calls/TestCppChainedCalls.py b/packages/Python/lldbsuite/test/lang/cpp/chained-calls/TestCppChainedCalls.py
new file mode 100644
index 000000000000..272665a78577
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/chained-calls/TestCppChainedCalls.py
@@ -0,0 +1,73 @@
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TestCppChainedCalls(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureWindows("llvm.org/pr21765")
+ def test_with_run_command(self):
+ self.build()
+
+ # Get main source file
+ src_file = "main.cpp"
+ src_file_spec = lldb.SBFileSpec(src_file)
+ self.assertTrue(src_file_spec.IsValid(), "Main source file")
+
+ # Get the path of the executable
+ cwd = os.getcwd()
+ exe_file = "a.out"
+ exe_path = os.path.join(cwd, exe_file)
+
+ # Load the executable
+ target = self.dbg.CreateTarget(exe_path)
+ self.assertTrue(target.IsValid(), VALID_TARGET)
+
+ # Break on main function
+ main_breakpoint = target.BreakpointCreateBySourceRegex("break here", src_file_spec)
+ self.assertTrue(main_breakpoint.IsValid() and main_breakpoint.GetNumLocations() >= 1, VALID_BREAKPOINT)
+
+ # Launch the process
+ args = None
+ env = None
+ process = target.LaunchSimple(args, env, self.get_process_working_directory())
+ self.assertTrue(process.IsValid(), PROCESS_IS_VALID)
+
+ # Get the thread of the process
+ self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+
+ # Get frame for current thread
+ frame = thread.GetSelectedFrame()
+
+ # Test chained calls
+ test_result = frame.EvaluateExpression("get(set(true))")
+ self.assertTrue(test_result.IsValid() and test_result.GetValue() == "true", "get(set(true)) = true")
+
+ test_result = frame.EvaluateExpression("get(set(false))")
+ self.assertTrue(test_result.IsValid() and test_result.GetValue() == "false", "get(set(false)) = false")
+
+ test_result = frame.EvaluateExpression("get(t & f)")
+ self.assertTrue(test_result.IsValid() and test_result.GetValue() == "false", "get(t & f) = false")
+
+ test_result = frame.EvaluateExpression("get(f & t)")
+ self.assertTrue(test_result.IsValid() and test_result.GetValue() == "false", "get(f & t) = false")
+
+ test_result = frame.EvaluateExpression("get(t & t)")
+ self.assertTrue(test_result.IsValid() and test_result.GetValue() == "true", "get(t & t) = true")
+
+ test_result = frame.EvaluateExpression("get(f & f)")
+ self.assertTrue(test_result.IsValid() and test_result.GetValue() == "false", "get(f & f) = false")
+
+ test_result = frame.EvaluateExpression("get(t & f)")
+ self.assertTrue(test_result.IsValid() and test_result.GetValue() == "false", "get(t & f) = false")
+
+ test_result = frame.EvaluateExpression("get(f) && get(t)")
+ self.assertTrue(test_result.IsValid() and test_result.GetValue() == "false", "get(f) && get(t) = false")
+
+ test_result = frame.EvaluateExpression("get(f) && get(f)")
+ self.assertTrue(test_result.IsValid() and test_result.GetValue() == "false", "get(f) && get(t) = false")
+
+ test_result = frame.EvaluateExpression("get(t) && get(t)")
+ self.assertTrue(test_result.IsValid() and test_result.GetValue() == "true", "get(t) && get(t) = true")
diff --git a/packages/Python/lldbsuite/test/lang/cpp/chained-calls/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/chained-calls/main.cpp
new file mode 100644
index 000000000000..a888c3f6c557
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/chained-calls/main.cpp
@@ -0,0 +1,33 @@
+class Bool {
+public:
+ Bool operator&(const Bool other)
+ {
+ Bool result;
+ result.value = value && other.value;
+ return result;
+ }
+
+ bool value;
+};
+
+bool get(Bool object)
+{
+ return object.value;
+}
+
+Bool set(bool value)
+{
+ Bool result;
+ result.value = value;
+ return result;
+}
+
+int main()
+{
+ Bool t = set(true);
+ Bool f = set(false);
+ get(t);
+ get(f);
+ get(t & f);
+ return 0; // break here
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/char1632_t/.categories b/packages/Python/lldbsuite/test/lang/cpp/char1632_t/.categories
new file mode 100644
index 000000000000..fe1da0247c62
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/char1632_t/.categories
@@ -0,0 +1 @@
+dataformatters
diff --git a/packages/Python/lldbsuite/test/lang/cpp/char1632_t/Makefile b/packages/Python/lldbsuite/test/lang/cpp/char1632_t/Makefile
new file mode 100644
index 000000000000..932046f26968
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/char1632_t/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+CFLAGS :=-g -O0 -std=c++11
+
+clean: OBJECTS+=$(wildcard main.d.*)
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/char1632_t/TestChar1632T.py b/packages/Python/lldbsuite/test/lang/cpp/char1632_t/TestChar1632T.py
new file mode 100644
index 000000000000..9bb1faf4ba6d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/char1632_t/TestChar1632T.py
@@ -0,0 +1,90 @@
+# coding=utf8
+"""
+Test that the C++11 support for char16_t and char32_t works correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class Char1632TestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break for main.cpp.
+ self.source = 'main.cpp'
+ self.lines = [ line_number(self.source, '// breakpoint1'),
+ line_number(self.source, '// breakpoint2') ]
+
+ @expectedFailureIcc # ICC (13.1) does not emit the DW_TAG_base_type for char16_t and char32_t.
+ @expectedFailureWindows("llvm.org/pr24489: Name lookup not working correctly on Windows")
+ def test(self):
+ """Test that the C++11 support for char16_t and char32_t works correctly."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Set breakpoints
+ for line in self.lines:
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", line)
+
+ # Now launch the process, and do not stop at entry point and stop at breakpoint1
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ if not process:
+ self.fail("SBTarget.Launch() failed")
+
+ if self.TraceOn():
+ self.runCmd("frame variable")
+
+ # Check that we correctly report the const types
+ self.expect("frame variable cs16 cs32",
+ substrs = ['(const char16_t *) cs16 = ','(const char32_t *) cs32 = ','u"hello world ྒྙྐ"','U"hello world ྒྙྐ"'])
+
+ # Check that we correctly report the non-const types
+ self.expect("frame variable s16 s32",
+ substrs = ['(char16_t *) s16 = ','(char32_t *) s32 = ','u"ﺸﺵۻ"','U"ЕЙРГЖО"'])
+
+ # Check that we correctly report the array types
+ self.expect("frame variable as16 as32",
+ patterns = ['\(char16_t \[[0-9]+\]\) as16 = ', '\(char32_t \[[0-9]+\]\) as32 = '],
+ substrs = ['u"ﺸﺵۻ"','U"ЕЙРГЖО"'])
+
+ self.runCmd("next") # step to after the string is nullified
+
+ # check that we don't crash on NULL
+ self.expect("frame variable s32",
+ substrs = ['(char32_t *) s32 = 0x00000000'])
+
+ # continue and hit breakpoint2
+ self.runCmd("continue")
+
+ # check that the new strings show
+ self.expect("frame variable s16 s32",
+ substrs = ['(char16_t *) s16 = 0x','(char32_t *) s32 = ','"色ハ匂ヘト散リヌルヲ"','"෴"'])
+
+ # check the same as above for arrays
+ self.expect("frame variable as16 as32",
+ patterns = ['\(char16_t \[[0-9]+\]\) as16 = ', '\(char32_t \[[0-9]+\]\) as32 = '],
+ substrs = ['"色ハ匂ヘト散リヌルヲ"','"෴"'])
+
+ # check that zero values are properly handles
+ self.expect('frame variable cs16_zero', substrs=["U+0000 u'\\0'"])
+ self.expect('frame variable cs32_zero', substrs=["U+0x00000000 U'\\0'"])
+ self.expect('expression cs16_zero', substrs=["U+0000 u'\\0'"])
+ self.expect('expression cs32_zero', substrs=["U+0x00000000 U'\\0'"])
+
+ # Check that we can run expressions that return charN_t
+ self.expect("expression u'a'",substrs = ['(char16_t) $',"61 u'a'"])
+ self.expect("expression U'a'",substrs = ['(char32_t) $',"61 U'a'"])
diff --git a/packages/Python/lldbsuite/test/lang/cpp/char1632_t/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/char1632_t/main.cpp
new file mode 100644
index 000000000000..b92c2d572923
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/char1632_t/main.cpp
@@ -0,0 +1,44 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <assert.h>
+#include <string>
+
+#define UASZ 64
+
+template<class T, int N>
+void copy_char_seq (T (&arr)[N], const T* src)
+{
+ size_t src_len = std::char_traits<T>::length(src);
+ assert(src_len < N);
+
+ std::char_traits<T>::copy(arr, src, src_len);
+ arr[src_len] = 0;
+}
+
+int main (int argc, char const *argv[])
+{
+ char16_t as16[UASZ];
+ char32_t as32[UASZ];
+ auto cs16_zero = (char16_t)0;
+ auto cs32_zero = (char32_t)0;
+ auto cs16 = u"hello world ྒྙྐ";
+ auto cs32 = U"hello world ྒྙྐ";
+ char16_t *s16 = (char16_t *)u"ﺸﺵۻ";
+ char32_t *s32 = (char32_t *)U"ЕЙРГЖО";
+ copy_char_seq(as16, s16);
+ copy_char_seq(as32, s32);
+ s32 = nullptr; // breakpoint1
+ s32 = (char32_t *)U"෴";
+ s16 = (char16_t *)u"色ハ匂ヘト散リヌルヲ";
+ copy_char_seq(as16, s16);
+ copy_char_seq(as32, s32);
+ s32 = nullptr; // breakpoint2
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/class_static/Makefile b/packages/Python/lldbsuite/test/lang/cpp/class_static/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/class_static/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/class_static/TestStaticVariables.py b/packages/Python/lldbsuite/test/lang/cpp/class_static/TestStaticVariables.py
new file mode 100644
index 000000000000..d47d1b7dde41
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/class_static/TestStaticVariables.py
@@ -0,0 +1,120 @@
+"""
+Test display and Python APIs on file and class static variables.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class StaticVariableTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ @expectedFailureWindows("llvm.org/pr24764")
+ def test_with_run_command(self):
+ """Test that file and class static variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # global variables are no longer displayed with the "frame variable" command.
+ self.expect('target variable A::g_points', VARIABLES_DISPLAYED_CORRECTLY,
+ patterns=['\(PointType \[[1-9]*\]\) A::g_points = {.*}'])
+ self.expect('target variable g_points', VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['(PointType [2]) g_points'])
+
+ # On Mac OS X, gcc 4.2 emits the wrong debug info for A::g_points.
+ # A::g_points is an array of two elements.
+ if self.platformIsDarwin() or self.getPlatform() == "linux":
+ self.expect("target variable A::g_points[1].x", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = "(int) A::g_points[1].x = 11")
+
+ @expectedFailureDarwin(9980907)
+ @expectedFailureClang('Clang emits incomplete debug info.')
+ @expectedFailureFreeBSD('llvm.org/pr20550 failing on FreeBSD-11')
+ @expectedFailureGcc('GCC emits incomplete debug info.')
+ @add_test_categories(['pyapi'])
+ def test_with_python_api(self):
+ """Test Python APIs on file and class static variables."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ thread = process.GetThreadAtIndex(0)
+ if thread.GetStopReason() != lldb.eStopReasonBreakpoint:
+ from lldbsuite.test.lldbutil import stop_reason_to_str
+ self.fail(STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS %
+ stop_reason_to_str(thread.GetStopReason()))
+
+ # Get the SBValue of 'A::g_points' and 'g_points'.
+ frame = thread.GetFrameAtIndex(0)
+
+ # arguments => False
+ # locals => False
+ # statics => True
+ # in_scope_only => False
+ valList = frame.GetVariables(False, False, True, False)
+
+ for val in valList:
+ self.DebugSBValue(val)
+ name = val.GetName()
+ self.assertTrue(name in ['g_points', 'A::g_points'])
+ if name == 'g_points':
+ self.assertTrue(val.GetValueType() == lldb.eValueTypeVariableStatic)
+ self.assertTrue(val.GetNumChildren() == 2)
+ elif name == 'A::g_points':
+ self.assertTrue(val.GetValueType() == lldb.eValueTypeVariableGlobal)
+ self.assertTrue(val.GetNumChildren() == 2)
+ child1 = val.GetChildAtIndex(1)
+ self.DebugSBValue(child1)
+ child1_x = child1.GetChildAtIndex(0)
+ self.DebugSBValue(child1_x)
+ self.assertTrue(child1_x.GetTypeName() == 'int' and
+ child1_x.GetValue() == '11')
+
+ # SBFrame.FindValue() should also work.
+ val = frame.FindValue("A::g_points", lldb.eValueTypeVariableGlobal)
+ self.DebugSBValue(val)
+ self.assertTrue(val.GetName() == 'A::g_points')
+
+ # Also exercise the "parameter" and "local" scopes while we are at it.
+ val = frame.FindValue("argc", lldb.eValueTypeVariableArgument)
+ self.DebugSBValue(val)
+ self.assertTrue(val.GetName() == 'argc')
+
+ val = frame.FindValue("argv", lldb.eValueTypeVariableArgument)
+ self.DebugSBValue(val)
+ self.assertTrue(val.GetName() == 'argv')
+
+ val = frame.FindValue("hello_world", lldb.eValueTypeVariableLocal)
+ self.DebugSBValue(val)
+ self.assertTrue(val.GetName() == 'hello_world')
diff --git a/packages/Python/lldbsuite/test/lang/cpp/class_static/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/class_static/main.cpp
new file mode 100644
index 000000000000..2068eadcac5f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/class_static/main.cpp
@@ -0,0 +1,53 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+// I made this example after noting that I was unable to display an unsized
+// static class array. It turns out that gcc 4.2 will emit DWARF that correctly
+// describes the PointType, but it will incorrectly emit debug info for the
+// "g_points" array where the following things are wrong:
+// - the DW_TAG_array_type won't have a subrange info
+// - the DW_TAG_variable for "g_points" won't have a valid byte size, so even
+// though we know the size of PointType, we can't infer the actual size
+// of the array by dividing the size of the variable by the number of
+// elements.
+
+#include <stdio.h>
+
+typedef struct PointType
+{
+ int x, y;
+} PointType;
+
+class A
+{
+public:
+ static PointType g_points[];
+};
+
+PointType A::g_points[] =
+{
+ { 1, 2 },
+ { 11, 22 }
+};
+
+static PointType g_points[] =
+{
+ { 3, 4 },
+ { 33, 44 }
+};
+
+int
+main (int argc, char const *argv[])
+{
+ const char *hello_world = "Hello, world!";
+ printf ("A::g_points[1].x = %i\n", A::g_points[1].x); // Set break point at this line.
+ printf ("::g_points[1].x = %i\n", g_points[1].x);
+ printf ("%s\n", hello_world);
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/class_types/Makefile b/packages/Python/lldbsuite/test/lang/cpp/class_types/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/class_types/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypes.py b/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypes.py
new file mode 100644
index 000000000000..b67e53c30745
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypes.py
@@ -0,0 +1,215 @@
+"""Test breakpoint on a class constructor; and variable list the this object."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ClassTypesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break for main.cpp.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def test_with_run_command(self):
+ """Test 'frame variable this' when stopped on a class constructor."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break on the ctor function of class C.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The test suite sometimes shows that the process has exited without stopping.
+ #
+ # CC=clang ./dotest.py -v -t class_types
+ # ...
+ # Process 76604 exited with status = 0 (0x00000000)
+ self.runCmd("process status")
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ # We should be stopped on the ctor function of class C.
+ self.expect("frame variable --show-types this", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['C *',
+ ' this = '])
+
+ @add_test_categories(['pyapi'])
+ def test_with_python_api(self):
+ """Use Python APIs to create a breakpoint by (filespec, line)."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ filespec = target.GetExecutable()
+ self.assertTrue(filespec, VALID_FILESPEC)
+
+ fsDir = os.path.normpath(filespec.GetDirectory())
+ fsFile = filespec.GetFilename()
+
+ self.assertTrue(fsDir == os.getcwd() and fsFile == "a.out",
+ "FileSpec matches the executable")
+
+ bpfilespec = lldb.SBFileSpec("main.cpp", False)
+
+ breakpoint = target.BreakpointCreateByLocation(bpfilespec, self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Verify the breakpoint just created.
+ self.expect(str(breakpoint), BREAKPOINT_CREATED, exe=False,
+ substrs = ['main.cpp',
+ str(self.line)])
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ if not process:
+ self.fail("SBTarget.Launch() failed")
+
+ if process.GetState() != lldb.eStateStopped:
+ self.fail("Process should be in the 'stopped' state, "
+ "instead the actual state is: '%s'" %
+ lldbutil.state_type_to_str(process.GetState()))
+
+ # The stop reason of the thread should be breakpoint.
+ thread = process.GetThreadAtIndex(0)
+ if thread.GetStopReason() != lldb.eStopReasonBreakpoint:
+ from lldbsuite.test.lldbutil import stop_reason_to_str
+ self.fail(STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS %
+ stop_reason_to_str(thread.GetStopReason()))
+
+ # The filename of frame #0 should be 'main.cpp' and the line number
+ # should be 93.
+ self.expect("%s:%d" % (lldbutil.get_filenames(thread)[0],
+ lldbutil.get_line_numbers(thread)[0]),
+ "Break correctly at main.cpp:%d" % self.line, exe=False,
+ startstr = "main.cpp:")
+ ### clang compiled code reported main.cpp:94?
+ ### startstr = "main.cpp:93")
+
+ # We should be stopped on the breakpoint with a hit count of 1.
+ self.assertTrue(breakpoint.GetHitCount() == 1, BREAKPOINT_HIT_ONCE)
+
+ process.Continue()
+
+ def test_with_expr_parser(self):
+ """Test 'frame variable this' and 'expr this' when stopped inside a constructor."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # rdar://problem/8516141
+ # Is this a case of clang (116.1) generating bad debug info?
+ #
+ # Break on the ctor function of class C.
+ #self.expect("breakpoint set -M C", BREAKPOINT_CREATED,
+ # startstr = "Breakpoint created: 1: name = 'C'")
+
+ # Make the test case more robust by using line number to break, instead.
+ lldbutil.run_break_set_by_file_and_line (self, None, self.line, num_expected_locations=-1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ # Continue on inside the ctor() body...
+ self.runCmd("register read pc")
+ self.runCmd("thread step-over")
+
+ # Verify that 'frame variable this' gets the data type correct.
+ self.expect("frame variable this",VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['C *'])
+
+ # Verify that frame variable --show-types this->m_c_int behaves correctly.
+ self.runCmd("register read pc")
+ self.runCmd("expr m_c_int")
+ self.expect("frame variable --show-types this->m_c_int", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = '(int) this->m_c_int = 66')
+
+ # Verify that 'expression this' gets the data type correct.
+ self.expect("expression this", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ['C *'])
+
+ # rdar://problem/8430916
+ # expr this->m_c_int returns an incorrect value
+ #
+ # Verify that expr this->m_c_int behaves correctly.
+ self.expect("expression this->m_c_int", VARIABLES_DISPLAYED_CORRECTLY,
+ patterns = ['\(int\) \$[0-9]+ = 66'])
+
+ def test_with_constructor_name (self):
+ """Test 'frame variable this' and 'expr this' when stopped inside a constructor."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ filespec = target.GetExecutable()
+ self.assertTrue(filespec, VALID_FILESPEC)
+
+ fsDir = os.path.normpath(filespec.GetDirectory())
+ fsFile = filespec.GetFilename()
+
+ self.assertTrue(fsDir == os.getcwd() and fsFile == "a.out",
+ "FileSpec matches the executable")
+
+ bpfilespec = lldb.SBFileSpec("main.cpp", False)
+
+ breakpoint = target.BreakpointCreateByLocation(bpfilespec, self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Verify the breakpoint just created.
+ self.expect(str(breakpoint), BREAKPOINT_CREATED, exe=False,
+ substrs = ['main.cpp',
+ str(self.line)])
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ if not process:
+ self.fail("SBTarget.Launch() failed")
+
+ if process.GetState() != lldb.eStateStopped:
+ self.fail("Process should be in the 'stopped' state, "
+ "instead the actual state is: '%s'" %
+ lldbutil.state_type_to_str(process.GetState()))
+
+ # The stop reason of the thread should be breakpoint.
+ thread = process.GetThreadAtIndex(0)
+ if thread.GetStopReason() != lldb.eStopReasonBreakpoint:
+ from lldbsuite.test.lldbutil import stop_reason_to_str
+ self.fail(STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS %
+ stop_reason_to_str(thread.GetStopReason()))
+
+ frame = thread.frames[0]
+ self.assertTrue (frame.IsValid(), "Got a valid frame.")
+
+ self.assertTrue ("C::C" in frame.name, "Constructor name includes class name.")
diff --git a/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypesDisassembly.py b/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypesDisassembly.py
new file mode 100644
index 000000000000..595d075d5180
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/class_types/TestClassTypesDisassembly.py
@@ -0,0 +1,94 @@
+"""
+Test the lldb disassemble command on each call frame when stopped on C's ctor.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class IterateFrameAndDisassembleTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test_and_run_command(self):
+ """Disassemble each call frame when stopped on C's constructor."""
+ self.build()
+ self.breakOnCtor()
+
+ raw_output = self.res.GetOutput()
+ frameRE = re.compile(r"""
+ ^\s\sframe # heading for the frame info,
+ .* # wildcard, and
+ 0x[0-9a-f]{16} # the frame pc, and
+ \sa.out`(.+) # module`function, and
+ \s\+\s # the rest ' + ....'
+ """, re.VERBOSE)
+ for line in raw_output.split(os.linesep):
+ match = frameRE.search(line)
+ if match:
+ function = match.group(1)
+ #print("line:", line)
+ #print("function:", function)
+ self.runCmd("disassemble -n '%s'" % function)
+
+ @add_test_categories(['pyapi'])
+ def test_and_python_api(self):
+ """Disassemble each call frame when stopped on C's constructor."""
+ self.build()
+ self.breakOnCtor()
+
+ # Now use the Python API to get at each function on the call stack and
+ # disassemble it.
+ target = self.dbg.GetSelectedTarget()
+ process = target.GetProcess()
+ thread = process.GetThreadAtIndex(0)
+ depth = thread.GetNumFrames()
+ for i in range(depth - 1):
+ frame = thread.GetFrameAtIndex(i)
+ function = frame.GetFunction()
+ # Print the function header.
+ if self.TraceOn():
+ print()
+ print(function)
+ if function:
+ # Get all instructions for this function and print them out.
+ insts = function.GetInstructions(target)
+ for inst in insts:
+ # We could simply do 'print inst' to print out the disassembly.
+ # But we want to print to stdout only if self.TraceOn() is True.
+ disasm = str(inst)
+ if self.TraceOn():
+ print(disasm)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break for main.cpp.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def breakOnCtor(self):
+ """Setup/run the program so it stops on C's constructor."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break on the ctor function of class C.
+ bpno = lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint %d.'%(bpno)])
+
+ # This test was failing because we fail to put the C:: in front of constructore.
+ # We should maybe make another testcase to cover that specifically, but we shouldn't
+ # fail this whole testcase for an inessential issue.
+ # We should be stopped on the ctor function of class C.
+ # self.expect("thread backtrace", BACKTRACE_DISPLAYED_CORRECTLY,
+ # substrs = ['C::C'])
diff --git a/packages/Python/lldbsuite/test/lang/cpp/class_types/cmds.txt b/packages/Python/lldbsuite/test/lang/cpp/class_types/cmds.txt
new file mode 100644
index 000000000000..1c7ef9f1c8ad
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/class_types/cmds.txt
@@ -0,0 +1,3 @@
+b main.cpp:97
+c
+var
diff --git a/packages/Python/lldbsuite/test/lang/cpp/class_types/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/class_types/main.cpp
new file mode 100644
index 000000000000..251e66c3c9f7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/class_types/main.cpp
@@ -0,0 +1,126 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+class Conversion
+{
+public:
+ Conversion (int i) :
+ m_i (i)
+ {}
+
+ operator bool()
+ {
+ return m_i != 0;
+ }
+
+private:
+ int m_i;
+};
+
+class A
+{
+public:
+ A(int i=0):
+ m_a_int(i),
+ m_aa_int(i+1)
+ {
+ }
+
+ //virtual
+ ~A()
+ {
+ }
+
+ int
+ GetInteger() const
+ {
+ return m_a_int;
+ }
+ void
+ SetInteger(int i)
+ {
+ m_a_int = i;
+ }
+
+protected:
+ int m_a_int;
+ int m_aa_int;
+};
+
+class B : public A
+{
+public:
+ B(int ai, int bi) :
+ A(ai),
+ m_b_int(bi)
+ {
+ }
+
+ //virtual
+ ~B()
+ {
+ }
+
+ int
+ GetIntegerB() const
+ {
+ return m_b_int;
+ }
+ void
+ SetIntegerB(int i)
+ {
+ m_b_int = i;
+ }
+
+protected:
+ int m_b_int;
+};
+
+#include <cstdio>
+class C : public B
+{
+public:
+ C(int ai, int bi, int ci) :
+ B(ai, bi),
+ m_c_int(ci)
+ {
+ printf("Within C::ctor() m_c_int=%d\n", m_c_int); // Set break point at this line.
+ }
+
+ //virtual
+ ~C()
+ {
+ }
+
+ int
+ GetIntegerC() const
+ {
+ return m_c_int;
+ }
+ void
+ SetIntegerC(int i)
+ {
+ m_c_int = i;
+ }
+
+protected:
+ int m_c_int;
+};
+
+int
+main (int argc, char const *argv[])
+{
+ A a(12);
+ B b(22,33);
+ C c(44,55,66);
+ Conversion conv(1);
+ if (conv)
+ return b.GetIntegerB() - a.GetInteger() + c.GetInteger();
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/diamond/Makefile b/packages/Python/lldbsuite/test/lang/cpp/diamond/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/diamond/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/diamond/TestDiamond.py b/packages/Python/lldbsuite/test/lang/cpp/diamond/TestDiamond.py
new file mode 100644
index 000000000000..67de03b54b20
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/diamond/TestDiamond.py
@@ -0,0 +1,41 @@
+"""
+Tests that bool types work
+"""
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class CPPTestDiamondInheritance(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test_with_run_command(self):
+ """Test that virtual base classes work in when SBValue objects are used to explore the variable value"""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+ self.set_breakpoint(line_number('main.cpp', '// breakpoint 1'))
+ self.set_breakpoint(line_number('main.cpp', '// breakpoint 2'))
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+ thread = process.GetThreadAtIndex(0)
+ frame = thread.GetFrameAtIndex(0)
+ j1 = frame.FindVariable("j1")
+ j1_Derived1 = j1.GetChildAtIndex(0)
+ j1_Derived2 = j1.GetChildAtIndex(1)
+ j1_Derived1_VBase = j1_Derived1.GetChildAtIndex(0)
+ j1_Derived2_VBase = j1_Derived2.GetChildAtIndex(0)
+ j1_Derived1_VBase_m_value = j1_Derived1_VBase.GetChildAtIndex(0)
+ j1_Derived2_VBase_m_value = j1_Derived2_VBase.GetChildAtIndex(0)
+ self.assertTrue(j1_Derived1_VBase.GetLoadAddress() == j1_Derived2_VBase.GetLoadAddress(), "ensure virtual base class is the same between Derived1 and Derived2")
+ self.assertTrue(j1_Derived1_VBase_m_value.GetValueAsUnsigned(1) == j1_Derived2_VBase_m_value.GetValueAsUnsigned(2), "ensure m_value in VBase is the same")
+ self.assertTrue(frame.FindVariable("d").GetChildAtIndex(0).GetChildAtIndex(0).GetValueAsUnsigned(0) == 12345, "ensure Derived2 from j1 is correct");
+ thread.StepOver()
+ self.assertTrue(frame.FindVariable("d").GetChildAtIndex(0).GetChildAtIndex(0).GetValueAsUnsigned(0) == 12346, "ensure Derived2 from j2 is correct");
+
+ def set_breakpoint(self, line):
+ # Some compilers (for example GCC 4.4.7 and 4.6.1) emit multiple locations for the statement with the ternary
+ # operator in the test program, while others emit only 1.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", line, num_expected_locations=-1, loc_exact=False)
diff --git a/packages/Python/lldbsuite/test/lang/cpp/diamond/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/diamond/main.cpp
new file mode 100644
index 000000000000..bfe098a089f5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/diamond/main.cpp
@@ -0,0 +1,85 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+static int g_next_value = 12345;
+
+class VBase
+{
+public:
+ VBase() : m_value(g_next_value++) {}
+ virtual ~VBase() {}
+ void Print()
+ {
+ printf("%p: %s\n%p: m_value = 0x%8.8x\n", this, __PRETTY_FUNCTION__, &m_value, m_value);
+ }
+ int m_value;
+};
+
+class Derived1 : public virtual VBase
+{
+public:
+ Derived1() {};
+ void Print ()
+ {
+ printf("%p: %s\n", this, __PRETTY_FUNCTION__);
+ VBase::Print();
+ }
+
+};
+
+class Derived2 : public virtual VBase
+{
+public:
+ Derived2() {};
+
+ void Print ()
+ {
+ printf("%p: %s\n", this, __PRETTY_FUNCTION__);
+ VBase::Print();
+ }
+};
+
+class Joiner1 : public Derived1, public Derived2
+{
+public:
+ Joiner1() :
+ m_joiner1(3456),
+ m_joiner2(6789) {}
+ void Print ()
+ {
+ printf("%p: %s \n%p: m_joiner1 = 0x%8.8x\n%p: m_joiner2 = 0x%8.8x\n",
+ this,
+ __PRETTY_FUNCTION__,
+ &m_joiner1,
+ m_joiner1,
+ &m_joiner2,
+ m_joiner2);
+ Derived1::Print();
+ Derived2::Print();
+ }
+ int m_joiner1;
+ int m_joiner2;
+};
+
+class Joiner2 : public Derived2
+{
+ int m_stuff[32];
+};
+
+int main(int argc, const char * argv[])
+{
+ Joiner1 j1;
+ Joiner2 j2;
+ j1.Print();
+ j2.Print();
+ Derived2 *d = &j1;
+ d = &j2; // breakpoint 1
+ return 0; // breakpoint 2
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/Makefile b/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/Makefile
new file mode 100644
index 000000000000..8770b2343ef0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := pass-to-base.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestCppValueCast.py b/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestCppValueCast.py
new file mode 100644
index 000000000000..4e23cd899285
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestCppValueCast.py
@@ -0,0 +1,129 @@
+"""
+Test lldb Python API SBValue::Cast(SBType) for C++ types.
+"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class CppValueCastTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @unittest2.expectedFailure("rdar://problem/10808472 SBValue::Cast test case is failing (virtual inheritance)")
+ @add_test_categories(['pyapi'])
+ def test_value_cast_with_virtual_inheritance(self):
+ """Test SBValue::Cast(SBType) API for C++ types with virtual inheritance."""
+ self.build(dictionary=self.d_virtual)
+ self.setTearDownCleanup(dictionary=self.d_virtual)
+ self.do_sbvalue_cast(self.exe_name)
+
+ @add_test_categories(['pyapi'])
+ def test_value_cast_with_regular_inheritance(self):
+ """Test SBValue::Cast(SBType) API for C++ types with regular inheritance."""
+ self.build(dictionary=self.d_regular)
+ self.setTearDownCleanup(dictionary=self.d_regular)
+ self.do_sbvalue_cast(self.exe_name)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+
+ # Find the line number to break for main.c.
+ self.source = 'sbvalue-cast.cpp';
+ self.line = line_number(self.source, '// Set breakpoint here.')
+ self.exe_name = self.testMethodName
+ self.d_virtual = {'CXX_SOURCES': self.source, 'EXE': self.exe_name, 'CFLAGS_EXTRAS': '-DDO_VIRTUAL_INHERITANCE'}
+ self.d_regular = {'CXX_SOURCES': self.source, 'EXE': self.exe_name}
+
+ def do_sbvalue_cast (self, exe_name):
+ """Test SBValue::Cast(SBType) API for C++ types."""
+ exe = os.path.join(os.getcwd(), exe_name)
+
+ # Create a target from the debugger.
+
+ target = self.dbg.CreateTarget (exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Set up our breakpoints:
+
+ breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+
+ # Find DerivedA and DerivedB types.
+ typeA = target.FindFirstType('DerivedA')
+ typeB = target.FindFirstType('DerivedB')
+ self.DebugSBType(typeA)
+ self.DebugSBType(typeB)
+ self.assertTrue(typeA)
+ self.assertTrue(typeB)
+ error = lldb.SBError()
+
+ # First stop is for DerivedA instance.
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint)
+ self.assertTrue (len(threads) == 1)
+ thread = threads[0]
+ frame0 = thread.GetFrameAtIndex(0)
+
+ tellerA = frame0.FindVariable('teller', lldb.eNoDynamicValues)
+ self.DebugSBValue(tellerA)
+ self.assertTrue(tellerA.GetChildMemberWithName('m_base_val').GetValueAsUnsigned(error, 0) == 20)
+
+ if self.TraceOn():
+ for child in tellerA:
+ print("child name:", child.GetName())
+ print(child)
+
+ # Call SBValue.Cast() to obtain instanceA.
+ instanceA = tellerA.Cast(typeA.GetPointerType())
+ self.DebugSBValue(instanceA)
+
+ # Iterate through all the children and print their values.
+ if self.TraceOn():
+ for child in instanceA:
+ print("child name:", child.GetName())
+ print(child)
+ a_member_val = instanceA.GetChildMemberWithName('m_a_val')
+ self.DebugSBValue(a_member_val)
+ self.assertTrue(a_member_val.GetValueAsUnsigned(error, 0) == 10)
+
+ # Second stop is for DerivedB instance.
+ threads = lldbutil.continue_to_breakpoint (process, breakpoint)
+ self.assertTrue (len(threads) == 1)
+ thread = threads[0]
+ frame0 = thread.GetFrameAtIndex(0)
+
+ tellerB = frame0.FindVariable('teller', lldb.eNoDynamicValues)
+ self.DebugSBValue(tellerB)
+ self.assertTrue(tellerB.GetChildMemberWithName('m_base_val').GetValueAsUnsigned(error, 0) == 12)
+
+ if self.TraceOn():
+ for child in tellerB:
+ print("child name:", child.GetName())
+ print(child)
+
+ # Call SBValue.Cast() to obtain instanceB.
+ instanceB = tellerB.Cast(typeB.GetPointerType())
+ self.DebugSBValue(instanceB)
+
+ # Iterate through all the children and print their values.
+ if self.TraceOn():
+ for child in instanceB:
+ print("child name:", child.GetName())
+ print(child)
+ b_member_val = instanceB.GetChildMemberWithName('m_b_val')
+ self.DebugSBValue(b_member_val)
+ self.assertTrue(b_member_val.GetValueAsUnsigned(error, 0) == 36)
diff --git a/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestDynamicValue.py b/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestDynamicValue.py
new file mode 100644
index 000000000000..56e81c56cfa6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/TestDynamicValue.py
@@ -0,0 +1,223 @@
+"""
+Use lldb Python API to test dynamic values in C++
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class DynamicValueTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+
+ # Find the line number to break for main.c.
+
+ self.do_something_line = line_number('pass-to-base.cpp', '// Break here in doSomething.')
+ self.main_first_call_line = line_number('pass-to-base.cpp',
+ '// Break here and get real addresses of myB and otherB.')
+ self.main_second_call_line = line_number('pass-to-base.cpp',
+ '// Break here and get real address of reallyA.')
+
+ @expectedFailureFreeBSD # FIXME: This needs to be root-caused.
+ @expectedFailureWindows("llvm.org/pr24663")
+ @add_test_categories(['pyapi'])
+ def test_get_dynamic_vals(self):
+ """Test fetching C++ dynamic values from pointers & references."""
+ self.build(dictionary=self.getBuildFlags())
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target from the debugger.
+
+ target = self.dbg.CreateTarget (exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Set up our breakpoints:
+
+ do_something_bpt = target.BreakpointCreateByLocation('pass-to-base.cpp', self.do_something_line)
+ self.assertTrue(do_something_bpt,
+ VALID_BREAKPOINT)
+
+ first_call_bpt = target.BreakpointCreateByLocation('pass-to-base.cpp', self.main_first_call_line)
+ self.assertTrue(first_call_bpt,
+ VALID_BREAKPOINT)
+
+ second_call_bpt = target.BreakpointCreateByLocation('pass-to-base.cpp', self.main_second_call_line)
+ self.assertTrue(second_call_bpt,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, first_call_bpt)
+ self.assertTrue (len(threads) == 1)
+ thread = threads[0]
+
+ frame = thread.GetFrameAtIndex(0)
+
+ # Now find the dynamic addresses of myB and otherB so we can compare them
+ # with the dynamic values we get in doSomething:
+
+ use_dynamic = lldb.eDynamicCanRunTarget
+ no_dynamic = lldb.eNoDynamicValues
+
+ myB = frame.FindVariable ('myB', no_dynamic);
+ self.assertTrue (myB)
+ myB_loc = int (myB.GetLocation(), 16)
+
+ otherB = frame.FindVariable('otherB', no_dynamic)
+ self.assertTrue (otherB)
+ otherB_loc = int (otherB.GetLocation(), 16)
+
+ # Okay now run to doSomething:
+
+ threads = lldbutil.continue_to_breakpoint (process, do_something_bpt)
+ self.assertTrue (len(threads) == 1)
+ thread = threads[0]
+
+ frame = thread.GetFrameAtIndex(0)
+
+ # Get "this" using FindVariable:
+
+ this_static = frame.FindVariable ('this', no_dynamic)
+ this_dynamic = frame.FindVariable ('this', use_dynamic)
+ self.examine_value_object_of_this_ptr (this_static, this_dynamic, myB_loc)
+
+ # Now make sure that the "GetDynamicValue" works:
+ # This doesn't work currently because we can't get dynamic values from ConstResult objects.
+ fetched_dynamic_value = this_static.GetDynamicValue(use_dynamic)
+ self.examine_value_object_of_this_ptr (this_static, fetched_dynamic_value, myB_loc)
+
+ # And conversely that the GetDynamicValue() interface also works:
+ fetched_static_value = this_dynamic.GetStaticValue()
+ self.examine_value_object_of_this_ptr (fetched_static_value, this_dynamic, myB_loc)
+
+ # Get "this" using FindValue, make sure that works too:
+ this_static = frame.FindValue ('this', lldb.eValueTypeVariableArgument, no_dynamic)
+ this_dynamic = frame.FindValue ('this', lldb.eValueTypeVariableArgument, use_dynamic)
+ self.examine_value_object_of_this_ptr (this_static, this_dynamic, myB_loc)
+
+ # Get "this" using the EvaluateExpression:
+ this_static = frame.EvaluateExpression ('this', False)
+ this_dynamic = frame.EvaluateExpression ('this', True)
+ self.examine_value_object_of_this_ptr (this_static, this_dynamic, myB_loc)
+
+ # The "frame var" code uses another path to get into children, so let's
+ # make sure that works as well:
+
+ self.expect('frame var -d run-target --ptr-depth=2 --show-types anotherA.m_client_A', 'frame var finds its way into a child member',
+ patterns = ['\(B \*\)'])
+
+ # Now make sure we also get it right for a reference as well:
+
+ anotherA_static = frame.FindVariable ('anotherA', False)
+ self.assertTrue (anotherA_static)
+ anotherA_static_addr = int (anotherA_static.GetValue(), 16)
+
+ anotherA_dynamic = frame.FindVariable ('anotherA', True)
+ self.assertTrue (anotherA_dynamic)
+ anotherA_dynamic_addr = int (anotherA_dynamic.GetValue(), 16)
+ anotherA_dynamic_typename = anotherA_dynamic.GetTypeName()
+ self.assertTrue (anotherA_dynamic_typename.find('B') != -1)
+
+ self.assertTrue(anotherA_dynamic_addr < anotherA_static_addr)
+
+ anotherA_m_b_value_dynamic = anotherA_dynamic.GetChildMemberWithName('m_b_value', True)
+ self.assertTrue (anotherA_m_b_value_dynamic)
+ anotherA_m_b_val = int (anotherA_m_b_value_dynamic.GetValue(), 10)
+ self.assertTrue (anotherA_m_b_val == 300)
+
+ anotherA_m_b_value_static = anotherA_static.GetChildMemberWithName('m_b_value', True)
+ self.assertFalse (anotherA_m_b_value_static)
+
+ # Okay, now continue again, and when we hit the second breakpoint in main
+
+ threads = lldbutil.continue_to_breakpoint (process, second_call_bpt)
+ self.assertTrue (len(threads) == 1)
+ thread = threads[0]
+
+ frame = thread.GetFrameAtIndex(0)
+ reallyA_value = frame.FindVariable ('reallyA', False)
+ self.assertTrue(reallyA_value)
+ reallyA_loc = int (reallyA_value.GetLocation(), 16)
+
+ # Finally continue to doSomething again, and make sure we get the right value for anotherA,
+ # which this time around is just an "A".
+
+ threads = lldbutil.continue_to_breakpoint (process, do_something_bpt)
+ self.assertTrue(len(threads) == 1)
+ thread = threads[0]
+
+ frame = thread.GetFrameAtIndex(0)
+ anotherA_value = frame.FindVariable ('anotherA', True)
+ self.assertTrue(anotherA_value)
+ anotherA_loc = int (anotherA_value.GetValue(), 16)
+ self.assertTrue (anotherA_loc == reallyA_loc)
+ self.assertTrue (anotherA_value.GetTypeName().find ('B') == -1)
+
+ def examine_value_object_of_this_ptr (self, this_static, this_dynamic, dynamic_location):
+ # Get "this" as its static value
+ self.assertTrue (this_static)
+ this_static_loc = int (this_static.GetValue(), 16)
+
+ # Get "this" as its dynamic value
+
+ self.assertTrue (this_dynamic)
+ this_dynamic_typename = this_dynamic.GetTypeName()
+ self.assertTrue (this_dynamic_typename.find('B') != -1)
+ this_dynamic_loc = int (this_dynamic.GetValue(), 16)
+
+ # Make sure we got the right address for "this"
+
+ self.assertTrue (this_dynamic_loc == dynamic_location)
+
+ # And that the static address is greater than the dynamic one
+
+ self.assertTrue (this_static_loc > this_dynamic_loc)
+
+ # Now read m_b_value which is only in the dynamic value:
+
+ use_dynamic = lldb.eDynamicCanRunTarget
+ no_dynamic = lldb.eNoDynamicValues
+
+ this_dynamic_m_b_value = this_dynamic.GetChildMemberWithName('m_b_value', use_dynamic)
+ self.assertTrue (this_dynamic_m_b_value)
+
+ m_b_value = int (this_dynamic_m_b_value.GetValue(), 0)
+ self.assertTrue (m_b_value == 10)
+
+ # Make sure it is not in the static version
+
+ this_static_m_b_value = this_static.GetChildMemberWithName('m_b_value', no_dynamic)
+ self.assertFalse (this_static_m_b_value)
+
+ # Okay, now let's make sure that we can get the dynamic type of a child element:
+
+ contained_auto_ptr = this_dynamic.GetChildMemberWithName ('m_client_A', use_dynamic)
+ self.assertTrue (contained_auto_ptr)
+ contained_b = contained_auto_ptr.GetChildMemberWithName ('_M_ptr', use_dynamic)
+ if not contained_b:
+ contained_b = contained_auto_ptr.GetChildMemberWithName ('__ptr_', use_dynamic)
+ self.assertTrue (contained_b)
+
+ contained_b_static = contained_auto_ptr.GetChildMemberWithName ('_M_ptr', no_dynamic)
+ if not contained_b_static:
+ contained_b_static = contained_auto_ptr.GetChildMemberWithName ('__ptr_', no_dynamic)
+ self.assertTrue (contained_b_static)
+
+ contained_b_addr = int (contained_b.GetValue(), 16)
+ contained_b_static_addr = int (contained_b_static.GetValue(), 16)
+
+ self.assertTrue (contained_b_addr < contained_b_static_addr)
diff --git a/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/pass-to-base.cpp b/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/pass-to-base.cpp
new file mode 100644
index 000000000000..2bccf3303823
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/pass-to-base.cpp
@@ -0,0 +1,69 @@
+#include <stdio.h>
+#include <memory>
+
+class Extra
+{
+public:
+ Extra (int in_one, int in_two) : m_extra_one(in_one), m_extra_two(in_two) {}
+
+private:
+ int m_extra_one;
+ int m_extra_two;
+};
+
+class A
+{
+public:
+ A(int value) : m_a_value (value) {}
+ A(int value, A* client_A) : m_a_value (value), m_client_A (client_A) {}
+
+ virtual ~A() {}
+
+ virtual void
+ doSomething (A &anotherA)
+ {
+ printf ("In A %p doing something with %d.\n", this, m_a_value);
+ int tmp_value = anotherA.Value();
+ printf ("Also have another A at %p: %d.\n", &anotherA, tmp_value); // Break here in doSomething.
+ }
+
+ int
+ Value()
+ {
+ return m_a_value;
+ }
+
+private:
+ int m_a_value;
+ std::auto_ptr<A> m_client_A;
+};
+
+class B : public Extra, public virtual A
+{
+public:
+ B (int b_value, int a_value) : Extra(b_value, a_value), A(a_value), m_b_value(b_value) {}
+ B (int b_value, int a_value, A *client_A) : Extra(b_value, a_value), A(a_value, client_A), m_b_value(b_value) {}
+
+ virtual ~B () {}
+
+private:
+ int m_b_value;
+};
+
+static A* my_global_A_ptr;
+
+int
+main (int argc, char **argv)
+{
+ my_global_A_ptr = new B (100, 200);
+ B myB (10, 20, my_global_A_ptr);
+ B *second_fake_A_ptr = new B (150, 250);
+ B otherB (300, 400, second_fake_A_ptr);
+
+ myB.doSomething(otherB); // Break here and get real addresses of myB and otherB.
+
+ A reallyA (500);
+ myB.doSomething (reallyA); // Break here and get real address of reallyA.
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/sbvalue-cast.cpp b/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/sbvalue-cast.cpp
new file mode 100644
index 000000000000..00fd7dad438c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/dynamic-value/sbvalue-cast.cpp
@@ -0,0 +1,80 @@
+//===-- sbvalue-cast.cpp ----------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#ifdef DO_VIRTUAL_INHERITANCE
+#define VIRTUAL virtual
+#else
+#define VIRTUAL
+#endif
+
+#include <stdio.h>
+
+class Base
+{
+public:
+ Base(int val) : m_base_val (val) {}
+ virtual ~Base() {}
+
+ virtual void
+ forcast(int input) {
+ int future_val = m_base_val + input * 1;
+ printf("Forcasting %d\n", future_val);
+ }
+
+protected:
+ int m_base_val;
+};
+
+class DerivedA : public VIRTUAL Base
+{
+public:
+ DerivedA(int val) : Base(val*2), m_a_val(val) {
+ printf("DerivedA::ctor()->\n");
+ printf("m_base_val=%d\n", m_base_val);
+ printf("m_a_val=%d\n", m_a_val);
+ }
+ virtual ~DerivedA() {}
+
+private:
+ int m_a_val;
+};
+
+class DerivedB : public VIRTUAL Base
+{
+public:
+ DerivedB(int val) : Base(val), m_b_val(val*3) {
+ printf("DerivedB::ctor()->\n");
+ printf("m_base_val=%d\n", m_base_val);
+ printf("m_b_val=%d\n", m_b_val);
+ }
+ virtual ~DerivedB() {}
+
+ virtual void
+ forcast(int input) {
+ int future_val = m_b_val + input * 2;
+ printf("Forcasting %d\n", future_val);
+ }
+
+private:
+ int m_b_val;
+};
+
+int
+main(int argc, char **argv)
+{
+ DerivedA* dA = new DerivedA(10);
+ DerivedB* dB = new DerivedB(12);
+ Base *array[2] = {dA, dB};
+ Base *teller = NULL;
+ for (int i = 0; i < 2; ++i) {
+ teller = array[i];
+ teller->forcast(i); // Set breakpoint here.
+ }
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/enum_types/Makefile b/packages/Python/lldbsuite/test/lang/cpp/enum_types/Makefile
new file mode 100644
index 000000000000..0e0f5d1dad3d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/enum_types/Makefile
@@ -0,0 +1,10 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+CXXFLAGS += -std=c++11
+
+clean: OBJECTS+=$(wildcard main.d.*)
+
+include $(LEVEL)/Makefile.rules
+
diff --git a/packages/Python/lldbsuite/test/lang/cpp/enum_types/TestCPP11EnumTypes.py b/packages/Python/lldbsuite/test/lang/cpp/enum_types/TestCPP11EnumTypes.py
new file mode 100644
index 000000000000..51c145c7b7cd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/enum_types/TestCPP11EnumTypes.py
@@ -0,0 +1,110 @@
+"""Look up enum type information and check for correct display."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class CPP11EnumTypesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test_int8_t(self):
+ """Test C++11 enumeration class types as int8_t types."""
+ self.build(dictionary={'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=int8_t"'})
+ self.image_lookup_for_enum_type()
+
+ def test_int16_t(self):
+ """Test C++11 enumeration class types as int16_t types."""
+ self.build(dictionary={'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=int16_t"'})
+ self.image_lookup_for_enum_type()
+
+ def test_int32_t(self):
+ """Test C++11 enumeration class types as int32_t types."""
+ self.build(dictionary={'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=int32_t"'})
+ self.image_lookup_for_enum_type()
+
+ def test_int64_t(self):
+ """Test C++11 enumeration class types as int64_t types."""
+ self.build(dictionary={'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=int64_t"'})
+ self.image_lookup_for_enum_type()
+
+ def test_uint8_t(self):
+ """Test C++11 enumeration class types as uint8_t types."""
+ self.build(dictionary={'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=uint8_t"'})
+ self.image_lookup_for_enum_type()
+
+ def test_uint16_t(self):
+ """Test C++11 enumeration class types as uint16_t types."""
+ self.build(dictionary={'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=uint16_t"'})
+ self.image_lookup_for_enum_type()
+
+ def test_uint32_t(self):
+ """Test C++11 enumeration class types as uint32_t types."""
+ self.build(dictionary={'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=uint32_t"'})
+ self.image_lookup_for_enum_type()
+
+ def test_uint64_t(self):
+ """Test C++11 enumeration class types as uint64_t types."""
+ self.build(dictionary={'CFLAGS_EXTRAS': '"-DTEST_BLOCK_CAPTURED_VARS=uint64_t"'})
+ self.image_lookup_for_enum_type()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def image_lookup_for_enum_type(self):
+ """Test C++11 enumeration class types."""
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break inside the main.
+ bkpt_id = lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ # Look up information about the 'DayType' enum type.
+ # Check for correct display.
+ self.expect("image lookup -t DayType", DATA_TYPES_DISPLAYED_CORRECTLY,
+ substrs = ['enum DayType {',
+ 'Monday',
+ 'Tuesday',
+ 'Wednesday',
+ 'Thursday',
+ 'Friday',
+ 'Saturday',
+ 'Sunday',
+ 'kNumDays',
+ '}'])
+
+ enum_values = [ '-4',
+ 'Monday',
+ 'Tuesday',
+ 'Wednesday',
+ 'Thursday',
+ 'Friday',
+ 'Saturday',
+ 'Sunday',
+ 'kNumDays',
+ '5'];
+
+ bkpt = self.target().FindBreakpointByID(bkpt_id)
+ for enum_value in enum_values:
+ self.expect("frame variable day", 'check for valid enumeration value',
+ substrs = [enum_value])
+ lldbutil.continue_to_breakpoint (self.process(), bkpt)
diff --git a/packages/Python/lldbsuite/test/lang/cpp/enum_types/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/enum_types/main.cpp
new file mode 100644
index 000000000000..8595050afbbf
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/enum_types/main.cpp
@@ -0,0 +1,33 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+#include <stdint.h>
+
+
+int main (int argc, char const *argv[])
+{
+ typedef int16_t enum_integer_t;
+ enum class DayType : enum_integer_t {
+ Monday = -3,
+ Tuesday,
+ Wednesday,
+ Thursday,
+ Friday,
+ Saturday,
+ Sunday,
+ kNumDays
+ };
+ enum_integer_t day_value;
+ for (day_value = (enum_integer_t)DayType::Monday - 1; day_value <= (enum_integer_t)DayType::kNumDays + 1; ++day_value)
+ {
+ DayType day = (DayType)day_value;
+ printf("day as int is %i\n", (int)day); // Set break point at this line.
+ }
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/exceptions/Makefile b/packages/Python/lldbsuite/test/lang/cpp/exceptions/Makefile
new file mode 100644
index 000000000000..a6bd8463ad54
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/exceptions/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := exceptions.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/exceptions/TestCPPExceptionBreakpoints.py b/packages/Python/lldbsuite/test/lang/cpp/exceptions/TestCPPExceptionBreakpoints.py
new file mode 100644
index 000000000000..65cf0b361d84
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/exceptions/TestCPPExceptionBreakpoints.py
@@ -0,0 +1,65 @@
+"""
+Test lldb exception breakpoint command for CPP.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class CPPBreakpointTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ self.source = 'exceptions.cpp'
+ self.catch_line = line_number(self.source, '// This is the line you should stop at for catch')
+
+ @expectedFailureWindows("llvm.org/pr24538") # clang-cl does not support throw or catch
+ def test(self):
+ """Test lldb exception breakpoint command for CPP."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target from the debugger.
+
+ target = self.dbg.CreateTarget (exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ exception_bkpt = target.BreakpointCreateForException (lldb.eLanguageTypeC_plus_plus, True, True)
+ self.assertTrue (exception_bkpt, "Made an exception breakpoint")
+
+ # Now run, and make sure we hit our breakpoint:
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue (process, "Got a valid process")
+
+ stopped_threads = []
+ stopped_threads = lldbutil.get_threads_stopped_at_breakpoint (process, exception_bkpt)
+ self.assertTrue (len(stopped_threads) == 1, "Stopped at our exception breakpoint.")
+ thread = stopped_threads[0]
+ # Make sure our throw function is still above us on the stack:
+
+ frame_functions = lldbutil.get_function_names(thread)
+ self.assertTrue (frame_functions.count ("throws_exception_on_even(int)") == 1, "Our throw function is still on the stack.")
+
+ # Okay we hit our exception throw breakpoint, now make sure we get our catch breakpoint.
+ # One potential complication is that we might hit a couple of the exception breakpoints in getting out of the throw.
+ # so loop till we don't see the throws function on the stack. We should stop one more time for our exception breakpoint
+ # and that should be the catch...
+
+ while frame_functions.count ("throws_exception_on_even(int)") == 1:
+ stopped_threads = lldbutil.continue_to_breakpoint (process, exception_bkpt)
+ self.assertTrue (len(stopped_threads) == 1)
+
+ thread = stopped_threads[0]
+ frame_functions = lldbutil.get_function_names(thread)
+
+ self.assertTrue (frame_functions.count ("throws_exception_on_even(int)") == 0, "At catch our throw function is off the stack")
+ self.assertTrue (frame_functions.count ("intervening_function(int)") == 0, "At catch our intervening function is off the stack")
+ self.assertTrue (frame_functions.count ("catches_exception(int)") == 1, "At catch our catch function is on the stack")
diff --git a/packages/Python/lldbsuite/test/lang/cpp/exceptions/exceptions.cpp b/packages/Python/lldbsuite/test/lang/cpp/exceptions/exceptions.cpp
new file mode 100644
index 000000000000..150d420b241b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/exceptions/exceptions.cpp
@@ -0,0 +1,42 @@
+#include <exception>
+#include <stdio.h>
+
+int throws_exception_on_even (int value);
+int intervening_function (int value);
+int catches_exception (int value);
+
+int
+catches_exception (int value)
+{
+ try
+ {
+ return intervening_function(value); // This is the line you should stop at for catch
+ }
+ catch (int value)
+ {
+ return value;
+ }
+}
+
+int
+intervening_function (int value)
+{
+ return throws_exception_on_even (2 * value);
+}
+
+int
+throws_exception_on_even (int value)
+{
+ printf ("Mod two works: %d.\n", value%2);
+ if (value % 2 == 0)
+ throw 30;
+ else
+ return value;
+}
+
+int
+main ()
+{
+ catches_exception (10); // Stop here
+ return 5;
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/Makefile b/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/TestFrameVariableAnonymousUnions.py b/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/TestFrameVariableAnonymousUnions.py
new file mode 100644
index 000000000000..396a637041cb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/TestFrameVariableAnonymousUnions.py
@@ -0,0 +1,27 @@
+"""
+Tests that frame variable looks into anonymous unions
+"""
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class FrameVariableAnonymousUnionsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test_with_run_command(self):
+ """Tests that frame variable looks into anonymous unions"""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ line = line_number('main.cpp', '// break here')
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", line, num_expected_locations=-1, loc_exact=False)
+
+ self.runCmd("process launch", RUN_SUCCEEDED)
+
+ self.expect('frame variable -f x i', substrs=['ffffff41'])
+ self.expect('frame variable c', substrs=["'A"])
+
+ self.expect('frame variable x', matching=False, substrs=['3'])
+ self.expect('frame variable y', matching=False, substrs=["'B'"])
+ self.expect('frame variable z', matching=False, substrs=['14'])
diff --git a/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/main.cpp
new file mode 100644
index 000000000000..494b846336ff
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/frame-var-anon-unions/main.cpp
@@ -0,0 +1,23 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+int main() {
+ union {
+ int i;
+ char c;
+ };
+ struct {
+ int x;
+ char y;
+ short z;
+ } s{3,'B',14};
+ i = 0xFFFFFF00;
+ c = 'A';
+ return c; // break here
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/global_operators/Makefile b/packages/Python/lldbsuite/test/lang/cpp/global_operators/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/global_operators/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/global_operators/TestCppGlobalOperators.py b/packages/Python/lldbsuite/test/lang/cpp/global_operators/TestCppGlobalOperators.py
new file mode 100644
index 000000000000..de56cd6a6c49
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/global_operators/TestCppGlobalOperators.py
@@ -0,0 +1,54 @@
+"""
+Test that global operators are found and evaluated.
+"""
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TestCppGlobalOperators(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureWindows("llvm.org/pr21765")
+ def test_with_run_command(self):
+ self.build()
+
+ # Get main source file
+ src_file = "main.cpp"
+ src_file_spec = lldb.SBFileSpec(src_file)
+ self.assertTrue(src_file_spec.IsValid(), "Main source file")
+
+ # Get the path of the executable
+ cwd = os.getcwd()
+ exe_file = "a.out"
+ exe_path = os.path.join(cwd, exe_file)
+
+ # Load the executable
+ target = self.dbg.CreateTarget(exe_path)
+ self.assertTrue(target.IsValid(), VALID_TARGET)
+
+ # Break on main function
+ main_breakpoint = target.BreakpointCreateBySourceRegex("// break here", src_file_spec)
+ self.assertTrue(main_breakpoint.IsValid() and main_breakpoint.GetNumLocations() >= 1, VALID_BREAKPOINT)
+
+ # Launch the process
+ args = None
+ env = None
+ process = target.LaunchSimple(args, env, self.get_process_working_directory())
+ self.assertTrue(process.IsValid(), PROCESS_IS_VALID)
+
+ # Get the thread of the process
+ self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+
+ # Check if global operators are evaluated
+ frame = thread.GetSelectedFrame()
+
+ test_result = frame.EvaluateExpression("operator==(s1, s2)")
+ self.assertTrue(test_result.IsValid() and test_result.GetValue() == "false", "operator==(s1, s2) = false")
+
+ test_result = frame.EvaluateExpression("operator==(s1, s3)")
+ self.assertTrue(test_result.IsValid() and test_result.GetValue() == "true", "operator==(s1, s3) = true")
+
+ test_result = frame.EvaluateExpression("operator==(s2, s3)")
+ self.assertTrue(test_result.IsValid() and test_result.GetValue() == "false", "operator==(s2, s3) = false")
diff --git a/packages/Python/lldbsuite/test/lang/cpp/global_operators/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/global_operators/main.cpp
new file mode 100644
index 000000000000..a0dd0787fa32
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/global_operators/main.cpp
@@ -0,0 +1,16 @@
+struct Struct {
+ int value;
+};
+
+bool operator==(const Struct &a, const Struct &b) {
+ return a.value == b.value;
+}
+
+int main() {
+ Struct s1, s2, s3;
+ s1.value = 3;
+ s2.value = 5;
+ s3.value = 3;
+ return 0; // break here
+}
+
diff --git a/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/Makefile b/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/Makefile
new file mode 100644
index 000000000000..6595e33b7269
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/Makefile
@@ -0,0 +1,35 @@
+LEVEL = ../../../make
+
+CXX_SOURCES = main.cpp length.cpp a.cpp
+
+CFLAGS_LIMIT = -c $(CXXFLAGS)
+CFLAGS_NO_LIMIT = -c $(CXXFLAGS)
+
+ifneq (,$(findstring clang,$(CC)))
+ CFLAGS_LIMIT += -flimit-debug-info
+ CFLAGS_NO_LIMIT += -fno-limit-debug-info
+endif
+
+all: limit nolimit
+
+limit: main.o length_limit.o a.o
+ $(CXX) $(LDFLAGS) main.o length_limit.o a.o -o limit
+
+nolimit: main.o length_nolimit.o a.o
+ $(CXX) $(LDFLAGS) main.o length_nolimit.o a.o -o nolimit
+
+main.o: main.cpp
+ $(CXX) $(CFLAGS_LIMIT) main.cpp -o main.o
+
+length_limit.o: length.cpp
+ $(CXX) $(CFLAGS_LIMIT) length.cpp -o length_limit.o
+
+length_nolimit.o: length.cpp
+ $(CXX) $(CFLAGS_NO_LIMIT) length.cpp -o length_nolimit.o
+
+a.o: a.cpp
+ $(CXX) $(CFLAGS_NO_DEBUG) -c a.cpp -o a.o
+
+clean: OBJECTS += limit nolimit length_limit.o length_nolimit.o length_limit.dwo length_nolimit.dwo
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/TestCppIncompleteTypes.py b/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/TestCppIncompleteTypes.py
new file mode 100644
index 000000000000..324f476efb9b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/TestCppIncompleteTypes.py
@@ -0,0 +1,66 @@
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TestCppIncompleteTypes(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureFreeBSD("llvm.org/pr25626 test executable not built correctly on FreeBSD")
+ @skipIfGcc
+ def test_limit_debug_info(self):
+ self.build()
+ frame = self.get_test_frame('limit')
+
+ value_f = frame.EvaluateExpression("f")
+ self.assertTrue(value_f.IsValid(), "'expr f' results in a valid SBValue object")
+ self.assertTrue(value_f.GetError().Success(), "'expr f' is successful")
+
+ value_a = frame.EvaluateExpression("a")
+ self.assertTrue(value_a.IsValid(), "'expr a' results in a valid SBValue object")
+ self.assertTrue(value_a.GetError().Success(), "'expr a' is successful")
+
+ @skipIfGcc
+ @skipIfWindows # Clang on Windows asserts in external record layout in this case.
+ def test_partial_limit_debug_info(self):
+ self.build()
+ frame = self.get_test_frame('nolimit')
+
+ value_f = frame.EvaluateExpression("f")
+ self.assertTrue(value_f.IsValid(), "'expr f' results in a valid SBValue object")
+ self.assertTrue(value_f.GetError().Success(), "'expr f' is successful")
+
+ value_a = frame.EvaluateExpression("a")
+ self.assertTrue(value_a.IsValid(), "'expr a' results in a valid SBValue object")
+ self.assertTrue(value_a.GetError().Success(), "'expr a' is successful")
+
+ def get_test_frame(self, exe):
+ # Get main source file
+ src_file = "main.cpp"
+ src_file_spec = lldb.SBFileSpec(src_file)
+ self.assertTrue(src_file_spec.IsValid(), "Main source file")
+
+ # Get the path of the executable
+ cwd = os.getcwd()
+ exe_path = os.path.join(cwd, exe)
+
+ # Load the executable
+ target = self.dbg.CreateTarget(exe_path)
+ self.assertTrue(target.IsValid(), VALID_TARGET)
+
+ # Break on main function
+ main_breakpoint = target.BreakpointCreateBySourceRegex("break here", src_file_spec)
+ self.assertTrue(main_breakpoint.IsValid() and main_breakpoint.GetNumLocations() >= 1, VALID_BREAKPOINT)
+
+ # Launch the process
+ args = None
+ env = None
+ process = target.LaunchSimple(args, env, self.get_process_working_directory())
+ self.assertTrue(process.IsValid(), PROCESS_IS_VALID)
+
+ # Get the thread of the process
+ self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+
+ # Get frame for current thread
+ return thread.GetSelectedFrame()
diff --git a/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/a.cpp b/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/a.cpp
new file mode 100644
index 000000000000..36b374be6f33
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/a.cpp
@@ -0,0 +1,10 @@
+
+#include "a.h"
+
+A::A () { }
+
+int
+A::length ()
+{
+ return 123;
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/a.h b/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/a.h
new file mode 100644
index 000000000000..13e9496e3fd7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/a.h
@@ -0,0 +1,11 @@
+#ifndef __A_H__
+#define __A_H__
+
+class A
+{
+public:
+ A();
+ virtual int length();
+};
+
+#endif
diff --git a/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/length.cpp b/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/length.cpp
new file mode 100644
index 000000000000..90a3b640f732
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/length.cpp
@@ -0,0 +1,8 @@
+
+#include "length.h"
+
+int
+length (A &a)
+{
+ return a.length();
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/length.h b/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/length.h
new file mode 100644
index 000000000000..96df4f021808
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/length.h
@@ -0,0 +1,8 @@
+#ifndef __LENGTH_H__
+#define __LENGTH_H__
+
+#include "a.h"
+
+int length (A &a);
+
+#endif
diff --git a/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/main.cpp
new file mode 100644
index 000000000000..ad324c905818
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/incomplete-types/main.cpp
@@ -0,0 +1,18 @@
+
+#include "length.h"
+
+class Foo {
+public:
+ A a;
+};
+
+class MyA : public A {
+};
+
+int main()
+{
+ Foo f;
+ MyA a;
+
+ return length(a); // break here
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/Makefile b/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/Makefile
new file mode 100644
index 000000000000..b9a3d3fe1c81
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../make
+
+CXX_SOURCES = main.cpp derived.cpp base.cpp
+
+CFLAGS_EXTRAS += $(LIMIT_DEBUG_INFO_FLAGS)
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/TestWithLimitDebugInfo.py b/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/TestWithLimitDebugInfo.py
new file mode 100644
index 000000000000..ec26f9efe907
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/TestWithLimitDebugInfo.py
@@ -0,0 +1,48 @@
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TestWithLimitDebugInfo(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIf(debug_info=not_in(["dwarf"]))
+ def test_limit_debug_info(self):
+ self.build()
+
+ cwd = os.getcwd()
+
+ src_file = os.path.join(cwd, "main.cpp")
+ src_file_spec = lldb.SBFileSpec(src_file)
+ self.assertTrue(src_file_spec.IsValid(), "breakpoint file")
+
+ # Get the path of the executable
+ exe_path = os.path.join(cwd, 'a.out')
+
+ # Load the executable
+ target = self.dbg.CreateTarget(exe_path)
+ self.assertTrue(target.IsValid(), VALID_TARGET)
+
+ # Break on main function
+ breakpoint = target.BreakpointCreateBySourceRegex("break here", src_file_spec)
+ self.assertTrue(breakpoint.IsValid() and breakpoint.GetNumLocations() >= 1, VALID_BREAKPOINT)
+
+ # Launch the process
+ process = target.LaunchSimple(None, None, self.get_process_working_directory())
+ self.assertTrue(process.IsValid(), PROCESS_IS_VALID)
+
+ # Get the thread of the process
+ self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ thread.StepInto()
+
+ # Get frame for current thread
+ frame = thread.GetSelectedFrame()
+
+ v1 = frame.EvaluateExpression("1")
+ self.assertTrue(v1.IsValid(), "'expr 1' results in a valid SBValue object")
+ self.assertTrue(v1.GetError().Success(), "'expr 1' succeeds without an error.")
+
+ v2 = frame.EvaluateExpression("this")
+ self.assertTrue(v2.IsValid(), "'expr this' results in a valid SBValue object")
+ self.assertTrue(v2.GetError().Success(), "'expr this' succeeds without an error.")
diff --git a/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/base.cpp b/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/base.cpp
new file mode 100644
index 000000000000..4023bdbc64af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/base.cpp
@@ -0,0 +1,6 @@
+#include "base.h"
+
+void FooNS::bar() {
+ x = 54321;
+}
+
diff --git a/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/base.h b/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/base.h
new file mode 100644
index 000000000000..d3a09572bd25
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/base.h
@@ -0,0 +1,10 @@
+class FooNS
+{
+public:
+ virtual void bar();
+ virtual char baz() = 0;
+
+protected:
+ int x;
+};
+
diff --git a/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/derived.cpp b/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/derived.cpp
new file mode 100644
index 000000000000..9d773593eb51
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/derived.cpp
@@ -0,0 +1,6 @@
+#include "derived.h"
+
+char Foo::baz() {
+ return (char)(x&0xff);
+}
+
diff --git a/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/derived.h b/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/derived.h
new file mode 100644
index 000000000000..46b3f83b9f74
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/derived.h
@@ -0,0 +1,13 @@
+#include "base.h"
+
+class Foo : public FooNS
+{
+public:
+ Foo() {
+ a = 12345;
+ }
+
+ char baz() override;
+ int a;
+};
+
diff --git a/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/main.cpp
new file mode 100644
index 000000000000..64e0349b5826
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/limit-debug-info/main.cpp
@@ -0,0 +1,7 @@
+#include "derived.h"
+
+int main() {
+ Foo f; // break here
+ f.bar();
+ return f.baz();
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/namespace/Makefile b/packages/Python/lldbsuite/test/lang/cpp/namespace/Makefile
new file mode 100644
index 000000000000..7dd5eb4c11f1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/namespace/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp ns.cpp ns2.cpp ns3.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespace.py b/packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespace.py
new file mode 100644
index 000000000000..a60d8252e9f0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespace.py
@@ -0,0 +1,125 @@
+"""
+Test the printing of anonymous and named namespace variables.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class NamespaceTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers for declarations of namespace variables i and j.
+ self.line_var_i = line_number('main.cpp',
+ '// Find the line number for anonymous namespace variable i.')
+ self.line_var_j = line_number('main.cpp',
+ '// Find the line number for named namespace variable j.')
+ # And the line number to break at.
+ self.line_break = line_number('main.cpp',
+ '// Set break point at this line.')
+ # Break inside do {} while and evaluate value
+ self.line_break_ns1 = line_number('main.cpp', '// Evaluate ns1::value')
+ self.line_break_ns2 = line_number('main.cpp', '// Evaluate ns2::value')
+
+ def runToBkpt(self, command):
+ self.runCmd(command, RUN_SUCCEEDED)
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # rdar://problem/8668674
+ @expectedFailureWindows("llvm.org/pr24764")
+ def test_with_run_command(self):
+ """Test that anonymous and named namespace variables display correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line_break_ns1, num_expected_locations=1, loc_exact=True)
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line_break_ns2, num_expected_locations=1, loc_exact=True)
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line_break, num_expected_locations=1, loc_exact=True)
+
+ self.runToBkpt("run")
+ # Evaluate ns1::value
+ self.expect("expression -- value", startstr = "(int) $0 = 100")
+
+ self.runToBkpt("continue")
+ # Evaluate ns2::value
+ self.expect("expression -- value", startstr = "(int) $1 = 200")
+
+ self.runToBkpt("continue")
+ # On Mac OS X, gcc 4.2 emits the wrong debug info with respect to types.
+ slist = ['(int) a = 12', 'anon_uint', 'a_uint', 'b_uint', 'y_uint']
+ if self.platformIsDarwin() and self.getCompiler() in ['clang', 'llvm-gcc']:
+ slist = ['(int) a = 12',
+ '::my_uint_t', 'anon_uint = 0',
+ '(A::uint_t) a_uint = 1',
+ '(A::B::uint_t) b_uint = 2',
+ '(Y::uint_t) y_uint = 3']
+
+ # 'frame variable' displays the local variables with type information.
+ self.expect('frame variable', VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = slist)
+
+ # 'frame variable' with basename 'i' should work.
+ self.expect("frame variable --show-declaration --show-globals i",
+ startstr = "main.cpp:%d: (int) (anonymous namespace)::i = 3" % self.line_var_i)
+ # main.cpp:12: (int) (anonymous namespace)::i = 3
+
+ # 'frame variable' with basename 'j' should work, too.
+ self.expect("frame variable --show-declaration --show-globals j",
+ startstr = "main.cpp:%d: (int) A::B::j = 4" % self.line_var_j)
+ # main.cpp:19: (int) A::B::j = 4
+
+ # 'frame variable' should support address-of operator.
+ self.runCmd("frame variable &i")
+
+ # 'frame variable' with fully qualified name 'A::B::j' should work.
+ self.expect("frame variable A::B::j", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = '(int) A::B::j = 4',
+ patterns = [' = 4'])
+
+ # So should the anonymous namespace case.
+ self.expect("frame variable '(anonymous namespace)::i'", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = '(int) (anonymous namespace)::i = 3',
+ patterns = [' = 3'])
+
+ # rdar://problem/8660275
+ # test/namespace: 'expression -- i+j' not working
+ # This has been fixed.
+ self.expect("expression -- i + j",
+ startstr = "(int) $2 = 7")
+ # (int) $2 = 7
+
+ self.runCmd("expression -- i")
+ self.runCmd("expression -- j")
+
+ # rdar://problem/8668674
+ # expression command with fully qualified namespace for a variable does not work
+ self.expect("expression -- ::i", VARIABLES_DISPLAYED_CORRECTLY,
+ patterns = [' = 3'])
+ self.expect("expression -- A::B::j", VARIABLES_DISPLAYED_CORRECTLY,
+ patterns = [' = 4'])
+
+ # expression command with function in anonymous namespace
+ self.expect("expression -- myanonfunc(3)",
+ patterns = [' = 6'])
+
+ # global namespace qualification with function in anonymous namespace
+ self.expect("expression -- ::myanonfunc(4)",
+ patterns = [' = 8'])
+
+ self.expect("p myanonfunc",
+ patterns = ['\(anonymous namespace\)::myanonfunc\(int\)'])
+
+ self.expect("p variadic_sum",
+ patterns = ['\(anonymous namespace\)::variadic_sum\(int, ...\)'])
diff --git a/packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespaceLookup.py b/packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespaceLookup.py
new file mode 100644
index 000000000000..4cad45564c87
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/namespace/TestNamespaceLookup.py
@@ -0,0 +1,223 @@
+"""
+Test the printing of anonymous and named namespace variables.
+"""
+
+from __future__ import print_function
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class NamespaceLookupTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Break inside different scopes and evaluate value
+ self.line_break_global_scope = line_number('ns.cpp', '// BP_global_scope')
+ self.line_break_file_scope = line_number('ns2.cpp', '// BP_file_scope')
+ self.line_break_ns_scope = line_number('ns2.cpp', '// BP_ns_scope')
+ self.line_break_nested_ns_scope = line_number('ns2.cpp', '// BP_nested_ns_scope')
+ self.line_break_nested_ns_scope_after_using = line_number('ns2.cpp', '// BP_nested_ns_scope_after_using')
+ self.line_break_before_using_directive = line_number('ns3.cpp', '// BP_before_using_directive')
+ self.line_break_after_using_directive = line_number('ns3.cpp', '// BP_after_using_directive')
+
+ def runToBkpt(self, command):
+ self.runCmd(command, RUN_SUCCEEDED)
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ @expectedFailureFreeBSD("llvm.org/pr25819")
+ @expectedFailureLinux("llvm.org/pr25819")
+ def test_scope_lookup_with_run_command(self):
+ """Test scope lookup of functions in lldb."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "ns.cpp", self.line_break_global_scope, num_expected_locations=1, loc_exact=False)
+ lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_ns_scope, num_expected_locations=1, loc_exact=False)
+ lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_nested_ns_scope, num_expected_locations=1, loc_exact=False)
+ lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_nested_ns_scope_after_using, num_expected_locations=1, loc_exact=False)
+ lldbutil.run_break_set_by_file_and_line (self, "ns3.cpp", self.line_break_before_using_directive, num_expected_locations=1, loc_exact=False)
+ lldbutil.run_break_set_by_file_and_line (self, "ns3.cpp", self.line_break_after_using_directive, num_expected_locations=1, loc_exact=False)
+
+ # Run to BP_global_scope at global scope
+ self.runToBkpt("run")
+ # Evaluate func() - should call ::func()
+ self.expect("expr -- func()", startstr = "(int) $0 = 1")
+ # Evaluate A::B::func() - should call A::B::func()
+ self.expect("expr -- A::B::func()", startstr = "(int) $1 = 4")
+ # Evaluate func(10) - should call ::func(int)
+ self.expect("expr -- func(10)", startstr = "(int) $2 = 11")
+ # Evaluate ::func() - should call A::func()
+ self.expect("expr -- ::func()", startstr = "(int) $3 = 1")
+ # Evaluate A::foo() - should call A::foo()
+ self.expect("expr -- A::foo()", startstr = "(int) $4 = 42")
+
+ # Continue to BP_ns_scope at ns scope
+ self.runToBkpt("continue")
+ # Evaluate func(10) - should call A::func(int)
+ self.expect("expr -- func(10)", startstr = "(int) $5 = 13")
+ # Evaluate B::func() - should call B::func()
+ self.expect("expr -- B::func()", startstr = "(int) $6 = 4")
+ # Evaluate func() - should call A::func()
+ self.expect("expr -- func()", startstr = "(int) $7 = 3")
+
+ # Continue to BP_nested_ns_scope at nested ns scope
+ self.runToBkpt("continue")
+ # Evaluate func() - should call A::B::func()
+ self.expect("expr -- func()", startstr = "(int) $8 = 4")
+ # Evaluate A::func() - should call A::func()
+ self.expect("expr -- A::func()", startstr = "(int) $9 = 3")
+
+ # Evaluate func(10) - should call A::func(10)
+ # NOTE: Under the rules of C++, this test would normally get an error
+ # because A::B::func() hides A::func(), but lldb intentionally
+ # disobeys these rules so that the intended overload can be found
+ # by only removing duplicates if they have the same type.
+ self.expect("expr -- func(10)", startstr = "(int) $10 = 13")
+
+ # Continue to BP_nested_ns_scope_after_using at nested ns scope after using declaration
+ self.runToBkpt("continue")
+ # Evaluate A::func(10) - should call A::func(int)
+ self.expect("expr -- A::func(10)", startstr = "(int) $11 = 13")
+
+ # Continue to BP_before_using_directive at global scope before using declaration
+ self.runToBkpt("continue")
+ # Evaluate ::func() - should call ::func()
+ self.expect("expr -- ::func()", startstr = "(int) $12 = 1")
+ # Evaluate B::func() - should call B::func()
+ self.expect("expr -- B::func()", startstr = "(int) $13 = 4")
+
+ # Continue to BP_after_using_directive at global scope after using declaration
+ self.runToBkpt("continue")
+ # Evaluate ::func() - should call ::func()
+ self.expect("expr -- ::func()", startstr = "(int) $14 = 1")
+ # Evaluate B::func() - should call B::func()
+ self.expect("expr -- B::func()", startstr = "(int) $15 = 4")
+
+ @unittest2.expectedFailure("lldb scope lookup of functions bugs")
+ def test_function_scope_lookup_with_run_command(self):
+ """Test scope lookup of functions in lldb."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "ns.cpp", self.line_break_global_scope, num_expected_locations=1, loc_exact=False)
+ lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_ns_scope, num_expected_locations=1, loc_exact=False)
+
+ # Run to BP_global_scope at global scope
+ self.runToBkpt("run")
+ # Evaluate foo() - should call ::foo()
+ # FIXME: lldb finds Y::foo because lookup for variables is done
+ # before functions.
+ self.expect("expr -- foo()", startstr = "(int) $0 = 42")
+ # Evaluate ::foo() - should call ::foo()
+ # FIXME: lldb finds Y::foo because lookup for variables is done
+ # before functions and :: is ignored.
+ self.expect("expr -- ::foo()", startstr = "(int) $1 = 42")
+
+ # Continue to BP_ns_scope at ns scope
+ self.runToBkpt("continue")
+ # Evaluate foo() - should call A::foo()
+ # FIXME: lldb finds Y::foo because lookup for variables is done
+ # before functions.
+ self.expect("expr -- foo()", startstr = "(int) $2 = 42")
+
+ @unittest2.expectedFailure("lldb file scope lookup bugs")
+ def test_file_scope_lookup_with_run_command(self):
+ """Test file scope lookup in lldb."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_file_scope, num_expected_locations=1, loc_exact=False)
+
+ # Run to BP_file_scope at file scope
+ self.runToBkpt("run")
+ # Evaluate func() - should call static ns2.cpp:func()
+ # FIXME: This test fails because lldb doesn't know about file scopes so
+ # finds the global ::func().
+ self.expect("expr -- func()", startstr = "(int) $0 = 2")
+
+ @expectedFailureLinux("llvm.org/pr25819")
+ def test_scope_lookup_before_using_with_run_command(self):
+ """Test scope lookup before using in lldb."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "ns3.cpp", self.line_break_before_using_directive, num_expected_locations=1, loc_exact=False)
+
+ # Run to BP_before_using_directive at global scope before using declaration
+ self.runToBkpt("run")
+ # Evaluate func() - should call ::func()
+ self.expect("expr -- func()", startstr = "(int) $0 = 1")
+
+ # NOTE: this test may fail on older systems that don't emit import
+ # emtries in DWARF - may need to add checks for compiler versions here.
+ @expectedFailureFreeBSD("llvm.org/pr25819")
+ @expectedFailureLinux("llvm.org/pr25819")
+ def test_scope_after_using_directive_lookup_with_run_command(self):
+ """Test scope lookup after using directive in lldb."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "ns3.cpp", self.line_break_after_using_directive, num_expected_locations=1, loc_exact=False)
+
+ # Run to BP_after_using_directive at global scope after using declaration
+ self.runToBkpt("run")
+ # Evaluate func2() - should call A::func2()
+ self.expect("expr -- func2()", startstr = "(int) $0 = 3")
+
+ @unittest2.expectedFailure("lldb scope lookup after using declaration bugs")
+ # NOTE: this test may fail on older systems that don't emit import
+ # emtries in DWARF - may need to add checks for compiler versions here.
+ def test_scope_after_using_declaration_lookup_with_run_command(self):
+ """Test scope lookup after using declaration in lldb."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_nested_ns_scope_after_using, num_expected_locations=1, loc_exact=False)
+
+ # Run to BP_nested_ns_scope_after_using at nested ns scope after using declaration
+ self.runToBkpt("run")
+ # Evaluate func() - should call A::func()
+ self.expect("expr -- func()", startstr = "(int) $0 = 3")
+
+ @unittest2.expectedFailure("lldb scope lookup ambiguity after using bugs")
+ def test_scope_ambiguity_after_using_lookup_with_run_command(self):
+ """Test scope lookup ambiguity after using in lldb."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "ns3.cpp", self.line_break_after_using_directive, num_expected_locations=1, loc_exact=False)
+
+ # Run to BP_after_using_directive at global scope after using declaration
+ self.runToBkpt("run")
+ # Evaluate func() - should get error: ambiguous
+ # FIXME: This test fails because lldb removes duplicates if they have
+ # the same type.
+ self.expect("expr -- func()", startstr = "error")
+
+ @expectedFailureFreeBSD("llvm.org/pr25819")
+ @expectedFailureLinux("llvm.org/pr25819")
+ def test_scope_lookup_shadowed_by_using_with_run_command(self):
+ """Test scope lookup shadowed by using in lldb."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "ns2.cpp", self.line_break_nested_ns_scope, num_expected_locations=1, loc_exact=False)
+
+ # Run to BP_nested_ns_scope at nested ns scope
+ self.runToBkpt("run")
+ # Evaluate func(10) - should call A::func(10)
+ # NOTE: Under the rules of C++, this test would normally get an error
+ # because A::B::func() shadows A::func(), but lldb intentionally
+ # disobeys these rules so that the intended overload can be found
+ # by only removing duplicates if they have the same type.
+ self.expect("expr -- func(10)", startstr = "(int) $0 = 13")
+
diff --git a/packages/Python/lldbsuite/test/lang/cpp/namespace/cmds.txt b/packages/Python/lldbsuite/test/lang/cpp/namespace/cmds.txt
new file mode 100644
index 000000000000..76bb1bcba759
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/namespace/cmds.txt
@@ -0,0 +1,3 @@
+b main.cpp:54
+c
+var
diff --git a/packages/Python/lldbsuite/test/lang/cpp/namespace/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/namespace/main.cpp
new file mode 100644
index 000000000000..560ec40f4733
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/namespace/main.cpp
@@ -0,0 +1,124 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <cstdarg>
+#include "ns.h"
+
+namespace {
+ typedef unsigned int my_uint_t;
+ int i; // Find the line number for anonymous namespace variable i.
+
+ int myanonfunc (int a)
+ {
+ return a + a;
+ }
+
+ int
+ variadic_sum (int arg_count...)
+ {
+ int sum = 0;
+ va_list args;
+ va_start(args, arg_count);
+
+ for (int i = 0; i < arg_count; i++)
+ sum += va_arg(args, int);
+
+ va_end(args);
+ return sum;
+ }
+}
+
+namespace A {
+ typedef unsigned int uint_t;
+ namespace B {
+ typedef unsigned int uint_t;
+ int j; // Find the line number for named namespace variable j.
+ int myfunc (int a);
+ int myfunc2(int a)
+ {
+ return a + 2;
+ }
+ float myfunc (float f)
+ {
+ return f - 2.0;
+ }
+ }
+}
+
+namespace Y
+{
+ typedef unsigned int uint_t;
+ using A::B::j;
+ int foo;
+}
+
+using A::B::j; // using declaration
+
+namespace Foo = A::B; // namespace alias
+
+using Foo::myfunc; // using declaration
+
+using namespace Foo; // using directive
+
+namespace A {
+ namespace B {
+ using namespace Y;
+ int k;
+ }
+}
+
+namespace ns1 {
+ int value = 100;
+}
+
+namespace ns2 {
+ int value = 200;
+}
+
+void test_namespace_scopes() {
+ do {
+ using namespace ns1;
+ printf("ns1::value = %d\n", value); // Evaluate ns1::value
+ } while(0);
+
+ do {
+ using namespace ns2;
+ printf("ns2::value = %d\n", value); // Evaluate ns2::value
+ } while(0);
+}
+
+int Foo::myfunc(int a)
+{
+ test_namespace_scopes();
+
+ ::my_uint_t anon_uint = 0;
+ A::uint_t a_uint = 1;
+ B::uint_t b_uint = 2;
+ Y::uint_t y_uint = 3;
+ i = 3;
+ j = 4;
+ printf("::i=%d\n", ::i);
+ printf("A::B::j=%d\n", A::B::j);
+ printf("variadic_sum=%d\n", variadic_sum(3, 1, 2, 3));
+ myanonfunc(3);
+ return myfunc2(3) + j + i + a + 2 + anon_uint + a_uint + b_uint + y_uint; // Set break point at this line.
+}
+
+int
+main (int argc, char const *argv[])
+{
+ test_lookup_at_global_scope();
+ test_lookup_at_file_scope();
+ A::test_lookup_at_ns_scope();
+ A::B::test_lookup_at_nested_ns_scope();
+ A::B::test_lookup_at_nested_ns_scope_after_using();
+ test_lookup_before_using_directive();
+ test_lookup_after_using_directive();
+ return Foo::myfunc(12);
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/namespace/ns.cpp b/packages/Python/lldbsuite/test/lang/cpp/namespace/ns.cpp
new file mode 100644
index 000000000000..9e5637d02b4b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/namespace/ns.cpp
@@ -0,0 +1,32 @@
+//===-- ns.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "ns.h"
+
+int foo()
+{
+ printf("global foo()\n");
+ return 42;
+}
+int func()
+{
+ printf("global func()\n");
+ return 1;
+}
+int func(int a)
+{
+ printf("global func(int)\n");
+ return a + 1;
+}
+void test_lookup_at_global_scope()
+{
+ // BP_global_scope
+ printf("at global scope: foo() = %d\n", foo()); // eval foo(), exp: 42
+ printf("at global scope: func() = %d\n", func()); // eval func(), exp: 1
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/namespace/ns.h b/packages/Python/lldbsuite/test/lang/cpp/namespace/ns.h
new file mode 100644
index 000000000000..a07b600efa30
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/namespace/ns.h
@@ -0,0 +1,36 @@
+//===-- ns.h ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+
+void test_lookup_at_global_scope();
+void test_lookup_at_file_scope();
+void test_lookup_before_using_directive();
+void test_lookup_after_using_directive();
+int func(int a);
+namespace A {
+ int foo();
+ int func(int a);
+ inline int func()
+ {
+ printf("A::func()\n");
+ return 3;
+ }
+ inline int func2()
+ {
+ printf("A::func2()\n");
+ return 3;
+ }
+ void test_lookup_at_ns_scope();
+ namespace B {
+ int func();
+ void test_lookup_at_nested_ns_scope();
+ void test_lookup_at_nested_ns_scope_after_using();
+ }
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/namespace/ns2.cpp b/packages/Python/lldbsuite/test/lang/cpp/namespace/ns2.cpp
new file mode 100644
index 000000000000..04046ad9b7f4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/namespace/ns2.cpp
@@ -0,0 +1,65 @@
+//===-- ns2.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "ns.h"
+
+static int func()
+{
+ printf("static m2.cpp func()\n");
+ return 2;
+}
+void test_lookup_at_file_scope()
+{
+ // BP_file_scope
+ printf("at file scope: func() = %d\n", func()); // eval func(), exp: 2
+ printf("at file scope: func(10) = %d\n", func(10)); // eval func(10), exp: 11
+}
+namespace A {
+ namespace B {
+ int func()
+ {
+ printf("A::B::func()\n");
+ return 4;
+ }
+ void test_lookup_at_nested_ns_scope()
+ {
+ // BP_nested_ns_scope
+ printf("at nested ns scope: func() = %d\n", func()); // eval func(), exp: 4
+
+ //printf("func(10) = %d\n", func(10)); // eval func(10), exp: 13
+ // NOTE: Under the rules of C++, this test would normally get an error
+ // because A::B::func() hides A::func(), but lldb intentionally
+ // disobeys these rules so that the intended overload can be found
+ // by only removing duplicates if they have the same type.
+ }
+ void test_lookup_at_nested_ns_scope_after_using()
+ {
+ // BP_nested_ns_scope_after_using
+ using A::func;
+ printf("at nested ns scope after using: func() = %d\n", func()); // eval func(), exp: 3
+ }
+ }
+}
+int A::foo()
+{
+ printf("A::foo()\n");
+ return 42;
+}
+int A::func(int a)
+{
+ printf("A::func(int)\n");
+ return a + 3;
+}
+void A::test_lookup_at_ns_scope()
+{
+ // BP_ns_scope
+ printf("at nested ns scope: func() = %d\n", func()); // eval func(), exp: 3
+ printf("at nested ns scope: func(10) = %d\n", func(10)); // eval func(10), exp: 13
+ printf("at nested ns scope: foo() = %d\n", foo()); // eval foo(), exp: 42
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/namespace/ns3.cpp b/packages/Python/lldbsuite/test/lang/cpp/namespace/ns3.cpp
new file mode 100644
index 000000000000..10b0df784225
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/namespace/ns3.cpp
@@ -0,0 +1,27 @@
+//===-- ns3.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include "ns.h"
+extern int func();
+
+// Note: the following function must be before the using.
+void test_lookup_before_using_directive()
+{
+ // BP_before_using_directive
+ printf("before using directive: func() = %d\n", func()); // eval func(), exp: 1
+}
+using namespace A;
+void test_lookup_after_using_directive()
+{
+ // BP_after_using_directive
+ //printf("func() = %d\n", func()); // eval func(), exp: error, amiguous
+ printf("after using directive: func2() = %d\n", func2()); // eval func2(), exp: 3
+ printf("after using directive: ::func() = %d\n", ::func()); // eval ::func(), exp: 1
+ printf("after using directive: B::func() = %d\n", B::func()); // eval B::func(), exp: 4
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/nsimport/Makefile b/packages/Python/lldbsuite/test/lang/cpp/nsimport/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/nsimport/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/nsimport/TestCppNsImport.py b/packages/Python/lldbsuite/test/lang/cpp/nsimport/TestCppNsImport.py
new file mode 100644
index 000000000000..97e9e27a6e98
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/nsimport/TestCppNsImport.py
@@ -0,0 +1,101 @@
+"""
+Tests imported namespaces in C++.
+"""
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TestCppNsImport(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureFreeBSD("llvm.org/pr25925")
+ @expectedFailureGcc(None, ['>=', '4.9'])
+ def test_with_run_command(self):
+ """Tests imported namespaces in C++."""
+ self.build()
+
+ # Get main source file
+ src_file = "main.cpp"
+ src_file_spec = lldb.SBFileSpec(src_file)
+ self.assertTrue(src_file_spec.IsValid(), "Main source file")
+
+ # Get the path of the executable
+ cwd = os.getcwd()
+ exe_file = "a.out"
+ exe_path = os.path.join(cwd, exe_file)
+
+ # Load the executable
+ target = self.dbg.CreateTarget(exe_path)
+ self.assertTrue(target.IsValid(), VALID_TARGET)
+
+ # Break on main function
+ break_0 = target.BreakpointCreateBySourceRegex("// break 0", src_file_spec)
+ self.assertTrue(break_0.IsValid() and break_0.GetNumLocations() >= 1, VALID_BREAKPOINT)
+ break_1 = target.BreakpointCreateBySourceRegex("// break 1", src_file_spec)
+ self.assertTrue(break_1.IsValid() and break_1.GetNumLocations() >= 1, VALID_BREAKPOINT)
+
+ # Launch the process
+ args = None
+ env = None
+ process = target.LaunchSimple(args, env, self.get_process_working_directory())
+ self.assertTrue(process.IsValid(), PROCESS_IS_VALID)
+
+ # Get the thread of the process
+ self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+
+ # Get current fream of the thread at the breakpoint
+ frame = thread.GetSelectedFrame()
+
+ # Test imported namespaces
+ test_result = frame.EvaluateExpression("n")
+ self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 1, "n = 1")
+
+ test_result = frame.EvaluateExpression("N::n")
+ self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 1, "N::n = 1")
+
+ test_result = frame.EvaluateExpression("nested")
+ self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 3, "nested = 3")
+
+ test_result = frame.EvaluateExpression("anon")
+ self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 2, "anon = 2")
+
+ test_result = frame.EvaluateExpression("global")
+ self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 4, "global = 4")
+
+ test_result = frame.EvaluateExpression("fun_var")
+ self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 9, "fun_var = 9")
+
+ test_result = frame.EvaluateExpression("Fun::fun_var")
+ self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 0, "Fun::fun_var = 0")
+
+ test_result = frame.EvaluateExpression("not_imported")
+ self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 35, "not_imported = 35")
+
+ # Currently there is no way to distinguish between "::imported" and "imported" in ClangExpressionDeclMap so this fails
+ #test_result = frame.EvaluateExpression("::imported")
+ #self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 89, "::imported = 89")
+
+ test_result = frame.EvaluateExpression("Imported::imported")
+ self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 99, "Imported::imported = 99")
+
+ test_result = frame.EvaluateExpression("imported")
+ self.assertTrue(test_result.IsValid() and test_result.GetError().Fail(), "imported is ambiguous")
+
+ test_result = frame.EvaluateExpression("single")
+ self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 3, "single = 3")
+
+ # Continue to second breakpoint
+ process.Continue()
+
+ # Get the thread of the process
+ self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+
+ # Get current fream of the thread at the breakpoint
+ frame = thread.GetSelectedFrame()
+
+ # Test function inside namespace
+ test_result = frame.EvaluateExpression("fun_var")
+ self.assertTrue(test_result.IsValid() and test_result.GetValueAsSigned() == 5, "fun_var = 5")
diff --git a/packages/Python/lldbsuite/test/lang/cpp/nsimport/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/nsimport/main.cpp
new file mode 100644
index 000000000000..e125ebaa2430
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/nsimport/main.cpp
@@ -0,0 +1,72 @@
+namespace N
+{
+ int n;
+}
+
+namespace
+{
+ int anon;
+}
+
+namespace Nested
+{
+ namespace
+ {
+ int nested;
+ }
+}
+
+namespace Global
+{
+ int global;
+}
+
+namespace Fun
+{
+ int fun_var;
+ int fun()
+ {
+ fun_var = 5;
+ return 0; // break 1
+ }
+}
+
+namespace Single
+{
+ int single = 3;
+}
+
+namespace NotImportedBefore
+{
+ int not_imported = 45;
+}
+
+using namespace Global;
+
+int not_imported = 35;
+int fun_var = 9;
+
+namespace NotImportedAfter
+{
+ int not_imported = 55;
+}
+
+namespace Imported
+{
+ int imported = 99;
+}
+
+int imported = 89;
+
+int main()
+{
+ using namespace N;
+ using namespace Nested;
+ using namespace Imported;
+ using Single::single;
+ n = 1;
+ anon = 2;
+ nested = 3;
+ global = 4;
+ return Fun::fun(); // break 0
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/Makefile b/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/Makefile
new file mode 100644
index 000000000000..a8d5c4eb0268
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp static-a.cpp static-b.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/TestOverloadedFunctions.py b/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/TestOverloadedFunctions.py
new file mode 100644
index 000000000000..d485dcd0f652
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/TestOverloadedFunctions.py
@@ -0,0 +1,36 @@
+"""
+Tests that functions with the same name are resolved correctly.
+"""
+
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class CPPStaticMethodsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ TestBase.setUp(self)
+ self.line = line_number('main.cpp', '// breakpoint')
+
+ @expectedFailureWindows("llvm.org/pr24489: Name lookup not working correctly on Windows")
+ def test_with_run_command(self):
+ """Test that functions with the same name are resolved correctly"""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("process launch", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list",
+ STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped', 'stop reason = breakpoint'])
+
+ self.expect("expression -- Dump(myB)",
+ startstr = "(int) $0 = 2")
+
+ self.expect("expression -- Static()",
+ startstr = "(int) $1 = 1")
diff --git a/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/main.cpp
new file mode 100644
index 000000000000..250e2cd1d96c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/main.cpp
@@ -0,0 +1,43 @@
+#include <stdio.h>
+
+struct A {
+ int aa;
+ char ab;
+};
+
+struct B {
+ int ba;
+ int bb;
+};
+
+struct C {
+ int ca;
+ int cb;
+};
+
+int Dump (A &a)
+{
+ return 1;
+}
+
+int Dump (B &b)
+{
+ return 2;
+}
+
+int Dump (C &c)
+{
+ return 3;
+}
+
+extern int CallStaticA();
+extern int CallStaticB();
+
+int main()
+{
+ A myA;
+ B myB;
+ C myC;
+
+ printf("%d\n", CallStaticA() + CallStaticB()); // breakpoint
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/static-a.cpp b/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/static-a.cpp
new file mode 100644
index 000000000000..7250fa4bed5e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/static-a.cpp
@@ -0,0 +1,9 @@
+static int Static()
+{
+ return 1;
+}
+
+int CallStaticA()
+{
+ return Static();
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/static-b.cpp b/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/static-b.cpp
new file mode 100644
index 000000000000..90a20f69e6db
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/overloaded-functions/static-b.cpp
@@ -0,0 +1,9 @@
+static int Static()
+{
+ return 1;
+}
+
+int CallStaticB()
+{
+ return Static();
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/rdar12991846/Makefile b/packages/Python/lldbsuite/test/lang/cpp/rdar12991846/Makefile
new file mode 100644
index 000000000000..1476447db355
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/rdar12991846/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+CFLAGS := -g -O0 -std=c++11
+
+clean: OBJECTS+=$(wildcard main.d.*)
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/rdar12991846/TestRdar12991846.py b/packages/Python/lldbsuite/test/lang/cpp/rdar12991846/TestRdar12991846.py
new file mode 100644
index 000000000000..636a82b425da
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/rdar12991846/TestRdar12991846.py
@@ -0,0 +1,85 @@
+# coding=utf8
+"""
+Test that the expression parser returns proper Unicode strings.
+"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+# this test case fails because of rdar://12991846
+# the expression parser does not deal correctly with Unicode expressions
+# e.g.
+#(lldb) expr L"Hello"
+#(const wchar_t [6]) $0 = {
+# [0] = \0\0\0\0
+# [1] = \0\0\0\0
+# [2] = \0\0\0\0
+# [3] = \0\0\0\0
+# [4] = H\0\0\0
+# [5] = e\0\0\0
+#}
+
+class Rdar12991846TestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @unittest2.expectedFailure("rdar://18684408")
+ @expectedFailureWindows("llvm.org/pr24489: Name lookup not working correctly on Windows")
+ def test_expr1(self):
+ """Test that the expression parser returns proper Unicode strings."""
+ self.build()
+ self.rdar12991846(expr=1)
+
+ @unittest2.expectedFailure("rdar://18684408")
+ @expectedFailureWindows("llvm.org/pr24489: Name lookup not working correctly on Windows")
+ def test_expr2(self):
+ """Test that the expression parser returns proper Unicode strings."""
+ self.build()
+ self.rdar12991846(expr=2)
+
+ @unittest2.expectedFailure("rdar://18684408")
+ @expectedFailureWindows("llvm.org/pr24489: Name lookup not working correctly on Windows")
+ def test_expr3(self):
+ """Test that the expression parser returns proper Unicode strings."""
+ self.build()
+ self.rdar12991846(expr=3)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break for main.cpp.
+ self.source = 'main.cpp'
+ self.line = line_number(self.source, '// Set break point at this line.')
+
+ def rdar12991846(self, expr=None):
+ """Test that the expression parser returns proper Unicode strings."""
+ if self.getArchitecture() in ['i386']:
+ self.skipTest("Skipping because this test is known to crash on i386")
+
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Break on the struct declration statement in main.cpp.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ if not process:
+ self.fail("SBTarget.Launch() failed")
+
+ if expr == 1: self.expect('expression L"hello"', substrs = ['hello'])
+
+ if expr == 2: self.expect('expression u"hello"', substrs = ['hello'])
+
+ if expr == 3: self.expect('expression U"hello"', substrs = ['hello'])
diff --git a/packages/Python/lldbsuite/test/lang/cpp/rdar12991846/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/rdar12991846/main.cpp
new file mode 100644
index 000000000000..fda951a78991
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/rdar12991846/main.cpp
@@ -0,0 +1,21 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+
+int main (int argc, char const *argv[])
+{
+ auto cs16 = u"hello world ྒྙྐ";
+ auto cs32 = U"hello world ྒྙྐ";
+ char16_t *s16 = (char16_t *)u"ﺸﺵۻ";
+ char32_t *s32 = (char32_t *)U"ЕЙРГЖО";
+ s32 = nullptr; // Set break point at this line.
+ s32 = (char32_t *)U"෴";
+ s16 = (char16_t *)u"色ハ匂ヘト散リヌルヲ";
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/Makefile b/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/Makefile
new file mode 100644
index 000000000000..3a1d8a579350
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+CXXFLAGS += -std=c++11
+
+include $(LEVEL)/Makefile.rules \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/TestRvalueReferences.py b/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/TestRvalueReferences.py
new file mode 100644
index 000000000000..d02c34ecb0fe
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/TestRvalueReferences.py
@@ -0,0 +1,49 @@
+"""
+Tests that rvalue references are supported in C++
+"""
+
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class RvalueReferencesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ #rdar://problem/11479676
+ @expectedFailureIcc("ICC (13.1, 14-beta) do not emit DW_TAG_rvalue_reference_type.")
+ @expectedFailureWindows("llvm.org/pr24489: Name lookup not working correctly on Windows")
+ def test_with_run_command(self):
+ """Test that rvalues are supported in the C++ expression parser"""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ self.set_breakpoint(line_number('main.cpp', '// breakpoint 1'))
+ self.set_breakpoint(line_number('main.cpp', '// breakpoint 2'))
+
+ self.runCmd("process launch", RUN_SUCCEEDED)
+
+ # Note that clang as of r187480 doesn't emit DW_TAG_const_type, unlike gcc 4.8.1
+ # With gcc 4.8.1, lldb reports the type as (int &&const)
+ self.expect("frame variable i",
+ startstr = "(int &&",
+ substrs = ["i = 0x", "&i = 3"])
+
+ self.expect("expression -- i",
+ startstr = "(int) ",
+ substrs = ["3"])
+
+ self.expect("breakpoint delete 1")
+
+ self.runCmd("process continue")
+
+ self.expect("expression -- foo(2)")
+
+ self.expect("expression -- int &&j = 3; foo(j)",
+ error = True)
+
+ self.expect("expression -- int &&k = 6; k",
+ startstr = "(int) $1 = 6")
+
+ def set_breakpoint(self, line):
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", line, num_expected_locations=1, loc_exact=True)
diff --git a/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/main.cpp
new file mode 100644
index 000000000000..6da34c73f101
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/rvalue-references/main.cpp
@@ -0,0 +1,12 @@
+#include <stdio.h>
+
+void foo (int &&i)
+{
+ printf("%d\n", i); // breakpoint 1
+}
+
+int main()
+{
+ foo(3);
+ return 0; // breakpoint 2
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/scope/Makefile b/packages/Python/lldbsuite/test/lang/cpp/scope/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/scope/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/scope/TestCppScope.py b/packages/Python/lldbsuite/test/lang/cpp/scope/TestCppScope.py
new file mode 100644
index 000000000000..66d4a1591575
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/scope/TestCppScope.py
@@ -0,0 +1,67 @@
+"""
+Test scopes in C++.
+"""
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TestCppScopes(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureDarwin
+ @expectedFailureWindows("llvm.org/pr24764")
+ def test_with_run_command(self):
+ self.build()
+
+ # Get main source file
+ src_file = "main.cpp"
+ src_file_spec = lldb.SBFileSpec(src_file)
+ self.assertTrue(src_file_spec.IsValid(), "Main source file")
+
+ # Get the path of the executable
+ cwd = os.getcwd()
+ exe_file = "a.out"
+ exe_path = os.path.join(cwd, exe_file)
+
+ # Load the executable
+ target = self.dbg.CreateTarget(exe_path)
+ self.assertTrue(target.IsValid(), VALID_TARGET)
+
+ # Break on main function
+ main_breakpoint = target.BreakpointCreateBySourceRegex("// break here", src_file_spec)
+ self.assertTrue(main_breakpoint.IsValid() and main_breakpoint.GetNumLocations() >= 1, VALID_BREAKPOINT)
+
+ # Launch the process
+ args = None
+ env = None
+ process = target.LaunchSimple(args, env, self.get_process_working_directory())
+ self.assertTrue(process.IsValid(), PROCESS_IS_VALID)
+
+ # Get the thread of the process
+ self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+
+ # Get current fream of the thread at the breakpoint
+ frame = thread.GetSelectedFrame()
+
+ # Test result for scopes of variables
+
+ global_variables = frame.GetVariables(True, True, True, False)
+ global_variables_assert = {
+ 'A::a': 1111,
+ 'B::a': 2222,
+ 'C::a': 3333,
+ '::a': 4444,
+ 'a': 4444
+ }
+
+ self.assertTrue(global_variables.GetSize() == 4, "target variable returns all variables")
+ for variable in global_variables:
+ name = variable.GetName()
+ self.assertTrue(name in global_variables_assert, "target variable returns wrong variable " + name)
+
+ for name in global_variables_assert:
+ value = frame.EvaluateExpression(name)
+ assert_value = global_variables_assert[name]
+ self.assertTrue(value.IsValid() and value.GetValueAsSigned() == assert_value, name + " = " + str(assert_value))
diff --git a/packages/Python/lldbsuite/test/lang/cpp/scope/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/scope/main.cpp
new file mode 100644
index 000000000000..da5d7ed529d1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/scope/main.cpp
@@ -0,0 +1,25 @@
+class A {
+public:
+ static int a;
+ int b;
+};
+
+class B {
+public:
+ static int a;
+ int b;
+};
+
+struct C {
+ static int a;
+};
+
+int A::a = 1111;
+int B::a = 2222;
+int C::a = 3333;
+int a = 4444;
+
+int main() // break here
+{
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/signed_types/Makefile b/packages/Python/lldbsuite/test/lang/cpp/signed_types/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/signed_types/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/signed_types/TestSignedTypes.py b/packages/Python/lldbsuite/test/lang/cpp/signed_types/TestSignedTypes.py
new file mode 100644
index 000000000000..51e6d4579e28
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/signed_types/TestSignedTypes.py
@@ -0,0 +1,60 @@
+"""
+Test that variables with signed types display correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class UnsignedTypesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.source = 'main.cpp'
+ self.line = line_number(self.source, '// Set break point at this line.')
+
+ def test(self):
+ """Test that variables with signed types display correctly."""
+ self.build()
+
+ # Run in synchronous mode
+ self.dbg.SetAsync(False)
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget("a.out")
+ self.assertTrue(target, VALID_TARGET)
+
+ lldbutil.run_break_set_by_file_and_line (self, self.source, self.line, num_expected_locations=1, loc_exact=True)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped', 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ # Execute the assignment statement.
+ self.runCmd("thread step-over")
+
+ # Test that signed types display correctly.
+ self.expect("frame variable --show-types --no-args", VARIABLES_DISPLAYED_CORRECTLY,
+ patterns = ["\((short int|short)\) the_signed_short = 99",
+ "\((signed char|char)\) the_signed_char = 'c'"],
+ substrs = ["(int) the_signed_int = 99",
+ "(long) the_signed_long = 99",
+ "(long long) the_signed_long_long = 99"])
diff --git a/packages/Python/lldbsuite/test/lang/cpp/signed_types/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/signed_types/main.cpp
new file mode 100644
index 000000000000..dbf3606aeba8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/signed_types/main.cpp
@@ -0,0 +1,33 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+int main (int argc, char const *argv[])
+{
+ char the_char = 'c';
+ short the_short = 'c';
+ wchar_t the_wchar_t = 'c';
+ int the_int = 'c';
+ long the_long = 'c';
+ long long the_long_long = 'c';
+
+ signed char the_signed_char = 'c';
+ signed short the_signed_short = 'c';
+ signed int the_signed_int = 'c';
+ signed long the_signed_long = 'c';
+ signed long long the_signed_long_long = 'c';
+ puts(""); // Set break point at this line.
+ return the_char - the_signed_char +
+ the_short - the_signed_short +
+ the_int - the_signed_int +
+ the_long - the_signed_long +
+ the_long_long - the_signed_long_long; //// break $source:$line; c
+ //// var the_int
+ //// val -set 22 1
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/static_members/Makefile b/packages/Python/lldbsuite/test/lang/cpp/static_members/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/static_members/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/static_members/TestCPPStaticMembers.py b/packages/Python/lldbsuite/test/lang/cpp/static_members/TestCPPStaticMembers.py
new file mode 100644
index 000000000000..1c41b1b6f571
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/static_members/TestCPPStaticMembers.py
@@ -0,0 +1,59 @@
+"""
+Tests that C++ member and static variables have correct layout and scope.
+"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class CPPStaticMembersTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @unittest2.expectedFailure # llvm.org/pr15401
+ @expectedFailureWindows("llvm.org/pr21765")
+ def test_with_run_command(self):
+ """Test that member variables have the correct layout, scope and qualifiers when stopped inside and outside C++ methods"""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ self.set_breakpoint(line_number('main.cpp', '// breakpoint 1'))
+ self.set_breakpoint(line_number('main.cpp', '// breakpoint 2'))
+
+ self.runCmd("process launch", RUN_SUCCEEDED)
+ self.expect("expression my_a.access()",
+ startstr = "(long) $0 = 10")
+
+ self.expect("expression my_a.m_a",
+ startstr = "(short) $1 = 1")
+
+ # Note: SymbolFileDWARF::ParseChildMembers doesn't call AddFieldToRecordType, consistent with clang's AST layout.
+ self.expect("expression my_a.s_d",
+ startstr = "(int) $2 = 4")
+
+ self.expect("expression my_a.s_b",
+ startstr = "(long) $3 = 2")
+
+ self.expect("expression A::s_b",
+ startstr = "(long) $4 = 2")
+
+ # should not be available in global scope
+ self.expect("expression s_d",
+ startstr = "error: use of undeclared identifier 's_d'")
+
+ self.runCmd("process continue")
+ self.expect("expression m_c",
+ startstr = "(char) $5 = \'\\x03\'")
+
+ self.expect("expression s_b",
+ startstr = "(long) $6 = 2")
+
+ self.runCmd("process continue")
+
+ def set_breakpoint(self, line):
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", line, num_expected_locations=1, loc_exact=False)
diff --git a/packages/Python/lldbsuite/test/lang/cpp/static_members/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/static_members/main.cpp
new file mode 100644
index 000000000000..7ccc2f9a328b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/static_members/main.cpp
@@ -0,0 +1,36 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+
+struct A
+{
+ short m_a;
+ static long s_b;
+ char m_c;
+ static int s_d;
+
+ long access() {
+ return m_a + s_b + m_c + s_d; // breakpoint 2
+ }
+};
+
+long A::s_b = 2;
+int A::s_d = 4;
+
+int main()
+{
+ A my_a;
+ my_a.m_a = 1;
+ my_a.m_c = 3;
+
+ my_a.access(); // breakpoint 1
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/lang/cpp/static_methods/Makefile b/packages/Python/lldbsuite/test/lang/cpp/static_methods/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/static_methods/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/static_methods/TestCPPStaticMethods.py b/packages/Python/lldbsuite/test/lang/cpp/static_methods/TestCPPStaticMethods.py
new file mode 100644
index 000000000000..dba556431e39
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/static_methods/TestCPPStaticMethods.py
@@ -0,0 +1,36 @@
+"""
+Tests expressions that distinguish between static and non-static methods.
+"""
+
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class CPPStaticMethodsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ TestBase.setUp(self)
+ self.line = line_number('main.cpp', '// Break at this line')
+
+ @expectedFailureWindows
+ def test_with_run_command(self):
+ """Test that static methods are properly distinguished from regular methods"""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("process launch", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list",
+ STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped', 'stop reason = breakpoint'])
+
+ self.expect("expression -- A::getStaticValue()",
+ startstr = "(int) $0 = 5")
+
+ self.expect("expression -- my_a.getMemberValue()",
+ startstr = "(int) $1 = 3")
diff --git a/packages/Python/lldbsuite/test/lang/cpp/static_methods/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/static_methods/main.cpp
new file mode 100644
index 000000000000..5141a407d111
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/static_methods/main.cpp
@@ -0,0 +1,38 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+
+class A
+{
+public:
+ static int getStaticValue();
+ int getMemberValue();
+ int a;
+};
+
+int A::getStaticValue()
+{
+ return 5;
+}
+
+int A::getMemberValue()
+{
+ return a;
+}
+
+int main()
+{
+ A my_a;
+
+ my_a.a = 3;
+
+ printf("%d\n", A::getStaticValue()); // Break at this line
+ printf("%d\n", my_a.getMemberValue());
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/stl/Makefile b/packages/Python/lldbsuite/test/lang/cpp/stl/Makefile
new file mode 100644
index 000000000000..f61a6300a994
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/stl/Makefile
@@ -0,0 +1,15 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+CFLAGS := -g -O0
+
+clean: OBJECTS+=$(wildcard main.d.*)
+
+# clang-3.5+ outputs FullDebugInfo by default for Darwin/FreeBSD
+# targets. Other targets do not, which causes this test to fail.
+# This flag enables FullDebugInfo for all targets.
+ifneq (,$(findstring clang,$(CC)))
+ CFLAGS_EXTRAS += -fno-limit-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/stl/TestSTL.py b/packages/Python/lldbsuite/test/lang/cpp/stl/TestSTL.py
new file mode 100644
index 000000000000..6dba1398947e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/stl/TestSTL.py
@@ -0,0 +1,118 @@
+"""
+Test some expressions involving STL data types.
+"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class STLTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.source = 'main.cpp'
+ self.line = line_number(self.source, '// Set break point at this line.')
+
+ # rdar://problem/10400981
+ @unittest2.expectedFailure
+ def test(self):
+ """Test some expressions involving STL data types."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # The following two lines, if uncommented, will enable loggings.
+ #self.ci.HandleCommand("log enable -f /tmp/lldb.log lldb default", res)
+ #self.assertTrue(res.Succeeded())
+
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # rdar://problem/8543077
+ # test/stl: clang built binaries results in the breakpoint locations = 3,
+ # is this a problem with clang generated debug info?
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Stop at 'std::string hello_world ("Hello World!");'.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['main.cpp:%d' % self.line,
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ # Now try some expressions....
+
+ self.runCmd('expr for (int i = 0; i < hello_world.length(); ++i) { (void)printf("%c\\n", hello_world[i]); }')
+
+ # rdar://problem/10373783
+ # rdar://problem/10400981
+ self.expect('expr associative_array.size()',
+ substrs = [' = 3'])
+ self.expect('expr associative_array.count(hello_world)',
+ substrs = [' = 1'])
+ self.expect('expr associative_array[hello_world]',
+ substrs = [' = 1'])
+ self.expect('expr associative_array["hello"]',
+ substrs = [' = 2'])
+
+ @expectedFailureIcc # icc 13.1 and 14-beta do not emit DW_TAG_template_type_parameter
+ @add_test_categories(['pyapi'])
+ def test_SBType_template_aspects(self):
+ """Test APIs for getting template arguments from an SBType."""
+ self.build()
+ exe = os.path.join(os.getcwd(), 'a.out')
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Create the breakpoint inside function 'main'.
+ breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Get Frame #0.
+ self.assertTrue(process.GetState() == lldb.eStateStopped)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
+ frame0 = thread.GetFrameAtIndex(0)
+
+ # Get the type for variable 'associative_array'.
+ associative_array = frame0.FindVariable('associative_array')
+ self.DebugSBValue(associative_array)
+ self.assertTrue(associative_array, VALID_VARIABLE)
+ map_type = associative_array.GetType()
+ self.DebugSBType(map_type)
+ self.assertTrue(map_type, VALID_TYPE)
+ num_template_args = map_type.GetNumberOfTemplateArguments()
+ self.assertTrue(num_template_args > 0)
+
+ # We expect the template arguments to contain at least 'string' and 'int'.
+ expected_types = { 'string': False, 'int': False }
+ for i in range(num_template_args):
+ t = map_type.GetTemplateArgumentType(i)
+ self.DebugSBType(t)
+ self.assertTrue(t, VALID_TYPE)
+ name = t.GetName()
+ if 'string' in name:
+ expected_types['string'] = True
+ elif 'int' == name:
+ expected_types['int'] = True
+
+ # Check that both entries of the dictionary have 'True' as the value.
+ self.assertTrue(all(expected_types.values()))
diff --git a/packages/Python/lldbsuite/test/lang/cpp/stl/TestStdCXXDisassembly.py b/packages/Python/lldbsuite/test/lang/cpp/stl/TestStdCXXDisassembly.py
new file mode 100644
index 000000000000..d7435c467274
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/stl/TestStdCXXDisassembly.py
@@ -0,0 +1,111 @@
+"""
+Test the lldb disassemble command on lib stdc++.
+"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class StdCXXDisassembleTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ # rdar://problem/8504895
+ # Crash while doing 'disassemble -n "-[NSNumber descriptionWithLocale:]"
+ @unittest2.skipIf(TestBase.skipLongRunningTest(), "Skip this long running test")
+ def test_stdcxx_disasm(self):
+ """Do 'disassemble' on each and every 'Code' symbol entry from the std c++ lib."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # rdar://problem/8543077
+ # test/stl: clang built binaries results in the breakpoint locations = 3,
+ # is this a problem with clang generated debug info?
+ #
+ # Break on line 13 of main.cpp.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Now let's get the target as well as the process objects.
+ target = self.dbg.GetSelectedTarget()
+ process = target.GetProcess()
+
+ # The process should be in a 'stopped' state.
+ self.expect(str(process), STOPPED_DUE_TO_BREAKPOINT, exe=False,
+ substrs = ["a.out",
+ "stopped"])
+
+ # Disassemble the functions on the call stack.
+ self.runCmd("thread backtrace")
+ thread = process.GetThreadAtIndex(0)
+ depth = thread.GetNumFrames()
+ for i in range(depth - 1):
+ frame = thread.GetFrameAtIndex(i)
+ function = frame.GetFunction()
+ if function.GetName():
+ self.runCmd("disassemble -n '%s'" % function.GetName())
+
+ lib_stdcxx = "FAILHORRIBLYHERE"
+ # Iterate through the available modules, looking for stdc++ library...
+ for i in range(target.GetNumModules()):
+ module = target.GetModuleAtIndex(i)
+ fs = module.GetFileSpec()
+ if (fs.GetFilename().startswith("libstdc++") or fs.GetFilename().startswith("libc++")):
+ lib_stdcxx = str(fs)
+ break
+
+ # At this point, lib_stdcxx is the full path to the stdc++ library and
+ # module is the corresponding SBModule.
+
+ self.expect(lib_stdcxx, "Libraray StdC++ is located", exe=False,
+ substrs = ["lib"])
+
+ self.runCmd("image dump symtab '%s'" % lib_stdcxx)
+ raw_output = self.res.GetOutput()
+ # Now, look for every 'Code' symbol and feed its load address into the
+ # command: 'disassemble -s load_address -e end_address', where the
+ # end_address is taken from the next consecutive 'Code' symbol entry's
+ # load address.
+ #
+ # The load address column comes after the file address column, with both
+ # looks like '0xhhhhhhhh', i.e., 8 hexadecimal digits.
+ codeRE = re.compile(r"""
+ \ Code\ {9} # ' Code' followed by 9 SPCs,
+ 0x[0-9a-f]{16} # the file address column, and
+ \ # a SPC, and
+ (0x[0-9a-f]{16}) # the load address column, and
+ .* # the rest.
+ """, re.VERBOSE)
+ # Maintain a start address variable; if we arrive at a consecutive Code
+ # entry, then the load address of the that entry is fed as the end
+ # address to the 'disassemble -s SA -e LA' command.
+ SA = None
+ for line in raw_output.split(os.linesep):
+ match = codeRE.search(line)
+ if match:
+ LA = match.group(1)
+ if self.TraceOn():
+ print("line:", line)
+ print("load address:", LA)
+ print("SA:", SA)
+ if SA and LA:
+ if int(LA, 16) > int(SA, 16):
+ self.runCmd("disassemble -s %s -e %s" % (SA, LA))
+ SA = LA
+ else:
+ # This entry is not a Code entry. Reset SA = None.
+ SA = None
diff --git a/packages/Python/lldbsuite/test/lang/cpp/stl/cmds.txt b/packages/Python/lldbsuite/test/lang/cpp/stl/cmds.txt
new file mode 100644
index 000000000000..9c9c2e3db57b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/stl/cmds.txt
@@ -0,0 +1,3 @@
+b main.cpp:6
+continue
+var
diff --git a/packages/Python/lldbsuite/test/lang/cpp/stl/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/stl/main.cpp
new file mode 100644
index 000000000000..cfdb7b2d3db5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/stl/main.cpp
@@ -0,0 +1,30 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <cstdio>
+#include <iostream>
+#include <string>
+#include <map>
+int main (int argc, char const *argv[])
+{
+ std::string hello_world ("Hello World!");
+ std::cout << hello_world << std::endl;
+ std::cout << hello_world.length() << std::endl;
+ std::cout << hello_world[11] << std::endl;
+
+ std::map<std::string, int> associative_array;
+ std::cout << "size of upon construction associative_array: " << associative_array.size() << std::endl;
+ associative_array[hello_world] = 1;
+ associative_array["hello"] = 2;
+ associative_array["world"] = 3;
+
+ std::cout << "size of associative_array: " << associative_array.size() << std::endl;
+ printf("associative_array[\"hello\"]=%d\n", associative_array["hello"]);
+
+ printf("before returning....\n"); // Set break point at this line.
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/this/Makefile b/packages/Python/lldbsuite/test/lang/cpp/this/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/this/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/this/TestCPPThis.py b/packages/Python/lldbsuite/test/lang/cpp/this/TestCPPThis.py
new file mode 100644
index 000000000000..07cc2e8e9788
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/this/TestCPPThis.py
@@ -0,0 +1,53 @@
+"""
+Tests that C++ member and static variables are available where they should be.
+"""
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class CPPThisTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ #rdar://problem/9962849
+ @expectedFailureGcc # llvm.org/pr15439 The 'this' pointer isn't available during expression evaluation when stopped in an inlined member function.
+ @expectedFailureIcc # ICC doesn't emit correct DWARF inline debug info for inlined member functions
+ @expectedFailureWindows("llvm.org/pr24489: Name lookup not working correctly on Windows")
+ @expectedFailureWindows("llvm.org/pr24490: We shouldn't be using platform-specific names like `getpid` in tests")
+ @expectedFlakeyClang(bugnumber='llvm.org/pr23012', compiler_version=['>=','3.6']) # failed with totclang - clang3.7
+ def test_with_run_command(self):
+ """Test that the appropriate member variables are available when stopped in C++ static, inline, and const methods"""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ self.set_breakpoint(line_number('main.cpp', '// breakpoint 1'))
+ self.set_breakpoint(line_number('main.cpp', '// breakpoint 2'))
+ self.set_breakpoint(line_number('main.cpp', '// breakpoint 3'))
+ self.set_breakpoint(line_number('main.cpp', '// breakpoint 4'))
+
+ self.runCmd("process launch", RUN_SUCCEEDED)
+
+ self.expect("expression -- m_a = 2",
+ startstr = "(int) $0 = 2")
+
+ self.runCmd("process continue")
+
+ # This would be disallowed if we enforced const. But we don't.
+ self.expect("expression -- m_a = 2",
+ startstr = "(int) $1 = 2")
+
+ self.expect("expression -- (int)getpid(); m_a",
+ startstr = "(int) $2 = 2")
+
+ self.runCmd("process continue")
+
+ self.expect("expression -- s_a",
+ startstr = "(int) $3 = 5")
+
+ self.runCmd("process continue")
+
+ self.expect("expression -- m_a",
+ startstr = "(int) $4 = 2")
+
+ def set_breakpoint(self, line):
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", line, num_expected_locations=1, loc_exact=False)
diff --git a/packages/Python/lldbsuite/test/lang/cpp/this/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/this/main.cpp
new file mode 100644
index 000000000000..4448a5cadf57
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/this/main.cpp
@@ -0,0 +1,53 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+
+template <class T> class A
+{
+public:
+ void accessMember(T a);
+ T accessMemberConst() const;
+ static int accessStaticMember();
+
+ void accessMemberInline(T a) __attribute__ ((always_inline))
+ {
+ m_a = a; // breakpoint 4
+ }
+
+ T m_a;
+ static int s_a;
+};
+
+template <class T> int A<T>::s_a = 5;
+
+template <class T> void A<T>::accessMember(T a)
+{
+ m_a = a; // breakpoint 1
+}
+
+template <class T> T A<T>::accessMemberConst() const
+{
+ return m_a; // breakpoint 2
+}
+
+template <class T> int A<T>::accessStaticMember()
+{
+ return s_a; // breakpoint 3
+}
+
+int main()
+{
+ A<int> my_a;
+
+ my_a.accessMember(3);
+ my_a.accessMemberConst();
+ A<int>::accessStaticMember();
+ my_a.accessMemberInline(5);
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/unique-types/Makefile b/packages/Python/lldbsuite/test/lang/cpp/unique-types/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/unique-types/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/unique-types/TestUniqueTypes.py b/packages/Python/lldbsuite/test/lang/cpp/unique-types/TestUniqueTypes.py
new file mode 100644
index 000000000000..2cbb1a191e68
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/unique-types/TestUniqueTypes.py
@@ -0,0 +1,62 @@
+"""
+Test that template instaniations of std::vector<long> and <short> in the same module have the correct types.
+"""
+
+from __future__ import print_function
+
+
+
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class UniqueTypesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number inside main.cpp.
+ self.line = line_number("main.cpp",
+ "// Set breakpoint here to verify that std::vector 'longs' and 'shorts' have unique types.")
+
+ def test(self):
+ """Test for unique types of std::vector<long> and std::vector<short>."""
+ self.build()
+
+ compiler = self.getCompiler()
+ compiler_basename = os.path.basename(compiler)
+ if "clang" in compiler_basename and int(self.getCompilerVersion().split('.')[0]) < 3:
+ self.skipTest("rdar://problem/9173060 lldb hangs while running unique-types for clang version < 3")
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Do a "frame variable --show-types longs" and verify "long" is in each line of output.
+ self.runCmd("frame variable --show-types longs")
+ output = self.res.GetOutput()
+ for x in [line.strip() for line in output.split(os.linesep)]:
+ # Skip empty line, closing brace, and messages about more variables than can be displayed.
+ if not x or x == '}' or x == '...' or "Some of your variables have more members than the debugger will show by default" in x:
+ continue
+ self.expect(x, "Expect type 'long'", exe=False,
+ substrs = ['long'])
+
+ # Do a "frame variable --show-types shorts" and verify "short" is in each line of output.
+ self.runCmd("frame variable --show-types shorts")
+ output = self.res.GetOutput()
+ for x in [line.strip() for line in output.split(os.linesep)]:
+ # Skip empty line, closing brace, and messages about more variables than can be displayed.
+ if not x or x == '}' or x == '...' or "Some of your variables have more members than the debugger will show by default" in x:
+ continue
+ self.expect(x, "Expect type 'short'", exe=False,
+ substrs = ['short'])
diff --git a/packages/Python/lldbsuite/test/lang/cpp/unique-types/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/unique-types/main.cpp
new file mode 100644
index 000000000000..c551c0e2c0d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/unique-types/main.cpp
@@ -0,0 +1,24 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <vector>
+
+#include <stdio.h>
+#include <stdint.h>
+
+int main (int argc, char const *argv[], char const *envp[])
+{
+ std::vector<long> longs;
+ std::vector<short> shorts;
+ for (int i=0; i<12; i++)
+ {
+ longs.push_back(i);
+ shorts.push_back(i);
+ }
+ return 0; // Set breakpoint here to verify that std::vector 'longs' and 'shorts' have unique types.
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/Makefile b/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/TestUnsignedTypes.py b/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/TestUnsignedTypes.py
new file mode 100644
index 000000000000..c137592558ed
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/TestUnsignedTypes.py
@@ -0,0 +1,54 @@
+"""
+Test that variables with unsigned types display correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class UnsignedTypesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def test(self):
+ """Test that variables with unsigned types display correctly."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # GCC puts a breakpoint on the last line of a multi-line expression, so
+ # if GCC is the target compiler, we cannot rely on an exact line match.
+ need_exact = "gcc" not in self.getCompiler()
+ # Break on line 19 in main() aftre the variables are assigned values.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=-1, loc_exact=need_exact)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped', 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ # Test that unsigned types display correctly.
+ self.expect("frame variable --show-types --no-args", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = "(unsigned char) the_unsigned_char = 'c'",
+ patterns = ["\((short unsigned int|unsigned short)\) the_unsigned_short = 99"],
+ substrs = ["(unsigned int) the_unsigned_int = 99",
+ "(unsigned long) the_unsigned_long = 99",
+ "(unsigned long long) the_unsigned_long_long = 99",
+ "(uint32_t) the_uint32 = 99"])
diff --git a/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/main.cpp
new file mode 100644
index 000000000000..b0d68377e983
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/unsigned_types/main.cpp
@@ -0,0 +1,22 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+int main (int argc, char const *argv[])
+{
+ typedef unsigned int uint32_t;
+ unsigned char the_unsigned_char = 'c';
+ unsigned short the_unsigned_short = 'c';
+ unsigned int the_unsigned_int = 'c';
+ unsigned long the_unsigned_long = 'c';
+ unsigned long long the_unsigned_long_long = 'c';
+ uint32_t the_uint32 = 'c';
+
+ return the_unsigned_char - the_unsigned_short + // Set break point at this line.
+ the_unsigned_int - the_unsigned_long +
+ the_unsigned_long_long - the_uint32;
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/virtual/Makefile b/packages/Python/lldbsuite/test/lang/cpp/virtual/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/virtual/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/virtual/TestVirtual.py b/packages/Python/lldbsuite/test/lang/cpp/virtual/TestVirtual.py
new file mode 100644
index 000000000000..1553a43e1a73
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/virtual/TestVirtual.py
@@ -0,0 +1,90 @@
+"""
+Test C++ virtual function and virtual inheritance.
+"""
+
+from __future__ import print_function
+
+import os, time
+import re
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+def Msg(expr, val):
+ return "'expression %s' matches the output (from compiled code): %s" % (expr, val)
+
+class CppVirtualMadness(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ # This is the pattern by design to match the "my_expr = 'value'" output from
+ # printf() stmts (see main.cpp).
+ pattern = re.compile("^([^=]*) = '([^=]*)'$")
+
+ # Assert message.
+ PRINTF_OUTPUT_GROKKED = "The printf output from compiled code is parsed correctly"
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break for main.cpp.
+ self.source = 'main.cpp'
+ self.line = line_number(self.source, '// Set first breakpoint here.')
+
+ @expectedFailureIcc('llvm.org/pr16808') # lldb does not call the correct virtual function with icc
+ @expectedFailureAll(oslist=['windows'])
+ def test_virtual_madness(self):
+ """Test that expression works correctly with virtual inheritance as well as virtual function."""
+ self.build()
+
+ # Bring the program to the point where we can issue a series of
+ # 'expression' command to compare against the golden output.
+ self.dbg.SetAsync(False)
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget("a.out")
+ self.assertTrue(target, VALID_TARGET)
+
+ # Create the breakpoint inside function 'main'.
+ breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ self.assertTrue(process.GetState() == lldb.eStateStopped)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
+
+ # First, capture the golden output from the program itself from the
+ # series of printf statements.
+ stdout = process.GetSTDOUT(1024)
+
+ self.assertIsNotNone(stdout, "Encountered an error reading the process's output")
+
+ # This golden list contains a list of "my_expr = 'value' pairs extracted
+ # from the golden output.
+ gl = []
+
+ # Scan the golden output line by line, looking for the pattern:
+ #
+ # my_expr = 'value'
+ #
+ for line in stdout.split(os.linesep):
+ match = self.pattern.search(line)
+ if match:
+ my_expr, val = match.group(1), match.group(2)
+ gl.append((my_expr, val))
+ #print("golden list:", gl)
+
+ # Now iterate through the golden list, comparing against the output from
+ # 'expression var'.
+ for my_expr, val in gl:
+
+ self.runCmd("expression %s" % my_expr)
+ output = self.res.GetOutput()
+
+ # The expression output must match the oracle.
+ self.expect(output, Msg(my_expr, val), exe=False,
+ substrs = [val])
diff --git a/packages/Python/lldbsuite/test/lang/cpp/virtual/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/virtual/main.cpp
new file mode 100644
index 000000000000..bed1422dcbdd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/virtual/main.cpp
@@ -0,0 +1,113 @@
+#include <stdio.h>
+#include <stdint.h>
+
+class A
+{
+public:
+ A () : m_pad ('c') {}
+
+ virtual ~A () {}
+
+ virtual const char * a()
+ {
+ return __PRETTY_FUNCTION__;
+ }
+
+ virtual const char * b()
+ {
+ return __PRETTY_FUNCTION__;
+ }
+
+ virtual const char * c()
+ {
+ return __PRETTY_FUNCTION__;
+ }
+protected:
+ char m_pad;
+};
+
+class AA
+{
+public:
+ AA () : m_pad('A') {}
+ virtual ~AA () {}
+
+ virtual const char * aa()
+ {
+ return __PRETTY_FUNCTION__;
+ }
+
+protected:
+ char m_pad;
+};
+
+class B : virtual public A, public AA
+{
+public:
+ B () : m_pad ('c') {}
+
+ virtual ~B () {}
+
+ virtual const char * a()
+ {
+ return __PRETTY_FUNCTION__;
+ }
+
+ virtual const char * b()
+ {
+ return __PRETTY_FUNCTION__;
+ }
+protected:
+ char m_pad;
+};
+
+class C : public B, virtual public A
+{
+public:
+ C () : m_pad ('c') {}
+
+ virtual ~C () {}
+
+ virtual const char * a()
+ {
+ return __PRETTY_FUNCTION__;
+ }
+protected:
+ char m_pad;
+};
+
+int main (int argc, char const *argv[], char const *envp[])
+{
+ A *a_as_A = new A();
+ B *b_as_B = new B();
+ A *b_as_A = b_as_B;
+ C *c_as_C = new C();
+ A *c_as_A = c_as_C;
+
+ printf ("a_as_A->a() = '%s'\n", a_as_A->a());
+ printf ("a_as_A->b() = '%s'\n", a_as_A->b());
+ printf ("a_as_A->c() = '%s'\n", a_as_A->c());
+ printf ("b_as_A->a() = '%s'\n", b_as_A->a());
+ printf ("b_as_A->b() = '%s'\n", b_as_A->b());
+ printf ("b_as_A->c() = '%s'\n", b_as_A->c());
+ printf ("b_as_B->aa() = '%s'\n", b_as_B->aa());
+ printf ("c_as_A->a() = '%s'\n", c_as_A->a());
+ printf ("c_as_A->b() = '%s'\n", c_as_A->b());
+ printf ("c_as_A->c() = '%s'\n", c_as_A->c());
+ printf ("c_as_C->aa() = '%s'\n", c_as_C->aa());
+ puts("");// Set first breakpoint here.
+ // then evaluate:
+ // expression a_as_A->a()
+ // expression a_as_A->b()
+ // expression a_as_A->c()
+ // expression b_as_A->a()
+ // expression b_as_A->b()
+ // expression b_as_A->c()
+ // expression b_as_B->aa()
+ // expression c_as_A->a()
+ // expression c_as_A->b()
+ // expression c_as_A->c()
+ // expression c_as_C->aa()
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/cpp/wchar_t/.categories b/packages/Python/lldbsuite/test/lang/cpp/wchar_t/.categories
new file mode 100644
index 000000000000..fe1da0247c62
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/wchar_t/.categories
@@ -0,0 +1 @@
+dataformatters
diff --git a/packages/Python/lldbsuite/test/lang/cpp/wchar_t/Makefile b/packages/Python/lldbsuite/test/lang/cpp/wchar_t/Makefile
new file mode 100644
index 000000000000..fe27980afe9b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/wchar_t/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+CFLAGS := -g -O0
+
+clean: OBJECTS+=$(wildcard main.d.*)
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/cpp/wchar_t/TestCxxWCharT.py b/packages/Python/lldbsuite/test/lang/cpp/wchar_t/TestCxxWCharT.py
new file mode 100644
index 000000000000..f9cdbca16e55
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/wchar_t/TestCxxWCharT.py
@@ -0,0 +1,74 @@
+#coding=utf8
+"""
+Test that C++ supports wchar_t correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class CxxWCharTTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break for main.cpp.
+ self.source = 'main.cpp'
+ self.line = line_number(self.source, '// Set break point at this line.')
+
+ def test(self):
+ """Test that C++ supports wchar_t correctly."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Break on the struct declration statement in main.cpp.
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ if not process:
+ self.fail("SBTarget.Launch() failed")
+
+ # Check that we correctly report templates on wchar_t
+ self.expect("frame variable foo_y",
+ substrs = ['(Foo<wchar_t>) foo_y = '])
+
+ # Check that we correctly report templates on int
+ self.expect("frame variable foo_x",
+ substrs = ['(Foo<int>) foo_x = '])
+
+ # Check that we correctly report wchar_t
+ self.expect("frame variable foo_y.object",
+ substrs = ['(wchar_t) foo_y.object = '])
+
+ # Check that we correctly report int
+ self.expect("frame variable foo_x.object",
+ substrs = ['(int) foo_x.object = '])
+
+ # Check that we can run expressions that return wchar_t
+ self.expect("expression L'a'",substrs = ['(wchar_t) $',"L'a'"])
+
+ # Mazel Tov if this works!
+ self.expect("frame variable mazeltov",
+ substrs = ['(const wchar_t *) mazeltov = ','L"מזל טוב"'])
+
+ self.expect("frame variable ws_NULL",substrs = ['(wchar_t *) ws_NULL = 0x0'])
+ self.expect("frame variable ws_empty",substrs = [' L""'])
+
+ self.expect("frame variable array",substrs = ['L"Hey, I\'m a super wchar_t string'])
+ self.expect("frame variable array",substrs = ['[0]'], matching=False)
+
+ self.expect('frame variable wchar_zero', substrs=["L'\\0'"])
+ self.expect('expression wchar_zero', substrs=["L'\\0'"])
diff --git a/packages/Python/lldbsuite/test/lang/cpp/wchar_t/main.cpp b/packages/Python/lldbsuite/test/lang/cpp/wchar_t/main.cpp
new file mode 100644
index 000000000000..e249c37b678f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/cpp/wchar_t/main.cpp
@@ -0,0 +1,35 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <cstring>
+
+template <typename T>
+class Foo
+{
+public:
+ Foo () : object() {}
+ Foo (T x) : object(x) {}
+ T getObject() { return object; }
+private:
+ T object;
+};
+
+
+int main (int argc, char const *argv[])
+{
+ Foo<int> foo_x('a');
+ Foo<wchar_t> foo_y(L'a');
+ const wchar_t *mazeltov = L"מזל טוב";
+ wchar_t *ws_NULL = nullptr;
+ wchar_t *ws_empty = L"";
+ wchar_t array[200], * array_source = L"Hey, I'm a super wchar_t string, éõñž";
+ wchar_t wchar_zero = (wchar_t)0;
+ memcpy(array, array_source, 39 * sizeof(wchar_t));
+ return 0; // Set break point at this line.
+}
diff --git a/packages/Python/lldbsuite/test/lang/go/expressions/TestExpressions.py b/packages/Python/lldbsuite/test/lang/go/expressions/TestExpressions.py
new file mode 100644
index 000000000000..cbd244a7e056
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/go/expressions/TestExpressions.py
@@ -0,0 +1,113 @@
+"""Test the go expression parser/interpreter."""
+
+import os, time
+import unittest2
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TestGoUserExpression(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @add_test_categories(['pyapi'])
+ @skipIfRemote # Not remote test suit ready
+ @skipUnlessGoInstalled
+ def test_with_dsym_and_python_api(self):
+ """Test GoASTUserExpress."""
+ self.buildGo()
+ self.launchProcess()
+ self.go_expressions()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break inside main().
+ self.main_source = "main.go"
+ self.break_line = line_number(self.main_source, '// Set breakpoint here.')
+
+ def check_builtin(self, name, size=0, typeclass=lldb.eTypeClassBuiltin):
+ tl = self.target().FindTypes(name)
+ self.assertEqual(1, len(tl))
+ t = list(tl)[0]
+ self.assertEqual(name, t.name)
+ self.assertEqual(typeclass, t.type)
+ if size > 0:
+ self.assertEqual(size, t.size)
+
+ def launchProcess(self):
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line)
+ self.assertTrue(bpt, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, bpt)
+
+ # Make sure we stopped at the first breakpoint.
+ self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.")
+ self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.")
+
+ frame = thread_list[0].GetFrameAtIndex(0)
+ self.assertTrue (frame, "Got a valid frame 0 frame.")
+
+ def go_expressions(self):
+ frame = self.frame()
+ v = frame.EvaluateExpression("1")
+ self.assertEqual(1, v.GetValueAsSigned())
+ x = frame.EvaluateExpression("x")
+ self.assertEqual(22, x.GetValueAsSigned())
+
+ a = frame.EvaluateExpression("a")
+ self.assertEqual(3, a.GetNumChildren())
+ a0 = a.GetChildAtIndex(0)
+ self.assertEqual(8, a0.GetValueAsSigned())
+
+ # Array indexing
+ a0 = frame.EvaluateExpression("a[0]")
+ self.assertEqual(8, a0.GetValueAsSigned())
+
+ # Slice indexing
+ b1 = frame.EvaluateExpression("b[1]")
+ self.assertEqual(9, b1.GetValueAsSigned())
+
+ # Test global in this package
+ g = frame.EvaluateExpression("myGlobal")
+ self.assertEqual(17, g.GetValueAsSigned(), str(g))
+
+ # Global with package name
+ g = frame.EvaluateExpression("main.myGlobal")
+ self.assertEqual(17, g.GetValueAsSigned(), str(g))
+
+ # Global with quoted package name
+ g = frame.EvaluateExpression('"main".myGlobal')
+ self.assertEqual(17, g.GetValueAsSigned(), str(g))
+
+ # Casting with package local type
+ s = frame.EvaluateExpression("*(*myStruct)(i.data)")
+ sb = s.GetChildMemberWithName("a")
+ self.assertEqual(2, sb.GetValueAsSigned())
+
+ # casting with explicit package
+ s = frame.EvaluateExpression("*(*main.myStruct)(i.data)")
+ sb = s.GetChildMemberWithName("a")
+ self.assertEqual(2, sb.GetValueAsSigned())
+
+ # Casting quoted package
+ s = frame.EvaluateExpression('*(*"main".myStruct)(i.data)')
+ sb = s.GetChildMemberWithName("b")
+ self.assertEqual(-1, sb.GetValueAsSigned())
+
+if __name__ == '__main__':
+ import atexit
+ lldb.SBDebugger.Initialize()
+ atexit.register(lambda: lldb.SBDebugger.Terminate())
+ unittest2.main()
diff --git a/packages/Python/lldbsuite/test/lang/go/expressions/main.go b/packages/Python/lldbsuite/test/lang/go/expressions/main.go
new file mode 100644
index 000000000000..c8b97fe07d7d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/go/expressions/main.go
@@ -0,0 +1,21 @@
+package main
+
+import "fmt"
+
+type myStruct struct {
+ a, b int
+}
+
+var myGlobal = 17
+
+func myFunc(i interface{}) {
+ a := [...]int{8, 9, 10}
+ b := a[:]
+ x := 22
+ fmt.Println(a, b, x, i, myGlobal) // Set breakpoint here.
+}
+
+func main() {
+ s := myStruct {2, -1}
+ myFunc(s)
+} \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/lang/go/formatters/TestGoFormatters.py b/packages/Python/lldbsuite/test/lang/go/formatters/TestGoFormatters.py
new file mode 100644
index 000000000000..8b869df4ef8f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/go/formatters/TestGoFormatters.py
@@ -0,0 +1,65 @@
+"""Test the Go Data Formatter Plugin."""
+
+import os, time
+import unittest2
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TestGoLanguage(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfFreeBSD # llvm.org/pr24895 triggers assertion failure
+ @skipIfRemote # Not remote test suite ready
+ @no_debug_info_test
+ @skipUnlessGoInstalled
+ def test_go_formatter_plugin(self):
+ """Test go data formatters."""
+ self.buildGo()
+ self.launchProcess()
+ self.check_formatters()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break inside main().
+ self.main_source = "main.go"
+ self.break_line = line_number(self.main_source, '// stop here')
+
+ def launchProcess(self):
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ self.bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line)
+ self.assertTrue(self.bpt, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, self.bpt)
+
+ # Make sure we stopped at the first breakpoint.
+ self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.")
+ self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.")
+
+ frame = thread_list[0].GetFrameAtIndex(0)
+ self.assertTrue (frame, "Got a valid frame 0 frame.")
+
+ def check_formatters(self):
+ a = self.frame().FindVariable('a')
+ self.assertEqual('(string) a = "my string"', str(a))
+ b = self.frame().FindVariable('b')
+ self.assertEqual("([]int) b = (len 2, cap 7) {\n [0] = 0\n [1] = 0\n}", str(b))
+
+
+if __name__ == '__main__':
+ import atexit
+ lldb.SBDebugger.Initialize()
+ atexit.register(lambda: lldb.SBDebugger.Terminate())
+ unittest2.main()
diff --git a/packages/Python/lldbsuite/test/lang/go/formatters/main.go b/packages/Python/lldbsuite/test/lang/go/formatters/main.go
new file mode 100644
index 000000000000..7956ad66bcb4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/go/formatters/main.go
@@ -0,0 +1,9 @@
+package main
+
+import "fmt"
+
+func main() {
+ a := "my string"
+ b := make([]int, 2, 7)
+ fmt.Println(a, b) // stop here
+} \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/lang/go/goroutines/TestGoroutines.py b/packages/Python/lldbsuite/test/lang/go/goroutines/TestGoroutines.py
new file mode 100644
index 000000000000..35961ebd1d92
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/go/goroutines/TestGoroutines.py
@@ -0,0 +1,85 @@
+"""Test the Go OS Plugin."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TestGoASTContext(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @add_test_categories(['pyapi'])
+ @skipIfFreeBSD # llvm.org/pr24895 triggers assertion failure
+ @skipIfRemote # Not remote test suite ready
+ @no_debug_info_test
+ @skipUnlessGoInstalled
+ def test_goroutine_plugin(self):
+ """Test goroutine as threads support."""
+ self.buildGo()
+ self.launchProcess()
+ self.check_goroutines()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break inside main().
+ self.main_source = "main.go"
+ self.break_line1 = line_number(self.main_source, '// stop1')
+ self.break_line2 = line_number(self.main_source, '// stop2')
+ self.break_line3 = line_number(self.main_source, '// stop3')
+
+ def launchProcess(self):
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ self.bpt1 = target.BreakpointCreateByLocation(self.main_source, self.break_line1)
+ self.assertTrue(self.bpt1, VALID_BREAKPOINT)
+ self.bpt2 = target.BreakpointCreateByLocation(self.main_source, self.break_line2)
+ self.assertTrue(self.bpt2, VALID_BREAKPOINT)
+ self.bpt3 = target.BreakpointCreateByLocation(self.main_source, self.break_line3)
+ self.assertTrue(self.bpt3, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, self.bpt1)
+
+ # Make sure we stopped at the first breakpoint.
+ self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.")
+ self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.")
+
+ frame = thread_list[0].GetFrameAtIndex(0)
+ self.assertTrue (frame, "Got a valid frame 0 frame.")
+
+ def check_goroutines(self):
+ self.assertLess(len(self.process().threads), 20)
+ self.process().Continue()
+
+ # Make sure we stopped at the 2nd breakpoint
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (self.process(), self.bpt2)
+ self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.")
+ self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.")
+
+ # There's (at least) 21 goroutines.
+ self.assertGreater(len(self.process().threads), 20)
+ # self.dbg.HandleCommand("log enable lldb os")
+
+ # Now test that stepping works if the memory thread moves to a different backing thread.
+ for i in list(range(11)):
+ self.thread().StepOver()
+ self.assertEqual(lldb.eStopReasonPlanComplete, self.thread().GetStopReason(), self.thread().GetStopDescription(100))
+
+ # Disable the plugin and make sure the goroutines disappear
+ self.dbg.HandleCommand("settings set plugin.os.goroutines.enable false")
+ self.thread().StepInstruction(False)
+ self.assertLess(len(self.process().threads), 20)
diff --git a/packages/Python/lldbsuite/test/lang/go/goroutines/main.go b/packages/Python/lldbsuite/test/lang/go/goroutines/main.go
new file mode 100644
index 000000000000..bb44f7b8b716
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/go/goroutines/main.go
@@ -0,0 +1,89 @@
+package main
+
+import (
+ "fmt"
+ "runtime"
+)
+
+type philosopher struct {
+ i int
+ forks [2]chan bool
+ eating chan int
+ done chan struct{}
+}
+
+func (p philosopher) run() {
+ for {
+ select {
+ case <-p.done:
+ return
+ case <-p.forks[0]:
+ p.eat()
+ }
+ }
+}
+
+func (p philosopher) eat() {
+ select {
+ case <-p.done:
+ return
+ case <-p.forks[1]:
+ p.eating <- p.i
+ p.forks[0] <- true
+ p.forks[1] <- true
+ runtime.Gosched()
+ }
+}
+
+func startPhilosophers(n int) (chan struct{}, chan int) {
+ philosophers := make([]*philosopher, n)
+ chans := make([]chan bool, n)
+ for i := range chans {
+ chans[i] = make(chan bool, 1)
+ chans[i] <- true
+ }
+ eating := make(chan int, n)
+ done := make(chan struct{})
+ for i := range philosophers {
+ var min, max int
+ if i == n - 1 {
+ min = 0
+ max = i
+ } else {
+ min = i
+ max = i + 1
+ }
+ philosophers[i] = &philosopher{i: i, forks: [2]chan bool{chans[min], chans[max]}, eating: eating, done: done}
+ go philosophers[i].run()
+ }
+ return done, eating
+}
+
+func wait(c chan int) {
+ fmt.Println(<- c)
+ runtime.Gosched()
+}
+
+func main() {
+ // Restrict go to 1 real thread so we can be sure we're seeing goroutines
+ // and not threads.
+ runtime.GOMAXPROCS(1)
+ // Create a bunch of goroutines
+ done, eating := startPhilosophers(20) // stop1
+ // Now turn up the number of threads so this goroutine is likely to get
+ // scheduled on a different thread.
+ runtime.GOMAXPROCS(runtime.NumCPU()) // stop2
+ // Now let things run. Hopefully we'll bounce around
+ wait(eating)
+ wait(eating)
+ wait(eating)
+ wait(eating)
+ wait(eating)
+ wait(eating)
+ wait(eating)
+ wait(eating)
+ wait(eating)
+ wait(eating)
+ close(done)
+ fmt.Println("done") // stop3
+}
diff --git a/packages/Python/lldbsuite/test/lang/go/runtime/TestGoLanguageRuntime b/packages/Python/lldbsuite/test/lang/go/runtime/TestGoLanguageRuntime
new file mode 100644
index 000000000000..44797077a641
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/go/runtime/TestGoLanguageRuntime
@@ -0,0 +1,80 @@
+"""Test the go dynamic type handling."""
+
+import os, time
+import unittest2
+import lldb
+import lldbutil
+from lldbtest import *
+
+class TestGoLanguageRuntime(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @python_api_test
+ @expectedFailureFreeBSD('llvm.org/pr24895')
+ @skipIfRemote # Not remote test suite ready
+ @skipUnlessGoInstalled
+ def test_with_dsym_and_python_api(self):
+ """Test GoASTContext dwarf parsing."""
+ self.buildGo()
+ self.launchProcess()
+ self.go_interface_types()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break inside main().
+ self.main_source = "main.go"
+ self.break_line1 = line_number(self.main_source, '// Set breakpoint 1')
+ self.break_line2 = line_number(self.main_source, '// Set breakpoint 2')
+
+
+ def launchProcess(self):
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ bpt1 = target.BreakpointCreateByLocation(self.main_source, self.break_line1)
+ self.assertTrue(bpt1, VALID_BREAKPOINT)
+ bpt2 = target.BreakpointCreateByLocation(self.main_source, self.break_line2)
+ self.assertTrue(bpt2, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, bpt1)
+
+ # Make sure we stopped at the first breakpoint.
+ self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.")
+ self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.")
+
+ frame = thread_list[0].GetFrameAtIndex(0)
+ self.assertTrue (frame, "Got a valid frame 0 frame.")
+
+ def go_interface_types(self):
+ f = self.frame()
+ v = f.FindVariable("a", lldb.eDynamicCanRunTarget)
+ self.assertEqual("*int", v.GetType().name)
+ self.assertEqual(1, v.Dereference().GetValueAsSigned())
+ v = f.FindVariable("b", lldb.eDynamicCanRunTarget)
+ self.assertEqual("*float64", v.GetType().name)
+ err = lldb.SBError()
+ self.assertEqual(2.0, v.Dereference().GetData().GetDouble(err, 0))
+ v = f.FindVariable("c", lldb.eDynamicCanRunTarget)
+ self.assertEqual("*main.SomeFooer", v.GetType().name)
+ self.assertEqual(9, v.Dereference().GetChildAtIndex(0).GetValueAsSigned())
+ v = f.FindVariable("d", lldb.eDynamicCanRunTarget)
+ self.assertEqual("*main.AnotherFooer", v.GetType().name)
+ self.assertEqual(-1, v.Dereference().GetChildAtIndex(0).GetValueAsSigned())
+ self.assertEqual(-2, v.Dereference().GetChildAtIndex(1).GetValueAsSigned())
+ self.assertEqual(-3, v.Dereference().GetChildAtIndex(2).GetValueAsSigned())
+
+if __name__ == '__main__':
+ import atexit
+ lldb.SBDebugger.Initialize()
+ atexit.register(lambda: lldb.SBDebugger.Terminate())
+ unittest2.main()
diff --git a/packages/Python/lldbsuite/test/lang/go/runtime/main.go b/packages/Python/lldbsuite/test/lang/go/runtime/main.go
new file mode 100644
index 000000000000..227c8c377ed7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/go/runtime/main.go
@@ -0,0 +1,38 @@
+package main
+
+import "fmt"
+
+type Fooer interface {
+ Foo() int
+}
+
+type SomeFooer struct {
+ val int
+}
+
+func (s SomeFooer) Foo() int {
+ return s.val
+}
+
+type AnotherFooer struct {
+ a, b, c int
+}
+
+func (s AnotherFooer) Foo() int {
+ return s.a
+}
+
+
+func printEface(a, b, c, d interface{}) {
+ fmt.Println(a, b, c, d) // Set breakpoint 1
+}
+
+func printIface(a, b Fooer) {
+ fmt.Println(a, b) // Set breakpoint 2
+}
+func main() {
+ sf := SomeFooer{9}
+ af := AnotherFooer{-1, -2, -3}
+ printEface(1,2.0, sf, af)
+ printIface(sf, af)
+} \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/lang/go/types/TestGoASTContext.py b/packages/Python/lldbsuite/test/lang/go/types/TestGoASTContext.py
new file mode 100644
index 000000000000..8da31e9e81f7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/go/types/TestGoASTContext.py
@@ -0,0 +1,133 @@
+"""Test the go DWARF type parsing."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TestGoASTContext(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @add_test_categories(['pyapi'])
+ @skipIfFreeBSD # llvm.org/pr24895 triggers assertion failure
+ @skipIfRemote # Not remote test suit ready
+ @no_debug_info_test
+ @skipUnlessGoInstalled
+ def test_with_dsym_and_python_api(self):
+ """Test GoASTContext dwarf parsing."""
+ self.buildGo()
+ self.launchProcess()
+ self.go_builtin_types()
+ self.check_main_vars()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break inside main().
+ self.main_source = "main.go"
+ self.break_line = line_number(self.main_source, '// Set breakpoint here.')
+
+ def check_builtin(self, name, size=0, typeclass=lldb.eTypeClassBuiltin):
+ tl = self.target().FindTypes(name)
+ self.assertEqual(1, len(tl))
+ t = list(tl)[0]
+ self.assertEqual(name, t.name)
+ self.assertEqual(typeclass, t.type)
+ if size > 0:
+ self.assertEqual(size, t.size)
+
+ def launchProcess(self):
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line)
+ self.assertTrue(bpt, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, bpt)
+
+ # Make sure we stopped at the first breakpoint.
+ self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.")
+ self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.")
+
+ frame = thread_list[0].GetFrameAtIndex(0)
+ self.assertTrue (frame, "Got a valid frame 0 frame.")
+
+ def go_builtin_types(self):
+ address_size = self.target().GetAddressByteSize()
+ self.check_builtin('bool')
+ self.check_builtin('uint8', 1)
+ self.check_builtin('int8', 1)
+ self.check_builtin('uint16', 2)
+ self.check_builtin('int16', 2)
+ self.check_builtin('uint32', 4)
+ self.check_builtin('int32', 4)
+ self.check_builtin('uint64', 8)
+ self.check_builtin('int64', 8)
+ self.check_builtin('uintptr', address_size)
+ self.check_builtin('int', address_size)
+ self.check_builtin('uint', address_size)
+ self.check_builtin('float32', 4)
+ self.check_builtin('float64', 8)
+ self.check_builtin('complex64', 8, lldb.eTypeClassComplexFloat)
+ self.check_builtin('complex128', 16, lldb.eTypeClassComplexFloat)
+
+ def var(self, name):
+ var = self.frame().FindVariable(name)
+ self.assertTrue(var.IsValid(), "%s %s" % (VALID_VARIABLE, name))
+ return var
+
+ def check_main_vars(self):
+ v = self.var('theBool')
+ self.assertEqual('true', v.value)
+
+ v = self.var('theInt')
+ self.assertEqual('-7', v.value)
+
+ v = self.var('theComplex')
+ self.assertEqual('1 + 2i', v.value)
+
+ v = self.var('thePointer')
+ self.assertTrue(v.TypeIsPointerType())
+ self.assertEqual('-10', v.Dereference().value)
+ self.assertEqual(1, v.GetNumChildren())
+ self.assertEqual('-10', v.GetChildAtIndex(0).value)
+
+ # print()
+ # print(os.getpid())
+ # time.sleep(60)
+ v = self.var('theStruct')
+ if v.TypeIsPointerType():
+ v = v.Dereference()
+ self.assertEqual(2, v.GetNumChildren())
+ self.assertEqual('7', v.GetChildAtIndex(0).value)
+ self.assertEqual('7', v.GetChildMemberWithName('myInt').value)
+ self.assertEqual(v.load_addr, v.GetChildAtIndex(1).GetValueAsUnsigned())
+ self.assertEqual(v.load_addr, v.GetChildMemberWithName('myPointer').GetValueAsUnsigned())
+
+ # Test accessing struct fields through pointers.
+ v = v.GetChildMemberWithName('myPointer')
+ self.assertTrue(v.TypeIsPointerType())
+ self.assertEqual(2, v.GetNumChildren())
+ self.assertEqual('7', v.GetChildAtIndex(0).value)
+ c = v.GetChildMemberWithName('myPointer')
+ self.assertTrue(c.TypeIsPointerType())
+ self.assertEqual(2, c.GetNumChildren())
+ self.assertEqual('7', c.GetChildAtIndex(0).value)
+
+ v = self.var('theArray')
+ self.assertEqual(5, v.GetNumChildren())
+ for i in list(range(5)):
+ self.assertEqual(str(i + 1), v.GetChildAtIndex(i).value)
diff --git a/packages/Python/lldbsuite/test/lang/go/types/main.go b/packages/Python/lldbsuite/test/lang/go/types/main.go
new file mode 100644
index 000000000000..c74650721d7d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/go/types/main.go
@@ -0,0 +1,47 @@
+package main
+
+import "fmt"
+
+type Fooer interface {
+ Foo() int
+}
+
+type SomeFooer struct {
+ val int
+}
+
+func (s SomeFooer) Foo() int {
+ return s.val
+}
+
+type mystruct struct {
+ myInt int
+ myPointer *mystruct
+}
+
+func main() {
+ theBool := true
+ theInt := -7
+ theComplex := 1 + 2i
+ pointee := -10
+ thePointer := &pointee
+ theStruct := &mystruct { myInt: 7}
+ theStruct.myPointer = theStruct
+ theArray := [5]byte{1, 2, 3, 4, 5}
+ theSlice := theArray[1:2]
+ theString := "abc"
+
+ f := SomeFooer {9}
+ var theEface interface{} = f
+ var theFooer Fooer = f
+
+ theChan := make(chan int)
+ theMap := make(map[int]string)
+ theMap[1] = "1"
+
+ fmt.Println(theBool) // Set breakpoint here.
+ // Reference all the variables so the compiler is happy.
+ fmt.Println(theInt, theComplex, thePointer, theStruct.myInt)
+ fmt.Println(theArray[0], theSlice[0], theString)
+ fmt.Println(theEface, theFooer, theChan, theMap)
+} \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/lang/mixed/Makefile b/packages/Python/lldbsuite/test/lang/mixed/Makefile
new file mode 100644
index 000000000000..860343ee907c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/mixed/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../make
+
+CXX_SOURCES := foo.cpp
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/mixed/TestMixedLanguages.py b/packages/Python/lldbsuite/test/lang/mixed/TestMixedLanguages.py
new file mode 100644
index 000000000000..d11f03b878ae
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/mixed/TestMixedLanguages.py
@@ -0,0 +1,56 @@
+"""Test that lldb works correctly on compile units form different languages."""
+
+from __future__ import print_function
+
+
+
+import os, time, re
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class MixedLanguagesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test_language_of_frame(self):
+ """Test that the language defaults to the language of the current frame."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Execute the cleanup function during test case tear down
+ # to restore the frame format.
+ def cleanup():
+ self.runCmd("settings set frame-format %s" % self.format_string, check=False)
+ self.addTearDownHook(cleanup)
+ self.runCmd("settings show frame-format")
+ m = re.match(
+ '^frame-format \(format-string\) = "(.*)\"$',
+ self.res.GetOutput())
+ self.assertTrue(m, "Bad settings string")
+ self.format_string = m.group(1)
+
+ # Change the default format to print the language.
+ format_string = "frame #${frame.index}: ${frame.pc}{ ${module.file.basename}`${function.name}{${function.pc-offset}}}{, lang=${language}}\n"
+ self.runCmd("settings set frame-format %s" % format_string)
+ self.expect("settings show frame-format", SETTING_MSG("frame-format"),
+ substrs = [format_string])
+
+ # Run to BP at main (in main.c) and test that the language is C.
+ self.runCmd("breakpoint set -n main")
+ self.runCmd("run")
+ self.expect("thread backtrace",
+ substrs = ["`main", "lang=c"])
+ # Make sure evaluation of C++11 fails.
+ self.expect("expr foo != nullptr", error=True,
+ startstr = "error")
+
+ # Run to BP at foo (in foo.cpp) and test that the language is C++.
+ self.runCmd("breakpoint set -n foo")
+ self.runCmd("continue")
+ self.expect("thread backtrace",
+ substrs = ["`::foo()", "lang=c++"])
+ # Make sure we can evaluate an expression requiring C++11
+ # (note: C++11 is enabled by default for C++).
+ self.expect("expr foo != nullptr",
+ patterns = ["true"])
diff --git a/packages/Python/lldbsuite/test/lang/mixed/foo.cpp b/packages/Python/lldbsuite/test/lang/mixed/foo.cpp
new file mode 100644
index 000000000000..8a5a6a2b5416
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/mixed/foo.cpp
@@ -0,0 +1,11 @@
+namespace ns {
+ int func(void)
+ {
+ return 0;
+ }
+}
+
+extern "C" int foo(void)
+{
+ return ns::func();
+}
diff --git a/packages/Python/lldbsuite/test/lang/mixed/main.c b/packages/Python/lldbsuite/test/lang/mixed/main.c
new file mode 100644
index 000000000000..f5c5d19f2c89
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/mixed/main.c
@@ -0,0 +1,15 @@
+int foo(void);
+static int static_value = 0;
+
+int
+bar()
+{
+ static_value++;
+ return static_value;
+}
+
+int main (int argc, char const *argv[])
+{
+ bar(); // breakpoint_in_main
+ return foo();
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/.categories b/packages/Python/lldbsuite/test/lang/objc/.categories
new file mode 100644
index 000000000000..72cf07c1efea
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/.categories
@@ -0,0 +1 @@
+objc
diff --git a/packages/Python/lldbsuite/test/lang/objc/blocks/Makefile b/packages/Python/lldbsuite/test/lang/objc/blocks/Makefile
new file mode 100644
index 000000000000..0af83591826f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/blocks/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := ivars-in-blocks.m main.m
+LDFLAGS = $(CFLAGS) -lobjc -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/blocks/TestObjCIvarsInBlocks.py b/packages/Python/lldbsuite/test/lang/objc/blocks/TestObjCIvarsInBlocks.py
new file mode 100644
index 000000000000..6a1cde1a3cb3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/blocks/TestObjCIvarsInBlocks.py
@@ -0,0 +1,103 @@
+"""Test printing ivars and ObjC objects captured in blocks that are made in methods of an ObjC class."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TestObjCIvarsInBlocks(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break inside main().
+ self.main_source = "main.m"
+ self.class_source = "ivars-in-blocks.m"
+ self.class_source_file_spec = lldb.SBFileSpec(self.class_source)
+
+ @skipUnlessDarwin
+ @add_test_categories(['pyapi'])
+ @expectedFailurei386 # This test requires the 2.0 runtime, so it will fail on i386.
+ def test_with_python_api(self):
+ """Test printing the ivars of the self when captured in blocks"""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateBySourceRegex ('// Break here inside the block.', self.class_source_file_spec)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ breakpoint_two = target.BreakpointCreateBySourceRegex ('// Break here inside the class method block.', self.class_source_file_spec)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue (process, "Created a process.")
+ self.assertTrue (process.GetState() == lldb.eStateStopped, "Stopped it too.")
+
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint)
+ self.assertTrue (len(thread_list) == 1)
+ thread = thread_list[0]
+
+ frame = thread.GetFrameAtIndex(0)
+ self.assertTrue (frame, "frame 0 is valid")
+
+ # First use the FindVariable API to see if we can find the ivar by undecorated name:
+ direct_blocky = frame.GetValueForVariablePath ("blocky_ivar")
+ self.assertTrue(direct_blocky, "Found direct access to blocky_ivar.")
+
+ # Now get it as a member of "self" and make sure the two values are equal:
+ self_var = frame.GetValueForVariablePath ("self")
+ self.assertTrue (self_var, "Found self in block.")
+ indirect_blocky = self_var.GetChildMemberWithName ("blocky_ivar")
+ self.assertTrue (indirect_blocky, "Found blocky_ivar through self")
+
+ error = lldb.SBError()
+ direct_value = direct_blocky.GetValueAsSigned(error)
+ self.assertTrue (error.Success(), "Got direct value for blocky_ivar")
+
+ indirect_value = indirect_blocky.GetValueAsSigned (error)
+ self.assertTrue (error.Success(), "Got indirect value for blocky_ivar")
+
+ self.assertTrue (direct_value == indirect_value, "Direct and indirect values are equal.")
+
+ # Now make sure that we can get at the captured ivar through the expression parser.
+ # Doing a little trivial math will force this into the real expression parser:
+ direct_expr = frame.EvaluateExpression ("blocky_ivar + 10")
+ self.assertTrue (direct_expr, "Got blocky_ivar through the expression parser")
+
+ # Again, get the value through self directly and make sure they are the same:
+ indirect_expr = frame.EvaluateExpression ("self->blocky_ivar + 10")
+ self.assertTrue (indirect_expr, "Got blocky ivar through expression parser using self.")
+
+ direct_value = direct_expr.GetValueAsSigned (error)
+ self.assertTrue (error.Success(), "Got value from direct use of expression parser")
+
+ indirect_value = indirect_expr.GetValueAsSigned (error)
+ self.assertTrue (error.Success(), "Got value from indirect access using the expression parser")
+
+ self.assertTrue (direct_value == indirect_value, "Direct ivar access and indirect through expression parser produce same value.")
+
+ process.Continue()
+ self.assertTrue (process.GetState() == lldb.eStateStopped, "Stopped at the second breakpoint.")
+
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint_two)
+ self.assertTrue (len(thread_list) == 1)
+ thread = thread_list[0]
+
+ frame = thread.GetFrameAtIndex(0)
+ self.assertTrue (frame, "frame 0 is valid")
+
+ expr = frame.EvaluateExpression("(ret)")
+ self.assertTrue (expr, "Successfully got a local variable in a block in a class method.")
+
+ ret_value_signed = expr.GetValueAsSigned (error)
+ # print('ret_value_signed = %i' % (ret_value_signed))
+ self.assertTrue (ret_value_signed == 5, "The local variable in the block was what we expected.")
diff --git a/packages/Python/lldbsuite/test/lang/objc/blocks/ivars-in-blocks.h b/packages/Python/lldbsuite/test/lang/objc/blocks/ivars-in-blocks.h
new file mode 100644
index 000000000000..1ceac3361ac0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/blocks/ivars-in-blocks.h
@@ -0,0 +1,11 @@
+#import <Foundation/Foundation.h>
+
+@interface IAmBlocky : NSObject
+{
+ @public
+ int blocky_ivar;
+}
++ (void) classMethod;
+- (IAmBlocky *) init;
+- (int) callABlock: (int) block_value;
+@end
diff --git a/packages/Python/lldbsuite/test/lang/objc/blocks/ivars-in-blocks.m b/packages/Python/lldbsuite/test/lang/objc/blocks/ivars-in-blocks.m
new file mode 100644
index 000000000000..1098a9136ae2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/blocks/ivars-in-blocks.m
@@ -0,0 +1,57 @@
+#import "ivars-in-blocks.h"
+
+typedef int (^my_block_ptr_type) (int);
+
+@interface IAmBlocky()
+{
+ int _hidden_ivar;
+ my_block_ptr_type _block_ptr;
+}
+
+@end
+
+@implementation IAmBlocky
+
++ (int) addend
+{
+ return 3;
+}
+
++ (void) classMethod
+{
+ int (^my_block)(int) = ^(int foo)
+ {
+ int ret = foo + [self addend];
+ return ret; // Break here inside the class method block.
+ };
+ printf("%d\n", my_block(2));
+}
+
+- (void) makeBlockPtr;
+{
+ _block_ptr = ^(int inval)
+ {
+ _hidden_ivar += inval;
+ return blocky_ivar * inval; // Break here inside the block.
+ };
+}
+
+- (IAmBlocky *) init
+{
+ blocky_ivar = 10;
+ _hidden_ivar = 20;
+ // Interesting... Apparently you can't make a block in your init method. This crashes...
+ // [self makeBlockPtr];
+ return self;
+}
+
+- (int) callABlock: (int) block_value
+{
+ if (_block_ptr == NULL)
+ [self makeBlockPtr];
+ int ret = _block_ptr (block_value);
+ [IAmBlocky classMethod];
+ return ret;
+}
+@end
+
diff --git a/packages/Python/lldbsuite/test/lang/objc/blocks/main.m b/packages/Python/lldbsuite/test/lang/objc/blocks/main.m
new file mode 100644
index 000000000000..0c56f45da464
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/blocks/main.m
@@ -0,0 +1,10 @@
+#import "ivars-in-blocks.h"
+
+int
+main (int argc, char **argv)
+{
+ IAmBlocky *my_blocky = [[IAmBlocky alloc] init];
+ int blocky_value;
+ blocky_value = [my_blocky callABlock: 33];
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/forward-decl/Container.h b/packages/Python/lldbsuite/test/lang/objc/forward-decl/Container.h
new file mode 100644
index 000000000000..85bbd06b161c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/forward-decl/Container.h
@@ -0,0 +1,13 @@
+#import <Foundation/Foundation.h>
+
+@class ForwardDeclaredClass;
+
+@interface Container : NSObject {
+@public
+ ForwardDeclaredClass *member;
+}
+
+-(id)init;
+-(ForwardDeclaredClass*)getMember;
+
+@end
diff --git a/packages/Python/lldbsuite/test/lang/objc/forward-decl/Container.m b/packages/Python/lldbsuite/test/lang/objc/forward-decl/Container.m
new file mode 100644
index 000000000000..4d2139ff5fc6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/forward-decl/Container.m
@@ -0,0 +1,27 @@
+#import "Container.h"
+
+@interface ForwardDeclaredClass : NSObject
+{
+ int a;
+ int b;
+}
+@end
+
+@implementation ForwardDeclaredClass
+
+@end
+
+@implementation Container
+
+-(id)init
+{
+ member = [ForwardDeclaredClass alloc];
+ return [super init];
+}
+
+-(ForwardDeclaredClass *)getMember
+{
+ return member;
+}
+
+@end
diff --git a/packages/Python/lldbsuite/test/lang/objc/forward-decl/Makefile b/packages/Python/lldbsuite/test/lang/objc/forward-decl/Makefile
new file mode 100644
index 000000000000..b99925b50b38
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/forward-decl/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../../make
+
+DYLIB_NAME := Container
+DYLIB_OBJC_SOURCES := Container.m
+OBJC_SOURCES := main.m
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/lang/objc/forward-decl/TestForwardDecl.py b/packages/Python/lldbsuite/test/lang/objc/forward-decl/TestForwardDecl.py
new file mode 100644
index 000000000000..207518abc91b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/forward-decl/TestForwardDecl.py
@@ -0,0 +1,54 @@
+"""Test that a forward-declared class works when its complete definition is in a library"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ForwardDeclTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.source = 'main.m'
+ self.line = line_number(self.source, '// Set breakpoint 0 here.')
+ self.shlib_names = ["Container"]
+
+ @skipUnlessDarwin
+ def test_expr(self):
+ self.build()
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget("a.out")
+ self.assertTrue(target, VALID_TARGET)
+
+ # Create the breakpoint inside function 'main'.
+ breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Register our shared libraries for remote targets so they get automatically uploaded
+ environment = self.registerSharedLibrariesWithTarget(target, self.shlib_names)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, environment, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ # This should display correctly.
+ self.expect("expression [j getMember]", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["= 0x"])
diff --git a/packages/Python/lldbsuite/test/lang/objc/forward-decl/main.m b/packages/Python/lldbsuite/test/lang/objc/forward-decl/main.m
new file mode 100644
index 000000000000..8e5256e95230
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/forward-decl/main.m
@@ -0,0 +1,14 @@
+#import <Foundation/Foundation.h>
+#import "Container.h"
+
+int main(int argc, const char * argv[])
+{
+
+ @autoreleasepool {
+ Container *j = [[Container alloc] init];
+
+ printf("member value = %p", [j getMember]); // Set breakpoint 0 here.
+ }
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/lang/objc/foundation/Makefile b/packages/Python/lldbsuite/test/lang/objc/foundation/Makefile
new file mode 100644
index 000000000000..ce2ccd28321d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/foundation/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m my-base.m
+#OBJC_SOURCES := const-strings.m
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/lang/objc/foundation/TestConstStrings.py b/packages/Python/lldbsuite/test/lang/objc/foundation/TestConstStrings.py
new file mode 100644
index 000000000000..a9298dd81cf8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/foundation/TestConstStrings.py
@@ -0,0 +1,53 @@
+"""
+Test that objective-c constant strings are generated correctly by the expression
+parser.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ConstStringTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+ d = {'OBJC_SOURCES': 'const-strings.m'}
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.main_source = "const-strings.m"
+ self.line = line_number(self.main_source, '// Set breakpoint here.')
+
+ @skipUnlessDarwin
+ def test_break(self):
+ """Test constant string generation amd comparison by the expression parser."""
+ self.build(dictionary=self.d)
+ self.setTearDownCleanup(self.d)
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, self.main_source, self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+ self.expect("process status", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = [" at %s:%d" % (self.main_source, self.line),
+ "stop reason = breakpoint"])
+
+ self.expect('expression (int)[str compare:@"hello"]',
+ startstr = "(int) $0 = 0")
+ self.expect('expression (int)[str compare:@"world"]',
+ startstr = "(int) $1 = -1")
+
+ # Test empty strings, too.
+ self.expect('expression (int)[@"" length]',
+ startstr = "(int) $2 = 0")
+
+ self.expect('expression (int)[@"123" length]',
+ startstr = "(int) $3 = 3")
diff --git a/packages/Python/lldbsuite/test/lang/objc/foundation/TestFoundationDisassembly.py b/packages/Python/lldbsuite/test/lang/objc/foundation/TestFoundationDisassembly.py
new file mode 100644
index 000000000000..88db12e95931
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/foundation/TestFoundationDisassembly.py
@@ -0,0 +1,134 @@
+"""
+Test the lldb disassemble command on foundation framework.
+"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+@skipUnlessDarwin
+class FoundationDisassembleTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ # rdar://problem/8504895
+ # Crash while doing 'disassemble -n "-[NSNumber descriptionWithLocale:]"
+ @unittest2.skipIf(TestBase.skipLongRunningTest(), "Skip this long running test")
+ def test_foundation_disasm(self):
+ """Do 'disassemble -n func' on each and every 'Code' symbol entry from the Foundation.framework."""
+ self.build()
+
+ # Enable synchronous mode
+ self.dbg.SetAsync(False)
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget("a.out")
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ foundation_framework = None
+ for module in target.modules:
+ print(module)
+ if module.file.basename == "Foundation":
+ foundation_framework = module.file.fullpath
+ break
+
+ self.assertTrue(foundation_framework != None, "Foundation.framework path located")
+ self.runCmd("image dump symtab '%s'" % foundation_framework)
+ raw_output = self.res.GetOutput()
+ # Now, grab every 'Code' symbol and feed it into the command:
+ # 'disassemble -n func'.
+ #
+ # The symbol name is on the last column and trails the flag column which
+ # looks like '0xhhhhhhhh', i.e., 8 hexadecimal digits.
+ codeRE = re.compile(r"""
+ \ Code\ {9} # ' Code' followed by 9 SPCs,
+ .* # the wildcard chars,
+ 0x[0-9a-f]{8} # the flag column, and
+ \ (.+)$ # finally the function symbol.
+ """, re.VERBOSE)
+ for line in raw_output.split(os.linesep):
+ match = codeRE.search(line)
+ if match:
+ func = match.group(1)
+ #print("line:", line)
+ #print("func:", func)
+ self.runCmd('disassemble -n "%s"' % func)
+
+
+ def test_simple_disasm(self):
+ """Test the lldb 'disassemble' command"""
+ self.build()
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget("a.out")
+ self.assertTrue(target, VALID_TARGET)
+
+ print(target)
+ for module in target.modules:
+ print(module)
+
+ # Stop at +[NSString stringWithFormat:].
+ symbol_name = "+[NSString stringWithFormat:]"
+ break_results = lldbutil.run_break_set_command (self, "_regexp-break %s"%(symbol_name))
+
+ lldbutil.check_breakpoint_result (self, break_results, symbol_name=symbol_name, num_locations=1)
+
+ # Stop at -[MyString initWithNSString:].
+ lldbutil.run_break_set_by_symbol (self, '-[MyString initWithNSString:]', num_expected_locations=1, sym_exact=True)
+
+ # Stop at the "description" selector.
+ lldbutil.run_break_set_by_selector (self, 'description', num_expected_locations=1, module_name='a.out')
+
+ # Stop at -[NSAutoreleasePool release].
+ break_results = lldbutil.run_break_set_command (self, "_regexp-break -[NSAutoreleasePool release]")
+ lldbutil.check_breakpoint_result (self, break_results, symbol_name='-[NSAutoreleasePool release]', num_locations=1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # First stop is +[NSString stringWithFormat:].
+ self.expect("thread backtrace", "Stop at +[NSString stringWithFormat:]",
+ substrs = ["Foundation`+[NSString stringWithFormat:]"])
+
+ # Do the disassemble for the currently stopped function.
+ self.runCmd("disassemble -f")
+
+ self.runCmd("process continue")
+ # Skip another breakpoint for +[NSString stringWithFormat:].
+ self.runCmd("process continue")
+
+ # Followed by a.out`-[MyString initWithNSString:].
+ self.expect("thread backtrace", "Stop at a.out`-[MyString initWithNSString:]",
+ substrs = ["a.out`-[MyString initWithNSString:]"])
+
+ # Do the disassemble for the currently stopped function.
+ self.runCmd("disassemble -f")
+
+ self.runCmd("process continue")
+
+ # Followed by -[MyString description].
+ self.expect("thread backtrace", "Stop at -[MyString description]",
+ substrs = ["a.out`-[MyString description]"])
+
+ # Do the disassemble for the currently stopped function.
+ self.runCmd("disassemble -f")
+
+ self.runCmd("process continue")
+ # Skip another breakpoint for -[MyString description].
+ self.runCmd("process continue")
+
+ # Followed by -[NSAutoreleasePool release].
+ self.expect("thread backtrace", "Stop at -[NSAutoreleasePool release]",
+ substrs = ["Foundation`-[NSAutoreleasePool release]"])
+
+ # Do the disassemble for the currently stopped function.
+ self.runCmd("disassemble -f")
diff --git a/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods.py b/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods.py
new file mode 100644
index 000000000000..8358bd5e923f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods.py
@@ -0,0 +1,262 @@
+"""
+Set breakpoints on objective-c class and instance methods in foundation.
+Also lookup objective-c data types and evaluate expressions.
+"""
+
+from __future__ import print_function
+
+
+
+import os, os.path, time
+import lldb
+import string
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+file_index = 0
+@skipUnlessDarwin
+class FoundationTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.main_source = "main.m"
+ self.line = line_number(self.main_source, '// Set break point at this line.')
+
+ def test_break(self):
+ """Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Stop at +[NSString stringWithFormat:].
+ break_results = lldbutil.run_break_set_command(self, "_regexp-break +[NSString stringWithFormat:]")
+ lldbutil.check_breakpoint_result (self, break_results, symbol_name='+[NSString stringWithFormat:]', num_locations=1)
+
+ # Stop at -[MyString initWithNSString:].
+ lldbutil.run_break_set_by_symbol (self, '-[MyString initWithNSString:]', num_expected_locations=1, sym_exact=True)
+
+ # Stop at the "description" selector.
+ lldbutil.run_break_set_by_selector (self, 'description', num_expected_locations=1, module_name='a.out')
+
+ # Stop at -[NSAutoreleasePool release].
+ break_results = lldbutil.run_break_set_command(self, "_regexp-break -[NSAutoreleasePool release]")
+ lldbutil.check_breakpoint_result (self, break_results, symbol_name='-[NSAutoreleasePool release]', num_locations=1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # First stop is +[NSString stringWithFormat:].
+ self.expect("thread backtrace", "Stop at +[NSString stringWithFormat:]",
+ substrs = ["Foundation`+[NSString stringWithFormat:]"])
+
+ self.runCmd("process continue")
+
+ # Second stop is still +[NSString stringWithFormat:].
+ self.expect("thread backtrace", "Stop at +[NSString stringWithFormat:]",
+ substrs = ["Foundation`+[NSString stringWithFormat:]"])
+
+ self.runCmd("process continue")
+
+ # Followed by a.out`-[MyString initWithNSString:].
+ self.expect("thread backtrace", "Stop at a.out`-[MyString initWithNSString:]",
+ substrs = ["a.out`-[MyString initWithNSString:]"])
+
+ self.runCmd("process continue")
+
+ # Followed by -[MyString description].
+ self.expect("thread backtrace", "Stop at -[MyString description]",
+ substrs = ["a.out`-[MyString description]"])
+
+ self.runCmd("process continue")
+
+ # Followed by the same -[MyString description].
+ self.expect("thread backtrace", "Stop at -[MyString description]",
+ substrs = ["a.out`-[MyString description]"])
+
+ self.runCmd("process continue")
+
+ # Followed by -[NSAutoreleasePool release].
+ self.expect("thread backtrace", "Stop at -[NSAutoreleasePool release]",
+ substrs = ["Foundation`-[NSAutoreleasePool release]"])
+
+ # rdar://problem/8542091
+ # rdar://problem/8492646
+ def test_data_type_and_expr(self):
+ """Lookup objective-c data types and evaluate expressions."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Stop at -[MyString description].
+ lldbutil.run_break_set_by_symbol (self, '-[MyString description]', num_expected_locations=1, sym_exact=True)
+# self.expect("breakpoint set -n '-[MyString description]", BREAKPOINT_CREATED,
+# startstr = "Breakpoint created: 1: name = '-[MyString description]', locations = 1")
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The backtrace should show we stop at -[MyString description].
+ self.expect("thread backtrace", "Stop at -[MyString description]",
+ substrs = ["a.out`-[MyString description]"])
+
+ # Lookup objc data type MyString and evaluate some expressions.
+
+ self.expect("image lookup -t NSString", DATA_TYPES_DISPLAYED_CORRECTLY,
+ substrs = ['name = "NSString"',
+ 'compiler_type = "@interface NSString'])
+
+ self.expect("image lookup -t MyString", DATA_TYPES_DISPLAYED_CORRECTLY,
+ substrs = ['name = "MyString"',
+ 'compiler_type = "@interface MyString',
+ 'NSString * str;',
+ 'NSDate * date;'])
+
+ self.expect("frame variable --show-types --scope", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["ARG: (MyString *) self"],
+ patterns = ["ARG: \(.*\) _cmd",
+ "(objc_selector *)|(SEL)"])
+
+ # rdar://problem/8651752
+ # don't crash trying to ask clang how many children an empty record has
+ self.runCmd("frame variable *_cmd")
+
+ # rdar://problem/8492646
+ # test/foundation fails after updating to tot r115023
+ # self->str displays nothing as output
+ self.expect("frame variable --show-types self->str", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = "(NSString *) self->str")
+
+ # rdar://problem/8447030
+ # 'frame variable self->date' displays the wrong data member
+ self.expect("frame variable --show-types self->date", VARIABLES_DISPLAYED_CORRECTLY,
+ startstr = "(NSDate *) self->date")
+
+ # This should display the str and date member fields as well.
+ self.expect("frame variable --show-types *self", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["(MyString) *self",
+ "(NSString *) str",
+ "(NSDate *) date"])
+
+ # isa should be accessible.
+ self.expect("expression self->isa", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["(Class)"])
+
+ # This should fail expectedly.
+ self.expect("expression self->non_existent_member",
+ COMMAND_FAILED_AS_EXPECTED, error=True,
+ startstr = "error: 'MyString' does not have a member named 'non_existent_member'")
+
+ # Use expression parser.
+ self.runCmd("expression self->str")
+ self.runCmd("expression self->date")
+
+ # (lldb) expression self->str
+ # error: instance variable 'str' is protected
+ # error: 1 errors parsing expression
+ #
+ # (lldb) expression self->date
+ # error: instance variable 'date' is protected
+ # error: 1 errors parsing expression
+ #
+
+ self.runCmd("breakpoint delete 1")
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("process continue")
+
+ # rdar://problem/8542091
+ # test/foundation: expr -o -- my not working?
+ #
+ # Test new feature with r115115:
+ # Add "-o" option to "expression" which prints the object description if available.
+ self.expect("expression --object-description -- my", "Object description displayed correctly",
+ patterns = ["Hello from.*a.out.*with timestamp: "])
+
+ @add_test_categories(['pyapi'])
+ def test_print_ivars_correctly (self):
+ self.build()
+ # See: <rdar://problem/8717050> lldb needs to use the ObjC runtime symbols for ivar offsets
+ # Only fails for the ObjC 2.0 runtime.
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ break1 = target.BreakpointCreateByLocation(self.main_source, self.line)
+ self.assertTrue(break1, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ thread = process.GetThreadAtIndex(0)
+ if thread.GetStopReason() != lldb.eStopReasonBreakpoint:
+ from lldbsuite.test.lldbutil import stop_reason_to_str
+ self.fail(STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS %
+ stop_reason_to_str(thread.GetStopReason()))
+
+ # Make sure we stopped at the first breakpoint.
+
+ cur_frame = thread.GetFrameAtIndex(0)
+
+ line_number = cur_frame.GetLineEntry().GetLine()
+ self.assertTrue (line_number == self.line, "Hit the first breakpoint.")
+
+ my_var = cur_frame.FindVariable("my")
+ self.assertTrue(my_var, "Made a variable object for my")
+
+ str_var = cur_frame.FindVariable("str")
+ self.assertTrue(str_var, "Made a variable object for str")
+
+ # Now make sure that the my->str == str:
+
+ my_str_var = my_var.GetChildMemberWithName("str")
+ self.assertTrue(my_str_var, "Found a str ivar in my")
+
+ str_value = int(str_var.GetValue(), 0)
+
+ my_str_value = int(my_str_var.GetValue(), 0)
+
+ self.assertTrue(str_value == my_str_value, "Got the correct value for my->str")
+
+ def test_expression_lookups_objc(self):
+ """Test running an expression detect spurious debug info lookups (DWARF)."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Stop at -[MyString initWithNSString:].
+ lldbutil.run_break_set_by_symbol (self, '-[MyString initWithNSString:]', num_expected_locations=1, sym_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ global file_index
+ # Log any DWARF lookups
+ ++file_index
+ logfile = os.path.join(os.getcwd(), "dwarf-lookups-" + self.getArchitecture() + "-" + str(file_index) + ".txt")
+ self.runCmd("log enable -f %s dwarf lookups" % (logfile))
+ self.runCmd("expr self")
+ self.runCmd("log disable dwarf lookups")
+
+ def cleanup():
+ if os.path.exists (logfile):
+ os.unlink (logfile)
+
+ self.addTearDownHook(cleanup)
+
+ if os.path.exists (logfile):
+ f = open(logfile)
+ lines = f.readlines()
+ num_errors = 0
+ for line in lines:
+ if string.find(line, "$__lldb") != -1:
+ if num_errors == 0:
+ print("error: found spurious name lookups when evaluating an expression:")
+ num_errors += 1
+ print(line, end='')
+ self.assertTrue(num_errors == 0, "Spurious lookups detected")
+ f.close()
diff --git a/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods2.py b/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods2.py
new file mode 100644
index 000000000000..b61a7702f1fe
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjCMethods2.py
@@ -0,0 +1,169 @@
+"""
+Test more expression command sequences with objective-c.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+@skipUnlessDarwin
+class FoundationTestCase2(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break at.
+ self.lines = []
+ self.lines.append(line_number('main.m', '// Break here for selector: tests'))
+ self.lines.append(line_number('main.m', '// Break here for NSArray tests'))
+ self.lines.append(line_number('main.m', '// Break here for NSString tests'))
+ self.lines.append(line_number('main.m', '// Break here for description test'))
+ self.lines.append(line_number('main.m', '// Set break point at this line'))
+
+ def test_more_expr_commands(self):
+ """More expression commands for objective-c."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Create a bunch of breakpoints.
+ for line in self.lines:
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Test_Selector:
+ self.runCmd("thread backtrace")
+ self.expect("expression (char *)sel_getName(sel)",
+ substrs = ["(char *)",
+ "length"])
+
+ self.runCmd("process continue")
+
+ # Test_NSArray:
+ self.runCmd("thread backtrace")
+ self.runCmd("process continue")
+
+ # Test_NSString:
+ self.runCmd("thread backtrace")
+ self.runCmd("process continue")
+
+ # Test_MyString:
+ self.runCmd("thread backtrace")
+ self.expect("expression (char *)sel_getName(_cmd)",
+ substrs = ["(char *)",
+ "description"])
+
+ self.runCmd("process continue")
+
+ def test_NSArray_expr_commands(self):
+ """Test expression commands for NSArray."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break inside Test_NSArray:
+ line = self.lines[1]
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Test_NSArray:
+ self.runCmd("thread backtrace")
+ self.expect("expression (int)[nil_mutable_array count]",
+ patterns = ["\(int\) \$.* = 0"])
+ self.expect("expression (int)[array1 count]",
+ patterns = ["\(int\) \$.* = 3"])
+ self.expect("expression (int)[array2 count]",
+ patterns = ["\(int\) \$.* = 3"])
+ self.expect("expression (int)array1.count",
+ patterns = ["\(int\) \$.* = 3"])
+ self.expect("expression (int)array2.count",
+ patterns = ["\(int\) \$.* = 3"])
+ self.runCmd("process continue")
+
+ def test_NSString_expr_commands(self):
+ """Test expression commands for NSString."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break inside Test_NSString:
+ line = self.lines[2]
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Test_NSString:
+ self.runCmd("thread backtrace")
+ self.expect("expression (int)[str length]",
+ patterns = ["\(int\) \$.* ="])
+ self.expect("expression (int)[str_id length]",
+ patterns = ["\(int\) \$.* ="])
+ self.expect("expression [str description]",
+ patterns = ["\(id\) \$.* = 0x"])
+ self.expect("expression (id)[str_id description]",
+ patterns = ["\(id\) \$.* = 0x"])
+ self.expect("expression str.length")
+ self.expect("expression str.description")
+ self.expect('expression str = @"new"')
+ self.runCmd("image lookup -t NSString")
+ self.expect('expression str = [NSString stringWithCString: "new"]')
+ self.runCmd("process continue")
+
+ def test_MyString_dump(self):
+ """Test dump of a known Objective-C object by dereferencing it."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ line = self.lines[4]
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.expect("expression --show-types -- *my",
+ patterns = ["\(MyString\) \$.* = ", "\(MyBase\)", "\(NSObject\)", "\(Class\)"])
+ self.runCmd("process continue")
+
+ @expectedFailurei386
+ def test_NSError_po(self):
+ """Test that po of the result of an unknown method doesn't require a cast."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ line = self.lines[4]
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.expect('po [NSError errorWithDomain:@"Hello" code:35 userInfo:@{@"NSDescription" : @"be completed."}]',
+ substrs = ["Error Domain=Hello", "Code=35", "be completed."])
+ self.runCmd("process continue")
+
+ def test_NSError_p(self):
+ """Test that p of the result of an unknown method does require a cast."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ line = self.lines[4]
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.expect("p [NSError thisMethodIsntImplemented:0]",
+ error = True,
+ patterns = ["no known method", "cast the message send to the method's return type"])
+ self.runCmd("process continue")
diff --git a/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjectDescriptionAPI.py b/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjectDescriptionAPI.py
new file mode 100644
index 000000000000..a85f0fec9636
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/foundation/TestObjectDescriptionAPI.py
@@ -0,0 +1,71 @@
+"""
+Test SBValue.GetObjectDescription() with the value from SBTarget.FindGlobalVariables().
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ObjectDescriptionAPITestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.source = 'main.m'
+ self.line = line_number(self.source, '// Set break point at this line.')
+
+ # rdar://problem/10857337
+ @skipUnlessDarwin
+ @add_test_categories(['pyapi'])
+ def test_find_global_variables_then_object_description(self):
+ """Exercise SBTarget.FindGlobalVariables() API."""
+ d = {'EXE': 'b.out'}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ exe = os.path.join(os.getcwd(), 'b.out')
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+ # Make sure we hit our breakpoint:
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint)
+ self.assertTrue (len(thread_list) == 1)
+
+ thread = thread_list[0]
+ frame0 = thread.GetFrameAtIndex(0)
+
+ # Note my_global_str's object description prints fine here.
+ value_list1 = frame0.GetVariables(True, True, True, True)
+ for v in value_list1:
+ self.DebugSBValue(v)
+ if self.TraceOn():
+ print("val:", v)
+ print("object description:", v.GetObjectDescription())
+ if v.GetName() == 'my_global_str':
+ self.assertTrue(v.GetObjectDescription() == 'This is a global string')
+
+ # But not here!
+ value_list2 = target.FindGlobalVariables('my_global_str', 3)
+ for v in value_list2:
+ self.DebugSBValue(v)
+ if self.TraceOn():
+ print("val:", v)
+ print("object description:", v.GetObjectDescription())
+ if v.GetName() == 'my_global_str':
+ self.assertTrue(v.GetObjectDescription() == 'This is a global string')
diff --git a/packages/Python/lldbsuite/test/lang/objc/foundation/TestRuntimeTypes.py b/packages/Python/lldbsuite/test/lang/objc/foundation/TestRuntimeTypes.py
new file mode 100644
index 000000000000..8f191721d89b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/foundation/TestRuntimeTypes.py
@@ -0,0 +1,48 @@
+"""
+Test that Objective-C methods from the runtime work correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+@skipUnlessDarwin
+class RuntimeTypesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def test_break(self):
+ """Test setting objc breakpoints using '_regexp-break' and 'breakpoint set'."""
+ if self.getArchitecture() != 'x86_64':
+ self.skipTest("This only applies to the v2 runtime")
+
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Stop at -[MyString description].
+ lldbutil.run_break_set_by_symbol (self, '-[MyString description]', num_expected_locations=1, sym_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The backtrace should show we stop at -[MyString description].
+ self.expect("thread backtrace", "Stop at -[MyString description]",
+ substrs = ["a.out`-[MyString description]"])
+
+ # Use runtime information about NSString.
+
+ # The length property should be usable.
+ self.expect("expression str.length", VARIABLES_DISPLAYED_CORRECTLY,
+ patterns = [r"(\(unsigned long long\))|\(NSUInteger\)"])
+
+ # Static methods on NSString should work.
+ self.expect("expr [NSString stringWithCString:\"foo\" encoding:1]", VALID_TYPE,
+ substrs = ["(id)", "$1"])
+
+ self.expect("po $1", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["foo"])
diff --git a/packages/Python/lldbsuite/test/lang/objc/foundation/TestSymbolTable.py b/packages/Python/lldbsuite/test/lang/objc/foundation/TestSymbolTable.py
new file mode 100644
index 000000000000..72952c1878b1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/foundation/TestSymbolTable.py
@@ -0,0 +1,68 @@
+"""
+Test symbol table access for main.m.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+
+@skipUnlessDarwin
+class FoundationSymtabTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ symbols_list = ['-[MyString initWithNSString:]',
+ '-[MyString dealloc]',
+ '-[MyString description]',
+ '-[MyString descriptionPauses]', # synthesized property
+ '-[MyString setDescriptionPauses:]', # synthesized property
+ 'Test_Selector',
+ 'Test_NSString',
+ 'Test_MyString',
+ 'Test_NSArray',
+ 'main'
+ ]
+
+ @add_test_categories(['pyapi'])
+ def test_with_python_api(self):
+ """Test symbol table access with Python APIs."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ #
+ # Exercise Python APIs to access the symbol table entries.
+ #
+
+ # Create the filespec by which to locate our a.out module.
+ filespec = lldb.SBFileSpec(exe, False)
+
+ module = target.FindModule(filespec)
+ self.assertTrue(module, VALID_MODULE)
+
+ # Create the set of known symbols. As we iterate through the symbol
+ # table, remove the symbol from the set if it is a known symbol.
+ expected_symbols = set(self.symbols_list)
+ for symbol in module:
+ self.assertTrue(symbol, VALID_SYMBOL)
+ #print("symbol:", symbol)
+ name = symbol.GetName()
+ if name in expected_symbols:
+ #print("Removing %s from known_symbols %s" % (name, expected_symbols))
+ expected_symbols.remove(name)
+
+ # At this point, the known_symbols set should have become an empty set.
+ # If not, raise an error.
+ #print("symbols unaccounted for:", expected_symbols)
+ self.assertTrue(len(expected_symbols) == 0,
+ "All the known symbols are accounted for")
diff --git a/packages/Python/lldbsuite/test/lang/objc/foundation/const-strings.m b/packages/Python/lldbsuite/test/lang/objc/foundation/const-strings.m
new file mode 100644
index 000000000000..8a43abee7b84
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/foundation/const-strings.m
@@ -0,0 +1,24 @@
+#import <Foundation/Foundation.h>
+
+// Tests to run:
+
+// Breakpoint 1
+// --
+// (lldb) expr (int)[str compare:@"hello"]
+// (int) $0 = 0
+// (lldb) expr (int)[str compare:@"world"]
+// (int) $1 = -1
+// (lldb) expr (int)[@"" length]
+// (int) $2 = 0
+
+int main ()
+{
+ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+
+ NSString *str = [NSString stringWithCString:"hello" encoding:NSASCIIStringEncoding];
+
+ NSLog(@"String \"%@\" has length %lu", str, [str length]); // Set breakpoint here.
+
+ [pool drain];
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/foundation/main.m b/packages/Python/lldbsuite/test/lang/objc/foundation/main.m
new file mode 100644
index 000000000000..519bec5a3e6a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/foundation/main.m
@@ -0,0 +1,141 @@
+#import <Foundation/Foundation.h>
+#include <unistd.h>
+#import "my-base.h"
+
+@interface MyString : MyBase {
+ NSString *str;
+ NSDate *date;
+ BOOL _desc_pauses;
+}
+
+@property(retain) NSString * str_property;
+@property BOOL descriptionPauses;
+
+- (id)initWithNSString:(NSString *)string;
+@end
+
+@implementation MyString
+@synthesize descriptionPauses = _desc_pauses;
+@synthesize str_property = str;
+
+- (id)initWithNSString:(NSString *)string
+{
+ if (self = [super init])
+ {
+ str = [NSString stringWithString:string];
+ date = [NSDate date];
+ }
+ self.descriptionPauses = NO;
+ return self;
+}
+
+- (void)dealloc
+{
+ [date release];
+ [str release];
+ [super dealloc];
+}
+
+- (NSString *)description
+{
+ // Set a breakpoint on '-[MyString description]' and test expressions:
+ // expression (char *)sel_getName(_cmd)
+ if (self.descriptionPauses) // Break here for description test
+ {
+ printf ("\nAbout to sleep.\n");
+ usleep(100000);
+ }
+
+ return [str stringByAppendingFormat:@" with timestamp: %@", date];
+}
+@end
+
+int
+Test_Selector ()
+{
+ SEL sel = @selector(length);
+ printf("sel = %p\n", sel);
+ // Expressions to test here for selector:
+ // expression (char *)sel_getName(sel)
+ // The expression above should return "sel" as it should be just
+ // a uniqued C string pointer. We were seeing the result pointer being
+ // truncated with recent LLDBs.
+ return 0; // Break here for selector: tests
+}
+
+int
+Test_NSString (const char *program)
+{
+ NSString *str = [NSString stringWithFormat:@"Hello from '%s'", program];
+ NSLog(@"NSString instance: %@", str);
+ printf("str = '%s'\n", [str cStringUsingEncoding: [NSString defaultCStringEncoding]]);
+ printf("[str length] = %zu\n", (size_t)[str length]);
+ printf("[str description] = %s\n", [[str description] UTF8String]);
+ id str_id = str;
+ // Expressions to test here for NSString:
+ // expression (char *)sel_getName(sel)
+ // expression [str length]
+ // expression [str_id length]
+ // expression [str description]
+ // expression [str_id description]
+ // expression str.length
+ // expression str.description
+ // expression str = @"new"
+ // expression str = [NSString stringWithFormat: @"%cew", 'N']
+ return 0; // Break here for NSString tests
+}
+
+NSString *my_global_str = NULL;
+
+void
+Test_MyString (const char *program)
+{
+ my_global_str = @"This is a global string";
+ NSString *str = [NSString stringWithFormat:@"Hello from '%s'", program];
+ MyString *my = [[MyString alloc] initWithNSString:str];
+ NSLog(@"MyString instance: %@", [my description]);
+ my.descriptionPauses = YES; // Set break point at this line. Test 'expression -o -- my'.
+ NSLog(@"MyString instance: %@", [my description]);
+}
+
+int
+Test_NSArray ()
+{
+ NSMutableArray *nil_mutable_array = nil;
+ NSArray *array1 = [NSArray arrayWithObjects: @"array1 object1", @"array1 object2", @"array1 object3", nil];
+ NSArray *array2 = [NSArray arrayWithObjects: array1, @"array2 object2", @"array2 object3", nil];
+ // Expressions to test here for NSArray:
+ // expression [nil_mutable_array count]
+ // expression [array1 count]
+ // expression array1.count
+ // expression [array2 count]
+ // expression array2.count
+ id obj;
+ // After each object at index call, use expression and validate object
+ obj = [array1 objectAtIndex: 0]; // Break here for NSArray tests
+ obj = [array1 objectAtIndex: 1];
+ obj = [array1 objectAtIndex: 2];
+
+ obj = [array2 objectAtIndex: 0];
+ obj = [array2 objectAtIndex: 1];
+ obj = [array2 objectAtIndex: 2];
+ NSUInteger count = [nil_mutable_array count];
+ return 0;
+}
+
+
+int main (int argc, char const *argv[])
+{
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+ Test_Selector();
+ Test_NSArray ();
+ Test_NSString (argv[0]);
+ Test_MyString (argv[0]);
+
+ printf("sizeof(id) = %zu\n", sizeof(id));
+ printf("sizeof(Class) = %zu\n", sizeof(Class));
+ printf("sizeof(SEL) = %zu\n", sizeof(SEL));
+
+ [pool release];
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/foundation/my-base.h b/packages/Python/lldbsuite/test/lang/objc/foundation/my-base.h
new file mode 100644
index 000000000000..53202aa0de37
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/foundation/my-base.h
@@ -0,0 +1,8 @@
+@interface MyBase : NSObject
+{
+#if !__OBJC2__
+ int maybe_used; // The 1.0 runtime needs to have backed properties...
+#endif
+}
+@property int propertyMovesThings;
+@end
diff --git a/packages/Python/lldbsuite/test/lang/objc/foundation/my-base.m b/packages/Python/lldbsuite/test/lang/objc/foundation/my-base.m
new file mode 100644
index 000000000000..0c316b244f26
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/foundation/my-base.m
@@ -0,0 +1,10 @@
+#import <Foundation/Foundation.h>
+#import "my-base.h"
+@implementation MyBase
+#if __OBJC2__
+@synthesize propertyMovesThings;
+#else
+@synthesize propertyMovesThings = maybe_used;
+#endif
+@end
+
diff --git a/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/InternalDefiner.h b/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/InternalDefiner.h
new file mode 100644
index 000000000000..59652d4b09c0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/InternalDefiner.h
@@ -0,0 +1,11 @@
+#import <Foundation/Foundation.h>
+#import <stdint.h>
+
+@interface InternalDefiner : NSObject {
+@public
+ uintptr_t foo;
+}
+
+-(id)initWithFoo:(uintptr_t)f andBar:(uintptr_t)b;
+
+@end
diff --git a/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/InternalDefiner.m b/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/InternalDefiner.m
new file mode 100644
index 000000000000..1a10ce021ce3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/InternalDefiner.m
@@ -0,0 +1,31 @@
+#import "InternalDefiner.h"
+
+@interface InternalDefiner () {
+ uintptr_t bar;
+}
+
+@end
+
+@implementation InternalDefiner
+
+-(id)init
+{
+ if (self = [super init])
+ {
+ foo = 2;
+ bar = 3;
+ }
+ return self;
+}
+
+-(id)initWithFoo:(uintptr_t)f andBar:(uintptr_t)b
+{
+ if (self = [super init])
+ {
+ foo = f;
+ bar = b;
+ }
+ return self;
+}
+
+@end
diff --git a/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/Makefile b/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/Makefile
new file mode 100644
index 000000000000..1768d11ca279
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../../make
+
+DYLIB_NAME := InternalDefiner
+DYLIB_OBJC_SOURCES := InternalDefiner.m
+OBJC_SOURCES := main.m
+
+LD_EXTRAS = -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/TestHiddenIvars.py b/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/TestHiddenIvars.py
new file mode 100644
index 000000000000..e85dd8f48dec
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/TestHiddenIvars.py
@@ -0,0 +1,174 @@
+"""Test that hidden ivars in a shared library are visible from the main executable."""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+import subprocess
+
+class HiddenIvarsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.source = 'main.m'
+ self.line = line_number(self.source, '// breakpoint1')
+ # The makefile names of the shared libraries as they appear in DYLIB_NAME.
+ # The names should have no loading "lib" or extension as they will be localized
+ self.shlib_names = ["InternalDefiner"]
+
+ @skipUnlessDarwin
+ @skipIfDwarf # This test requires a stripped binary and a dSYM
+ @skipIfDWO # This test requires a stripped binary and a dSYM
+ def test_expr_stripped(self):
+ if self.getArchitecture() == 'i386':
+ self.skipTest("requires modern objc runtime")
+ else:
+ self.build()
+ self.expr(True)
+
+ @skipUnlessDarwin
+ def test_expr(self):
+ if self.getArchitecture() == 'i386':
+ self.skipTest("requires modern objc runtime")
+ else:
+ self.build()
+ self.expr(False)
+
+ @skipUnlessDarwin
+ @skipIfDwarf # This test requires a stripped binary and a dSYM
+ @skipIfDWO # This test requires a stripped binary and a dSYM
+ def test_frame_variable_stripped(self):
+ if self.getArchitecture() == 'i386':
+ self.skipTest("requires modern objc runtime")
+ else:
+ self.build()
+ self.frame_var(True)
+
+ @skipUnlessDarwin
+ def test_frame_variable(self):
+ if self.getArchitecture() == 'i386':
+ self.skipTest("requires modern objc runtime")
+ else:
+ self.build()
+ self.frame_var(False)
+
+ @unittest2.expectedFailure("rdar://18683637")
+ @skipUnlessDarwin
+ def test_frame_variable_across_modules(self):
+ if self.getArchitecture() == 'i386':
+ self.skipTest("requires modern objc runtime")
+ else:
+ self.build()
+ self.common_setup(False)
+ self.expect("frame variable k->bar", VARIABLES_DISPLAYED_CORRECTLY, substrs = ["= 3"])
+
+ def common_setup(self, strip):
+
+ if strip:
+ self.assertTrue(subprocess.call(['/usr/bin/strip', '-Sx', 'libInternalDefiner.dylib']) == 0, 'stripping dylib succeeded')
+ self.assertTrue(subprocess.call(['/bin/rm', '-rf', 'libInternalDefiner.dylib.dSYM']) == 0, 'remove dylib dSYM file succeeded')
+ self.assertTrue(subprocess.call(['/usr/bin/strip', '-Sx', 'a.out']) == 0, 'stripping a.out succeeded')
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget("a.out")
+ self.assertTrue(target, VALID_TARGET)
+
+ # Create the breakpoint inside function 'main'.
+ breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Register our shared libraries for remote targets so they get automatically uploaded
+ environment = self.registerSharedLibrariesWithTarget(target, self.shlib_names)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, environment, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break inside the foo function which takes a bar_ptr argument.
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ def expr(self, strip):
+ self.common_setup(strip)
+
+ # This should display correctly.
+ self.expect("expression (j->_definer->foo)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["= 4"])
+
+ self.expect("expression (j->_definer->bar)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["= 5"])
+
+ if strip:
+ self.expect("expression *(j->_definer)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["foo = 4"])
+ else:
+ self.expect("expression *(j->_definer)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["foo = 4", "bar = 5"])
+
+ self.expect("expression (k->foo)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["= 2"])
+
+ self.expect("expression (k->bar)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["= 3"])
+
+ self.expect("expression k.filteredDataSource", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = [' = 0x', '"2 elements"'])
+
+ if strip:
+ self.expect("expression *(k)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["foo = 2", ' = 0x', '"2 elements"'])
+ else:
+ self.expect("expression *(k)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["foo = 2", "bar = 3", '_filteredDataSource = 0x', '"2 elements"'])
+
+ def frame_var(self, strip):
+ self.common_setup(strip)
+
+ # This should display correctly.
+ self.expect("frame variable j->_definer->foo", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["= 4"])
+
+ if not strip:
+ self.expect("frame variable j->_definer->bar", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["= 5"])
+
+ if strip:
+ self.expect("frame variable *j->_definer", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["foo = 4"])
+ else:
+ self.expect("frame variable *j->_definer", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["foo = 4", "bar = 5"])
+
+ self.expect("frame variable k->foo", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["= 2"])
+
+ self.expect("frame variable k->_filteredDataSource", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = [' = 0x', '"2 elements"'])
+
+ if strip:
+ self.expect("frame variable *k", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["foo = 2", '_filteredDataSource = 0x', '"2 elements"'])
+ else:
+ self.expect("frame variable *k", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["foo = 2", "bar = 3", '_filteredDataSource = 0x', '"2 elements"'])
diff --git a/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/main.m b/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/main.m
new file mode 100644
index 000000000000..1795d56e7d8a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/hidden-ivars/main.m
@@ -0,0 +1,54 @@
+#import <Foundation/Foundation.h>
+#import "InternalDefiner.h"
+
+@interface Container : NSObject {
+@public
+ InternalDefiner *_definer;
+}
+
+-(id)init;
+@end
+
+@implementation Container
+
+-(id)init
+{
+ if (self = [super init])
+ {
+ _definer = [[InternalDefiner alloc] initWithFoo:4 andBar:5];
+ }
+ return self;
+}
+
+@end
+
+@interface InheritContainer : InternalDefiner
+@property (nonatomic, strong) NSMutableArray *filteredDataSource;
+-(id)init;
+@end
+
+@implementation InheritContainer
+
+-(id)init
+{
+ if (self = [super initWithFoo:2 andBar:3])
+ {
+ self.filteredDataSource = [NSMutableArray arrayWithObjects:@"hello", @"world", nil];
+ }
+ return self;
+}
+
+@end
+
+int main(int argc, const char * argv[])
+{
+ @autoreleasepool {
+ Container *j = [[Container alloc] init];
+ InheritContainer *k = [[InheritContainer alloc] init];
+
+ printf("ivar value = %u\n", (unsigned)j->_definer->foo); // breakpoint1
+ printf("ivar value = %u\n", (unsigned)k->foo);
+ }
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/Makefile b/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/Makefile
new file mode 100644
index 000000000000..329ceabeea97
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/Makefile
@@ -0,0 +1,12 @@
+LEVEL = ../../../make
+
+myclass.o: myclass.h myclass.m
+ $(CC) myclass.m -c -o myclass.o
+
+repro: myclass.o repro.m
+ $(CC) -g -O0 myclass.o repro.m -framework Foundation
+
+cleanup:
+ rm -r myclass.o
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/TestObjCiVarIMP.py b/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/TestObjCiVarIMP.py
new file mode 100644
index 000000000000..9ed2bb98e6e1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/TestObjCiVarIMP.py
@@ -0,0 +1,63 @@
+"""
+Test that dynamically discovered ivars of type IMP do not crash LLDB
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+import lldbsuite.support.seven as seven
+
+def execute_command (command):
+ # print('%% %s' % (command))
+ (exit_status, output) = seven.get_command_status_output(command)
+ # if output:
+ # print(output)
+ # print('status = %u' % (exit_status))
+ return exit_status
+
+class ObjCiVarIMPTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipUnlessDarwin
+ @no_debug_info_test
+ def test_imp_ivar_type(self):
+ """Test that dynamically discovered ivars of type IMP do not crash LLDB"""
+ if self.getArchitecture() == 'i386':
+ # rdar://problem/9946499
+ self.skipTest("Dynamic types for ObjC V1 runtime not implemented")
+
+ execute_command("make repro")
+ def cleanup():
+ execute_command("make cleanup")
+ self.addTearDownHook(cleanup)
+
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target from the debugger.
+ target = self.dbg.CreateTarget (exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Set up our breakpoint
+
+ bkpt = lldbutil.run_break_set_by_source_regexp (self, "break here")
+
+ # Now launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+
+ self.expect('frame variable --ptr-depth=1 --show-types -d run -- object', substrs=[
+ '(MyClass *) object = 0x',
+ '(void *) myImp = 0x'
+ ])
+ self.expect('disassemble --start-address `((MyClass*)object)->myImp`', substrs=[
+ '-[MyClass init]'
+ ])
diff --git a/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/myclass.h b/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/myclass.h
new file mode 100644
index 000000000000..da28d1e05181
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/myclass.h
@@ -0,0 +1,6 @@
+#import <Foundation/Foundation.h>
+
+@interface MyClass : NSObject
+{}
+- (id)init;
+@end
diff --git a/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/myclass.m b/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/myclass.m
new file mode 100644
index 000000000000..85b2fcfe9b3c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/myclass.m
@@ -0,0 +1,16 @@
+#import <Foundation/Foundation.h>
+#import "myclass.h"
+
+@implementation MyClass
+{
+ IMP myImp;
+}
+- (id)init {
+ if (self = [super init])
+ {
+ SEL theSelector = @selector(init);
+ self->myImp = [self methodForSelector:theSelector];
+ }
+ return self;
+}
+@end
diff --git a/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/repro.m b/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/repro.m
new file mode 100644
index 000000000000..14f911f07dd8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/ivar-IMP/repro.m
@@ -0,0 +1,7 @@
+#import <Foundation/Foundation.h>
+#import "myclass.h"
+
+int main() {
+ id object = [MyClass new];
+ return 0; // break here
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/Makefile b/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/Makefile
new file mode 100644
index 000000000000..e42b59f9518c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+OBJC_SOURCES := main.m
+
+CFLAGS += -fmodules -gmodules -g
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/TestModulesAutoImport.py b/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/TestModulesAutoImport.py
new file mode 100644
index 000000000000..2c052aae3ba1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/TestModulesAutoImport.py
@@ -0,0 +1,53 @@
+"""Test that importing modules in Objective-C works as expected."""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import lldb
+import platform
+import lldbsuite.test.lldbutil as lldbutil
+
+from distutils.version import StrictVersion
+
+from lldbsuite.test.lldbtest import *
+
+class ObjCModulesAutoImportTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.m', '// Set breakpoint 0 here.')
+
+ @skipUnlessDarwin
+ @unittest2.expectedFailure("rdar://problem/19991953")
+ @expectedFailureDarwin # clang: error: unknown argument: '-gmodules'
+ @unittest2.skipIf(platform.system() != "Darwin" or StrictVersion('12.0.0') > platform.release(), "Only supported on Darwin 12.0.0+")
+ def test_expr(self):
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break inside the foo function which takes a bar_ptr argument.
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ self.runCmd("settings set target.auto-import-clang-modules true")
+
+ self.expect("p getpid()", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["pid_t"])
diff --git a/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/main.m b/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/main.m
new file mode 100644
index 000000000000..5452ffd9bd15
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/modules-auto-import/main.m
@@ -0,0 +1,7 @@
+@import Darwin;
+
+int main()
+{
+ size_t ret = printf("Stop here\n"); // Set breakpoint 0 here.
+ return ret;
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/Makefile b/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/Makefile
new file mode 100644
index 000000000000..cbd95de007d8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m myModule.m
+
+include $(LEVEL)/Makefile.rules
+
+CFLAGS += -fmodules -I$(PWD)
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/TestIncompleteModules.py b/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/TestIncompleteModules.py
new file mode 100644
index 000000000000..8667e628d464
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/TestIncompleteModules.py
@@ -0,0 +1,61 @@
+"""Test that DWARF types are trusted over module types"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import lldb
+import platform
+import lldbsuite.test.lldbutil as lldbutil
+
+from distutils.version import StrictVersion
+
+from lldbsuite.test.lldbtest import *
+
+class IncompleteModulesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.m', '// Set breakpoint 0 here.')
+
+ @skipUnlessDarwin
+ @unittest2.expectedFailure("rdar://20416388")
+ @unittest2.skipIf(platform.system() != "Darwin" or StrictVersion('12.0.0') > platform.release(), "Only supported on Darwin 12.0.0+")
+ def test_expr(self):
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break inside the foo function which takes a bar_ptr argument.
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ self.runCmd("settings set target.clang-module-search-paths \"" + os.getcwd() + "\"")
+
+ self.expect("expr @import myModule; 3", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["int", "3"])
+
+ self.expect("expr [myObject privateMethod]", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["int", "5"])
+
+ self.expect("expr MIN(2,3)", "#defined macro was found",
+ substrs = ["int", "2"])
+
+ self.expect("expr MAX(2,3)", "#undefd macro was correcltly not found",
+ error=True)
diff --git a/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/main.m b/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/main.m
new file mode 100644
index 000000000000..8ebfb0c1f11a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/main.m
@@ -0,0 +1,11 @@
+@import Foundation;
+@import myModule;
+
+int main()
+{
+ @autoreleasepool
+ {
+ MyClass *myObject = [MyClass alloc];
+ [myObject publicMethod]; // Set breakpoint 0 here.
+ }
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/module.map b/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/module.map
new file mode 100644
index 000000000000..2ef8064d15b4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/module.map
@@ -0,0 +1,4 @@
+module myModule {
+ header "myModule.h"
+ export *
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/myModule.h b/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/myModule.h
new file mode 100644
index 000000000000..d03dde0d07aa
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/myModule.h
@@ -0,0 +1,8 @@
+@import Foundation;
+
+#undef MAX
+
+@interface MyClass : NSObject {
+};
+-(void)publicMethod;
+@end
diff --git a/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/myModule.m b/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/myModule.m
new file mode 100644
index 000000000000..d6a2619d8016
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/modules-incomplete/myModule.m
@@ -0,0 +1,14 @@
+#include "myModule.h"
+#include "stdio.h"
+
+@implementation MyClass {
+};
+-(void)publicMethod {
+ printf("Hello public!\n");
+}
+-(int)privateMethod {
+ printf("Hello private!\n");
+ return 5;
+}
+@end
+
diff --git a/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/Makefile b/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/Makefile
new file mode 100644
index 000000000000..6ad9e0010bb0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../../make
+
+C_SOURCES := myModule.c
+
+OBJC_SOURCES := main.m
+
+include $(LEVEL)/Makefile.rules
+
+CFLAGS += -fmodules -I$(PWD)
diff --git a/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/TestModulesInlineFunctions.py b/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/TestModulesInlineFunctions.py
new file mode 100644
index 000000000000..d9d94a8cf321
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/TestModulesInlineFunctions.py
@@ -0,0 +1,55 @@
+"""Test that inline functions from modules are imported correctly"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import lldb
+import platform
+import lldbsuite.test.lldbutil as lldbutil
+
+from distutils.version import StrictVersion
+
+from lldbsuite.test.lldbtest import *
+
+class ModulesInlineFunctionsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.m', '// Set breakpoint here.')
+
+ @skipUnlessDarwin
+ @unittest2.skipIf(platform.system() != "Darwin" or StrictVersion('12.0.0') > platform.release(), "Only supported on Darwin 12.0.0+")
+ @expectedFailureDarwin("llvm.org/pr25743")
+ def test_expr(self):
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break inside the foo function which takes a bar_ptr argument.
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ self.runCmd("settings set target.clang-module-search-paths \"" + os.getcwd() + "\"")
+
+ self.expect("expr @import myModule; 3", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["int", "3"])
+
+ self.expect("expr isInline(2)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["4"])
diff --git a/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/main.m b/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/main.m
new file mode 100644
index 000000000000..13a5bf316ee9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/main.m
@@ -0,0 +1,9 @@
+@import Darwin;
+@import myModule;
+
+int main()
+{
+ int a = isInline(2);
+ int b = notInline();
+ printf("%d %d\n", a, b); // Set breakpoint here.
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/module.map b/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/module.map
new file mode 100644
index 000000000000..2ef8064d15b4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/module.map
@@ -0,0 +1,4 @@
+module myModule {
+ header "myModule.h"
+ export *
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/myModule.c b/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/myModule.c
new file mode 100644
index 000000000000..ad3c85d155e4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/myModule.c
@@ -0,0 +1,7 @@
+#include "myModule.h"
+
+int notInline()
+{
+ return 3;
+}
+
diff --git a/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/myModule.h b/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/myModule.h
new file mode 100644
index 000000000000..d50d0101f645
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/modules-inline-functions/myModule.h
@@ -0,0 +1,7 @@
+int notInline();
+
+static __inline__ __attribute__ ((always_inline)) int isInline(int a)
+{
+ int b = a + a;
+ return b;
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/modules/Makefile b/packages/Python/lldbsuite/test/lang/objc/modules/Makefile
new file mode 100644
index 000000000000..ad3cb3fadcde
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/modules/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/lang/objc/modules/TestObjCModules.py b/packages/Python/lldbsuite/test/lang/objc/modules/TestObjCModules.py
new file mode 100644
index 000000000000..04fc07281811
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/modules/TestObjCModules.py
@@ -0,0 +1,71 @@
+"""Test that importing modules in Objective-C works as expected."""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import lldb
+import platform
+import lldbsuite.test.lldbutil as lldbutil
+
+from distutils.version import StrictVersion
+
+from lldbsuite.test.lldbtest import *
+
+class ObjCModulesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.m', '// Set breakpoint 0 here.')
+
+ @skipUnlessDarwin
+ @unittest2.expectedFailure("rdar://20416388")
+ @unittest2.skipIf(platform.system() != "Darwin" or StrictVersion('12.0.0') > platform.release(), "Only supported on Darwin 12.0.0+")
+ def test_expr(self):
+ if not self.applies():
+ return
+
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break inside the foo function which takes a bar_ptr argument.
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ self.expect("expr @import Darwin; 3", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["int", "3"])
+
+ self.expect("expr getpid()", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["pid_t"])
+
+ self.expect("expr @import Foundation; 4", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["int", "4"])
+
+ self.expect("expr string.length", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["NSUInteger", "5"])
+
+ self.expect("expr array.count", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["NSUInteger", "3"])
+
+ self.expect("p *[NSURL URLWithString:@\"http://lldb.llvm.org\"]", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["NSURL", "isa", "_urlString"])
+
+ self.expect("p [NSURL URLWithString:@\"http://lldb.llvm.org\"].scheme", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["http"])
diff --git a/packages/Python/lldbsuite/test/lang/objc/modules/main.m b/packages/Python/lldbsuite/test/lang/objc/modules/main.m
new file mode 100644
index 000000000000..99b50f9620d6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/modules/main.m
@@ -0,0 +1,12 @@
+#import <Foundation/Foundation.h>
+
+int main()
+{
+ @autoreleasepool
+ {
+ NSString *string = @"Hello";
+ NSArray *array = @[ @1, @2, @3 ];
+
+ NSLog(@"Stop here"); // Set breakpoint 0 here.
+ }
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc++/Makefile b/packages/Python/lldbsuite/test/lang/objc/objc++/Makefile
new file mode 100644
index 000000000000..910d4943ef05
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc++/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+OBJCXX_SOURCES := main.mm
+LD_EXTRAS = -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc++/TestObjCXX.py b/packages/Python/lldbsuite/test/lang/objc/objc++/TestObjCXX.py
new file mode 100644
index 000000000000..38ef853ae112
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc++/TestObjCXX.py
@@ -0,0 +1,33 @@
+"""
+Make sure that ivars of Objective-C++ classes are visible in LLDB.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ObjCXXTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipUnlessDarwin
+ def test_break(self):
+ """Test ivars of Objective-C++ classes"""
+ if self.getArchitecture() == 'i386':
+ self.skipTest("requires Objective-C 2.0 runtime")
+
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_source_regexp (self, 'breakpoint 1', num_expected_locations=1)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.expect("expr f->f", "Found ivar in class",
+ substrs = ["= 3"])
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc++/main.mm b/packages/Python/lldbsuite/test/lang/objc/objc++/main.mm
new file mode 100644
index 000000000000..50d2f0a8df37
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc++/main.mm
@@ -0,0 +1,19 @@
+#include <Foundation/NSObject.h>
+
+@interface F : NSObject
+@end
+
+@implementation F
+{
+@public
+ int f;
+}
+
+@end
+
+int main(int argc, char* argv[])
+{
+ F* f = [F new];
+ f->f = 3;
+ return 0; // breakpoint 1
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/Makefile b/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/Makefile
new file mode 100644
index 000000000000..7f7baeb3cf1c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+LD_EXTRAS = -lobjc -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/TestObjCBaseClassSBType.py b/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/TestObjCBaseClassSBType.py
new file mode 100644
index 000000000000..5d2414eed8f5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/TestObjCBaseClassSBType.py
@@ -0,0 +1,58 @@
+"""
+Use lldb Python API to test base class resolution for ObjC classes
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ObjCDynamicValueTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+
+ self.line = line_number('main.m', '// Set breakpoint here.')
+
+ @skipUnlessDarwin
+ @add_test_categories(['pyapi'])
+ def test_get_baseclass(self):
+ """Test fetching ObjC dynamic values."""
+ if self.getArchitecture() == 'i386':
+ # rdar://problem/9946499
+ self.skipTest("Dynamic types for ObjC V1 runtime not implemented")
+
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target from the debugger.
+
+ target = self.dbg.CreateTarget (exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Set up our breakpoints:
+
+ target.BreakpointCreateByLocation('main.m', self.line)
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+
+ var = self.frame().FindVariable("foo")
+ var_ptr_type = var.GetType()
+ var_pte_type = var_ptr_type.GetPointeeType()
+ self.assertTrue(var_ptr_type.GetNumberOfDirectBaseClasses() == 1, "Foo * has one base class")
+ self.assertTrue(var_pte_type.GetNumberOfDirectBaseClasses() == 1, "Foo has one base class")
+
+ self.assertTrue(var_ptr_type.GetDirectBaseClassAtIndex(0).IsValid(), "Foo * has a valid base class")
+ self.assertTrue(var_pte_type.GetDirectBaseClassAtIndex(0).IsValid(), "Foo * has a valid base class")
+
+ self.assertTrue(var_ptr_type.GetDirectBaseClassAtIndex(0).GetName() == var_pte_type.GetDirectBaseClassAtIndex(0).GetName(), "Foo and its pointer type don't agree on their base class")
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/main.m b/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/main.m
new file mode 100644
index 000000000000..3ec78fd0bd6b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-baseclass-sbtype/main.m
@@ -0,0 +1,22 @@
+#import <Foundation/Foundation.h>
+
+@interface Foo : NSObject {}
+
+-(id) init;
+
+@end
+
+@implementation Foo
+
+-(id) init
+{
+ return self = [super init];
+}
+@end
+int main ()
+{
+ Foo *foo = [Foo new];
+ NSLog(@"a"); // Set breakpoint here.
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/Makefile b/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/TestObjCBuiltinTypes.py b/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/TestObjCBuiltinTypes.py
new file mode 100644
index 000000000000..f7ce2809081a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/TestObjCBuiltinTypes.py
@@ -0,0 +1,55 @@
+"""Test that the expression parser doesn't get confused by 'id' and 'Class'"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TestObjCBuiltinTypes(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break inside main().
+ self.main_source = "main.cpp"
+ self.break_line = line_number(self.main_source, '// Set breakpoint here.')
+
+ @skipUnlessDarwin
+ @add_test_categories(['pyapi'])
+ #<rdar://problem/10591460> [regression] Can't print ivar value: error: reference to 'id' is ambiguous
+ def test_with_python_api(self):
+ """Test expression parser respect for ObjC built-in types."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line)
+ self.assertTrue(bpt, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, bpt)
+
+ # Make sure we stopped at the first breakpoint.
+ self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.")
+ self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.")
+
+ # Now make sure we can call a function in the class method we've stopped in.
+ frame = thread_list[0].GetFrameAtIndex(0)
+ self.assertTrue (frame, "Got a valid frame 0 frame.")
+
+ self.expect("expr (foo)", patterns = ["\(ns::id\) \$.* = 0"])
+
+ self.expect("expr id my_id = 0; my_id", patterns = ["\(id\) \$.* = nil"])
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/main.cpp b/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/main.cpp
new file mode 100644
index 000000000000..6dd8cbc6e9fe
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-builtin-types/main.cpp
@@ -0,0 +1,9 @@
+namespace ns {
+ typedef int id;
+};
+
+int main()
+{
+ ns::id foo = 0;
+ return foo; // Set breakpoint here.
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-checker/Makefile b/packages/Python/lldbsuite/test/lang/objc/objc-checker/Makefile
new file mode 100644
index 000000000000..a1608fe5a664
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-checker/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+LDFLAGS = $(CFLAGS) -lobjc -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-checker/TestObjCCheckers.py b/packages/Python/lldbsuite/test/lang/objc/objc-checker/TestObjCCheckers.py
new file mode 100644
index 000000000000..533ec2f6b7c4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-checker/TestObjCCheckers.py
@@ -0,0 +1,75 @@
+"""
+Use lldb Python API to make sure the dynamic checkers are doing their jobs.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ObjCCheckerTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+
+ # Find the line number to break for main.c.
+ self.source_name = 'main.m'
+
+ @skipUnlessDarwin
+ @add_test_categories(['pyapi'])
+ def test_objc_checker(self):
+ """Test that checkers catch unrecognized selectors"""
+ if self.getArchitecture() == 'i386':
+ self.skipTest("requires Objective-C 2.0 runtime")
+
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target from the debugger.
+
+ target = self.dbg.CreateTarget (exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Set up our breakpoints:
+
+
+ main_bkpt = target.BreakpointCreateBySourceRegex ("Set a breakpoint here.", lldb.SBFileSpec (self.source_name))
+ self.assertTrue(main_bkpt and
+ main_bkpt.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, main_bkpt)
+ self.assertTrue (len(threads) == 1)
+ thread = threads[0]
+
+ #
+ # The class Simple doesn't have a count method. Make sure that we don't
+ # actually try to send count but catch it as an unrecognized selector.
+
+ frame = thread.GetFrameAtIndex(0)
+ expr_value = frame.EvaluateExpression("(int) [my_simple count]", False)
+ expr_error = expr_value.GetError()
+
+ self.assertTrue (expr_error.Fail())
+
+ # Make sure the call produced no NSLog stdout.
+ stdout = process.GetSTDOUT(100)
+ self.assertTrue (stdout is None or (len(stdout) == 0))
+
+ # Make sure the error is helpful:
+ err_string = expr_error.GetCString()
+ self.assertTrue ("selector" in err_string)
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-checker/main.m b/packages/Python/lldbsuite/test/lang/objc/objc-checker/main.m
new file mode 100644
index 000000000000..4a09a2826f70
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-checker/main.m
@@ -0,0 +1,32 @@
+#import <Foundation/Foundation.h>
+
+@interface Simple : NSObject
+{
+ int _value;
+}
+- (int) value;
+- (void) setValue: (int) newValue;
+@end
+
+@implementation Simple
+- (int) value
+{
+ return _value;
+}
+
+- (void) setValue: (int) newValue
+{
+ _value = newValue;
+}
+@end
+
+int main ()
+{
+ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+ Simple *my_simple = [[Simple alloc] init];
+ my_simple.value = 20;
+ // Set a breakpoint here.
+ NSLog (@"Object has value: %d.", my_simple.value);
+ [pool drain];
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-class-method/Makefile b/packages/Python/lldbsuite/test/lang/objc/objc-class-method/Makefile
new file mode 100644
index 000000000000..c2d07910a6e8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-class-method/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := class.m
+LDFLAGS = $(CFLAGS) -lobjc -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-class-method/TestObjCClassMethod.py b/packages/Python/lldbsuite/test/lang/objc/objc-class-method/TestObjCClassMethod.py
new file mode 100644
index 000000000000..2a978bc9c024
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-class-method/TestObjCClassMethod.py
@@ -0,0 +1,56 @@
+"""Test calling functions in class methods."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TestObjCClassMethod(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break inside main().
+ self.main_source = "class.m"
+ self.break_line = line_number(self.main_source, '// Set breakpoint here.')
+
+ @skipUnlessDarwin
+ @expectedFailurei386
+ @add_test_categories(['pyapi'])
+ #rdar://problem/9745789 "expression" can't call functions in class methods
+ def test_with_python_api(self):
+ """Test calling functions in class methods."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line)
+ self.assertTrue(bpt, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, bpt)
+
+ # Make sure we stopped at the first breakpoint.
+ self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.")
+ self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.")
+
+ # Now make sure we can call a function in the class method we've stopped in.
+ frame = thread_list[0].GetFrameAtIndex(0)
+ self.assertTrue (frame, "Got a valid frame 0 frame.")
+
+ cmd_value = frame.EvaluateExpression ("(int)[Foo doSomethingWithString:@\"Hello\"]")
+ self.assertTrue (cmd_value.IsValid())
+ self.assertTrue (cmd_value.GetValueAsUnsigned() == 5)
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-class-method/class.m b/packages/Python/lldbsuite/test/lang/objc/objc-class-method/class.m
new file mode 100644
index 000000000000..18a2c2729bea
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-class-method/class.m
@@ -0,0 +1,24 @@
+#import <Foundation/Foundation.h>
+
+@interface Foo : NSObject
++(int) doSomethingWithString: (NSString *) string;
+-(int) doSomethingInstance: (NSString *) string;
+@end
+
+@implementation Foo
++(int) doSomethingWithString: (NSString *) string
+{
+ NSLog (@"String is: %@.", string);
+ return [string length];
+}
+
+-(int) doSomethingInstance: (NSString *)string
+{
+ return [Foo doSomethingWithString:string];
+}
+@end
+
+int main()
+{
+ return 0; // Set breakpoint here.
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/.categories b/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/.categories
new file mode 100644
index 000000000000..9526bab96fbb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/.categories
@@ -0,0 +1 @@
+dyntype
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/Makefile b/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/Makefile
new file mode 100644
index 000000000000..dd909afba21b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+
+include $(LEVEL)/Makefile.rules
+
+LD_EXTRAS = -framework Foundation
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/TestObjCDynamicSBType.py b/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/TestObjCDynamicSBType.py
new file mode 100644
index 000000000000..b9e84541e2df
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/TestObjCDynamicSBType.py
@@ -0,0 +1,62 @@
+"""
+Test that we are able to properly report a usable dynamic type
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+@skipUnlessDarwin
+class ObjCDynamicSBTypeTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # We'll use the test method name as the exe_name.
+ self.exe_name = self.testMethodName
+ # Find the line number to break inside main().
+ self.main_source = "main.m"
+ self.line = line_number(self.main_source, '// Set breakpoint here.')
+
+ @skipIfi386
+ def test_dyn(self):
+ """Test that we are able to properly report a usable dynamic type."""
+ d = {'EXE': self.exe_name}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+
+ exe = os.path.join(os.getcwd(), self.exe_name)
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, self.main_source, self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ v_object = self.frame().FindVariable("object").GetDynamicValue(lldb.eDynamicCanRunTarget)
+ v_base = self.frame().FindVariable("base").GetDynamicValue(lldb.eDynamicCanRunTarget)
+ self.assertTrue(v_object.GetTypeName() == "MyDerivedClass *", "The NSObject is properly type-named")
+ self.assertTrue(v_base.GetTypeName() == "MyDerivedClass *", "The Base is properly type-named")
+ object_type = v_object.GetType()
+ base_type = v_base.GetType()
+ self.assertTrue(object_type.GetName() == "MyDerivedClass *", "The dynamic SBType for NSObject is for the correct type")
+ self.assertTrue(base_type.GetName() == "MyDerivedClass *", "The dynamic SBType for Base is for the correct type")
+ object_pointee_type = object_type.GetPointeeType()
+ base_pointee_type = base_type.GetPointeeType()
+ self.assertTrue(object_pointee_type.GetName() == "MyDerivedClass", "The dynamic type for NSObject figures out its pointee type just fine")
+ self.assertTrue(base_pointee_type.GetName() == "MyDerivedClass", "The dynamic type for Base figures out its pointee type just fine")
+
+ self.assertTrue(object_pointee_type.GetDirectBaseClassAtIndex(0).GetName() == "MyBaseClass", "The dynamic type for NSObject can go back to its base class")
+ self.assertTrue(base_pointee_type.GetDirectBaseClassAtIndex(0).GetName() == "MyBaseClass", "The dynamic type for Base can go back to its base class")
+
+ self.assertTrue(object_pointee_type.GetDirectBaseClassAtIndex(0).GetType().GetDirectBaseClassAtIndex(0).GetName() == "NSObject", "The dynamic type for NSObject can go up the hierarchy")
+ self.assertTrue(base_pointee_type.GetDirectBaseClassAtIndex(0).GetType().GetDirectBaseClassAtIndex(0).GetName() == "NSObject", "The dynamic type for Base can go up the hierarchy")
+
+ self.assertTrue(object_pointee_type.GetNumberOfFields() == 2, "The dynamic type for NSObject has 2 fields")
+ self.assertTrue(base_pointee_type.GetNumberOfFields() == 2, "The dynamic type for Base has 2 fields")
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/main.m b/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/main.m
new file mode 100644
index 000000000000..f3587b52cd5f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-dyn-sbtype/main.m
@@ -0,0 +1,53 @@
+#import <Foundation/Foundation.h>
+
+@interface MyBaseClass : NSObject
+{}
+-(id) init;
+-(int) getInt;
+@end
+
+@implementation MyBaseClass
+- (id) init {
+ return (self = [super init]);
+}
+
+- (int) getInt {
+ return 1;
+}
+@end
+
+@interface MyDerivedClass : MyBaseClass
+{
+ int x;
+ int y;
+}
+-(id) init;
+-(int) getInt;
+@end
+
+@implementation MyDerivedClass
+- (id) init {
+ self = [super init];
+ if (self) {
+ self-> x = 0;
+ self->y = 1;
+ }
+ return self;
+}
+
+- (int) getInt {
+ y = x++;
+ return x;
+}
+@end
+
+
+int main (int argc, char const *argv[])
+{
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+ NSObject* object = [[MyDerivedClass alloc] init];
+ MyBaseClass* base = [[MyDerivedClass alloc] init];
+ [pool release]; // Set breakpoint here.
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/Makefile b/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/Makefile
new file mode 100644
index 000000000000..a981f4b9035e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := dynamic-value.m
+LDFLAGS = $(CFLAGS) -lobjc -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/TestObjCDynamicValue.py b/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/TestObjCDynamicValue.py
new file mode 100644
index 000000000000..acddfb8bd647
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/TestObjCDynamicValue.py
@@ -0,0 +1,177 @@
+"""
+Use lldb Python API to test dynamic values in ObjC
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ObjCDynamicValueTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+
+ # Find the line number to break for main.c.
+
+ self.source_name = 'dynamic-value.m'
+ self.set_property_line = line_number(self.source_name, '// This is the line in setProperty, make sure we step to here.')
+ self.handle_SourceBase = line_number(self.source_name,
+ '// Break here to check dynamic values.')
+ self.main_before_setProperty_line = line_number(self.source_name,
+ '// Break here to see if we can step into real method.')
+
+ @skipUnlessDarwin
+ @add_test_categories(['pyapi'])
+ @expectedFailureDarwin("llvm.org/pr20271 rdar://18684107")
+ def test_get_objc_dynamic_vals(self):
+ """Test fetching ObjC dynamic values."""
+ if self.getArchitecture() == 'i386':
+ # rdar://problem/9946499
+ self.skipTest("Dynamic types for ObjC V1 runtime not implemented")
+
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target from the debugger.
+
+ target = self.dbg.CreateTarget (exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Set up our breakpoints:
+
+ handle_SourceBase_bkpt = target.BreakpointCreateByLocation(self.source_name, self.handle_SourceBase)
+ self.assertTrue(handle_SourceBase_bkpt and
+ handle_SourceBase_bkpt.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ main_before_setProperty_bkpt = target.BreakpointCreateByLocation(self.source_name, self.main_before_setProperty_line)
+ self.assertTrue(main_before_setProperty_bkpt and
+ main_before_setProperty_bkpt.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, main_before_setProperty_bkpt)
+ self.assertTrue (len(threads) == 1)
+ thread = threads[0]
+
+ #
+ # At this point, myObserver has a Source pointer that is actually a KVO swizzled SourceDerived
+ # make sure we can get that properly:
+
+ frame = thread.GetFrameAtIndex(0)
+ myObserver = frame.FindVariable('myObserver', lldb.eDynamicCanRunTarget)
+ self.assertTrue (myObserver)
+ myObserver_source = myObserver.GetChildMemberWithName ('_source', lldb.eDynamicCanRunTarget)
+ self.examine_SourceDerived_ptr (myObserver_source)
+
+ #
+ # Make sure a static value can be correctly turned into a dynamic value.
+
+ frame = thread.GetFrameAtIndex(0)
+ myObserver_static = frame.FindVariable('myObserver', lldb.eNoDynamicValues)
+ self.assertTrue (myObserver_static)
+ myObserver = myObserver_static.GetDynamicValue (lldb.eDynamicCanRunTarget)
+ myObserver_source = myObserver.GetChildMemberWithName ('_source', lldb.eDynamicCanRunTarget)
+ self.examine_SourceDerived_ptr (myObserver_source)
+
+ # The "frame var" code uses another path to get into children, so let's
+ # make sure that works as well:
+
+ result = lldb.SBCommandReturnObject()
+
+ self.expect('frame var -d run-target myObserver->_source', 'frame var finds its way into a child member',
+ patterns = ['\(SourceDerived \*\)'])
+
+ # check that our ObjC GetISA() does a good job at hiding KVO swizzled classes
+
+ self.expect('frame var -d run-target myObserver->_source -T', 'the KVO-ed class is hidden',
+ substrs = ['SourceDerived'])
+
+ self.expect('frame var -d run-target myObserver->_source -T', 'the KVO-ed class is hidden', matching = False,
+ substrs = ['NSKVONotify'])
+
+ # This test is not entirely related to the main thrust of this test case, but since we're here,
+ # try stepping into setProperty, and make sure we get into the version in Source:
+
+ thread.StepInto()
+
+ threads = lldbutil.get_stopped_threads (process, lldb.eStopReasonPlanComplete)
+ self.assertTrue (len(threads) == 1)
+ line_entry = threads[0].GetFrameAtIndex(0).GetLineEntry()
+
+ self.assertEqual (line_entry.GetLine(), self.set_property_line)
+ self.assertEqual (line_entry.GetFileSpec().GetFilename(), self.source_name)
+
+ # Okay, back to the main business. Continue to the handle_SourceBase and make sure we get the correct dynamic value.
+
+ threads = lldbutil.continue_to_breakpoint (process, handle_SourceBase_bkpt)
+ self.assertTrue (len(threads) == 1)
+ thread = threads[0]
+
+ frame = thread.GetFrameAtIndex(0)
+
+ # Get "object" using FindVariable:
+
+ noDynamic = lldb.eNoDynamicValues
+ useDynamic = lldb.eDynamicCanRunTarget
+
+ object_static = frame.FindVariable ('object', noDynamic)
+ object_dynamic = frame.FindVariable ('object', useDynamic)
+
+ # Delete this object to make sure that this doesn't cause havoc with the dynamic object that depends on it.
+ del (object_static)
+
+ self.examine_SourceDerived_ptr (object_dynamic)
+
+ # Get "this" using FindValue, make sure that works too:
+ object_static = frame.FindValue ('object', lldb.eValueTypeVariableArgument, noDynamic)
+ object_dynamic = frame.FindValue ('object', lldb.eValueTypeVariableArgument, useDynamic)
+ del (object_static)
+ self.examine_SourceDerived_ptr (object_dynamic)
+
+ # Get "this" using the EvaluateExpression:
+ object_static = frame.EvaluateExpression ('object', noDynamic)
+ object_dynamic = frame.EvaluateExpression ('object', useDynamic)
+ del (object_static)
+ self.examine_SourceDerived_ptr (object_dynamic)
+
+ # Continue again to the handle_SourceBase and make sure we get the correct dynamic value.
+ # This one looks exactly the same, but in fact this is an "un-KVO'ed" version of SourceBase, so
+ # its isa pointer points to SourceBase not NSKVOSourceBase or whatever...
+
+ threads = lldbutil.continue_to_breakpoint (process, handle_SourceBase_bkpt)
+ self.assertTrue (len(threads) == 1)
+ thread = threads[0]
+
+ frame = thread.GetFrameAtIndex(0)
+
+ # Get "object" using FindVariable:
+
+ object_static = frame.FindVariable ('object', noDynamic)
+ object_dynamic = frame.FindVariable ('object', useDynamic)
+
+ # Delete this object to make sure that this doesn't cause havoc with the dynamic object that depends on it.
+ del (object_static)
+
+ self.examine_SourceDerived_ptr (object_dynamic)
+
+ def examine_SourceDerived_ptr (self, object):
+ self.assertTrue (object)
+ self.assertTrue (object.GetTypeName().find ('SourceDerived') != -1)
+ derivedValue = object.GetChildMemberWithName ('_derivedValue')
+ self.assertTrue (derivedValue)
+ self.assertTrue (int (derivedValue.GetValue(), 0) == 30)
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/dynamic-value.m b/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/dynamic-value.m
new file mode 100644
index 000000000000..2bcb76b1d9dc
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-dynamic-value/dynamic-value.m
@@ -0,0 +1,147 @@
+#import <Foundation/Foundation.h>
+
+// SourceBase will be the base class of Source. We'll pass a Source object into a
+// function as a SourceBase, and then see if the dynamic typing can get us through the KVO
+// goo and all the way back to Source.
+
+@interface SourceBase: NSObject
+{
+ uint32_t _value;
+}
+- (SourceBase *) init;
+- (uint32_t) getValue;
+@end
+
+@implementation SourceBase
+- (SourceBase *) init
+{
+ [super init];
+ _value = 10;
+ return self;
+}
+- (uint32_t) getValue
+{
+ return _value;
+}
+@end
+
+// Source is a class that will be observed by the Observer class below.
+// When Observer sets itself up to observe this property (in initWithASource)
+// the KVO system will overwrite the "isa" pointer of the object with the "kvo'ed"
+// one.
+
+@interface Source : SourceBase
+{
+ int _property;
+}
+- (Source *) init;
+- (void) setProperty: (int) newValue;
+@end
+
+@implementation Source
+- (Source *) init
+{
+ [super init];
+ _property = 20;
+ return self;
+}
+- (void) setProperty: (int) newValue
+{
+ _property = newValue; // This is the line in setProperty, make sure we step to here.
+}
+@end
+
+@interface SourceDerived : Source
+{
+ int _derivedValue;
+}
+- (SourceDerived *) init;
+- (uint32_t) getValue;
+@end
+
+@implementation SourceDerived
+- (SourceDerived *) init
+{
+ [super init];
+ _derivedValue = 30;
+ return self;
+}
+- (uint32_t) getValue
+{
+ return _derivedValue;
+}
+@end
+
+// Observer is the object that will watch Source and cause KVO to swizzle it...
+
+@interface Observer : NSObject
+{
+ Source *_source;
+}
++ (Observer *) observerWithSource: (Source *) source;
+- (Observer *) initWithASource: (Source *) source;
+- (void) observeValueForKeyPath: (NSString *) path
+ ofObject: (id) object
+ change: (NSDictionary *) change
+ context: (void *) context;
+@end
+
+@implementation Observer
+
++ (Observer *) observerWithSource: (Source *) inSource;
+{
+ Observer *retval;
+
+ retval = [[Observer alloc] initWithASource: inSource];
+ return retval;
+}
+
+- (Observer *) initWithASource: (Source *) source
+{
+ [super init];
+ _source = source;
+ [_source addObserver: self
+ forKeyPath: @"property"
+ options: (NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
+ context: NULL];
+ return self;
+}
+
+- (void) observeValueForKeyPath: (NSString *) path
+ ofObject: (id) object
+ change: (NSDictionary *) change
+ context: (void *) context
+{
+ printf ("Observer function called.\n");
+ return;
+}
+@end
+
+uint32_t
+handle_SourceBase (SourceBase *object)
+{
+ return [object getValue]; // Break here to check dynamic values.
+}
+
+int main ()
+{
+ Source *mySource;
+ Observer *myObserver;
+
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+
+ mySource = [[SourceDerived alloc] init];
+ myObserver = [Observer observerWithSource: mySource];
+
+ [mySource setProperty: 5]; // Break here to see if we can step into real method.
+
+ uint32_t return_value = handle_SourceBase (mySource);
+
+ SourceDerived *unwatchedSource = [[SourceDerived alloc] init];
+
+ return_value = handle_SourceBase (unwatchedSource);
+
+ [pool release];
+ return 0;
+
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/Makefile b/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/Makefile
new file mode 100644
index 000000000000..fdd3b5ebfa9e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := objc-ivar-offsets.m main.m
+LDFLAGS = $(CFLAGS) -lobjc -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/TestObjCIvarOffsets.py b/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/TestObjCIvarOffsets.py
new file mode 100644
index 000000000000..6be1d379c8eb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/TestObjCIvarOffsets.py
@@ -0,0 +1,74 @@
+"""Test printing ObjC objects that use unbacked properties - so that the static ivar offsets are incorrect."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TestObjCIvarOffsets(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break inside main().
+ self.main_source = "main.m"
+ self.stop_line = line_number(self.main_source, '// Set breakpoint here.')
+
+ @skipUnlessDarwin
+ @add_test_categories(['pyapi'])
+ def test_with_python_api(self):
+ """Test printing ObjC objects that use unbacked properties"""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByLocation(self.main_source, self.stop_line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue (process, "Created a process.")
+ self.assertTrue (process.GetState() == lldb.eStateStopped, "Stopped it too.")
+
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint)
+ self.assertTrue (len(thread_list) == 1)
+ thread = thread_list[0]
+
+ frame = thread.GetFrameAtIndex(0)
+ self.assertTrue (frame, "frame 0 is valid")
+
+ mine = thread.GetFrameAtIndex(0).FindVariable("mine")
+ self.assertTrue(mine, "Found local variable mine.")
+
+ # Test the value object value for BaseClass->_backed_int
+
+ error = lldb.SBError()
+
+ mine_backed_int = mine.GetChildMemberWithName ("_backed_int")
+ self.assertTrue(mine_backed_int, "Found mine->backed_int local variable.")
+ backed_value = mine_backed_int.GetValueAsSigned (error)
+ self.assertTrue (error.Success())
+ self.assertTrue (backed_value == 1111)
+
+ # Test the value object value for DerivedClass->_derived_backed_int
+
+ mine_derived_backed_int = mine.GetChildMemberWithName ("_derived_backed_int")
+ self.assertTrue(mine_derived_backed_int, "Found mine->derived_backed_int local variable.")
+ derived_backed_value = mine_derived_backed_int.GetValueAsSigned (error)
+ self.assertTrue (error.Success())
+ self.assertTrue (derived_backed_value == 3333)
+
+ # Make sure we also get bit-field offsets correct:
+
+ mine_flag2 = mine.GetChildMemberWithName ("flag2")
+ self.assertTrue(mine_flag2, "Found mine->flag2 local variable.")
+ flag2_value = mine_flag2.GetValueAsUnsigned (error)
+ self.assertTrue (error.Success())
+ self.assertTrue (flag2_value == 7)
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/main.m b/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/main.m
new file mode 100644
index 000000000000..41943f48aef5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/main.m
@@ -0,0 +1,15 @@
+#include "objc-ivar-offsets.h"
+
+int
+main ()
+{
+ DerivedClass *mine = [[DerivedClass alloc] init];
+ mine.backed_int = 1111;
+ mine.unbacked_int = 2222;
+ mine.derived_backed_int = 3333;
+ mine.derived_unbacked_int = 4444;
+ mine->flag1 = 1;
+ mine->flag2 = 7;
+
+ return 0; // Set breakpoint here.
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/objc-ivar-offsets.h b/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/objc-ivar-offsets.h
new file mode 100644
index 000000000000..99bbd427b064
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/objc-ivar-offsets.h
@@ -0,0 +1,27 @@
+#import <Foundation/Foundation.h>
+
+@interface BaseClass : NSObject
+{
+ int _backed_int;
+#if !__OBJC2__
+ int _unbacked_int;
+#endif
+}
+@property int backed_int;
+@property int unbacked_int;
+@end
+
+@interface DerivedClass : BaseClass
+{
+ int _derived_backed_int;
+#if !__OBJC2__
+ int _derived_unbacked_int;
+#endif
+ @public
+ uint32_t flag1 : 1;
+ uint32_t flag2 : 3;
+}
+
+@property int derived_backed_int;
+@property int derived_unbacked_int;
+@end
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/objc-ivar-offsets.m b/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/objc-ivar-offsets.m
new file mode 100644
index 000000000000..db87adea3d13
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-ivar-offsets/objc-ivar-offsets.m
@@ -0,0 +1,19 @@
+#import "objc-ivar-offsets.h"
+
+@implementation BaseClass
+@synthesize backed_int = _backed_int;
+#if __OBJC2__
+@synthesize unbacked_int;
+#else
+@synthesize unbacked_int = _unbacked_int;
+#endif
+@end
+
+@implementation DerivedClass
+@synthesize derived_backed_int = _derived_backed_int;
+#if __OBJC2__
+@synthesize derived_unbacked_int;
+#else
+@synthesize derived_unbacked_int = _derived_unbacked_int;
+#endif
+@end
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-ivar-protocols/TestIvarProtocols.py b/packages/Python/lldbsuite/test/lang/objc/objc-ivar-protocols/TestIvarProtocols.py
new file mode 100644
index 000000000000..80305e303d03
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-ivar-protocols/TestIvarProtocols.py
@@ -0,0 +1,4 @@
+import lldbsuite.test.lldbinline as lldbinline
+import lldbsuite.test.lldbtest as lldbtest
+
+lldbinline.MakeInlineTest(__file__, globals(), [lldbtest.skipIfFreeBSD,lldbtest.skipIfLinux,lldbtest.skipIfWindows])
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-ivar-protocols/main.m b/packages/Python/lldbsuite/test/lang/objc/objc-ivar-protocols/main.m
new file mode 100644
index 000000000000..aa6c4715c33b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-ivar-protocols/main.m
@@ -0,0 +1,33 @@
+#import <Foundation/Foundation.h>
+
+@protocol MyProtocol
+-(void)aMethod;
+@end
+
+@interface MyClass : NSObject {
+ id <MyProtocol> myId;
+ NSObject <MyProtocol> *myObject;
+};
+
+-(void)doSomething;
+
+@end
+
+@implementation MyClass
+
+-(void)doSomething
+{
+ NSLog(@"Hello"); //% self.expect("expression -- myId", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["id"]);
+ //% self.expect("expression -- myObject", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["NSObject"]);
+}
+
+@end
+
+int main ()
+{
+ @autoreleasepool
+ {
+ MyClass *c = [MyClass alloc];
+ [c doSomething];
+ }
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/Makefile b/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/Makefile
new file mode 100644
index 000000000000..4365ed9ae936
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/Makefile
@@ -0,0 +1,15 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+LDFLAGS = $(CFLAGS) -lobjc -framework Foundation
+
+default: a.out.stripped
+
+a.out.stripped: a.out.dSYM
+ strip -o a.out.stripped a.out
+
+clean::
+ rm -f a.out.stripped
+ rm -rf a.out.stripped.dSYM
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/TestObjCIvarStripped.py b/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/TestObjCIvarStripped.py
new file mode 100644
index 000000000000..78c7123eefca
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/TestObjCIvarStripped.py
@@ -0,0 +1,59 @@
+"""Test printing ObjC objects that use unbacked properties - so that the static ivar offsets are incorrect."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TestObjCIvarStripped(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break inside main().
+ self.main_source = "main.m"
+ self.stop_line = line_number(self.main_source, '// Set breakpoint here.')
+
+ @skipUnlessDarwin
+ @skipIfDwarf # This test requires a stripped binary and a dSYM
+ @skipIfDWO # This test requires a stripped binary and a dSYM
+ @add_test_categories(['pyapi'])
+ def test_with_python_api(self):
+ """Test that we can find stripped Objective-C ivars in the runtime"""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out.stripped")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ self.dbg.HandleCommand("add-dsym a.out.dSYM")
+
+ breakpoint = target.BreakpointCreateByLocation(self.main_source, self.stop_line)
+ self.assertTrue(breakpoint.IsValid() and breakpoint.GetNumLocations() > 0, VALID_BREAKPOINT)
+
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue (process, "Created a process.")
+ self.assertTrue (process.GetState() == lldb.eStateStopped, "Stopped it too.")
+
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint)
+ self.assertTrue (len(thread_list) == 1)
+ thread = thread_list[0]
+
+ frame = thread.GetFrameAtIndex(0)
+ self.assertTrue (frame, "frame 0 is valid")
+
+ # Test the expression for mc->_foo
+
+ error = lldb.SBError()
+
+ ivar = frame.EvaluateExpression ("(mc->_foo)")
+ self.assertTrue(ivar, "Got result for mc->_foo")
+ ivar_value = ivar.GetValueAsSigned (error)
+ self.assertTrue (error.Success())
+ self.assertTrue (ivar_value == 3)
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/main.m b/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/main.m
new file mode 100644
index 000000000000..ed9c1d9ec426
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-ivar-stripped/main.m
@@ -0,0 +1,33 @@
+#import <Foundation/Foundation.h>
+
+@interface MyClass : NSObject {
+@public
+ int _foo;
+};
+
+-(id)init;
+@end
+
+@implementation MyClass
+
+-(id)init
+{
+ if ([super init])
+ {
+ _foo = 3;
+ }
+
+ return self;
+}
+
+@end
+
+int main ()
+{
+ @autoreleasepool
+ {
+ MyClass *mc = [[MyClass alloc] init];
+
+ NSLog(@"%d", mc->_foo); // Set breakpoint here.
+ }
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/Makefile b/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/Makefile
new file mode 100644
index 000000000000..ad3cb3fadcde
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/TestObjCNewSyntax.py b/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/TestObjCNewSyntax.py
new file mode 100644
index 000000000000..ca77de261829
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/TestObjCNewSyntax.py
@@ -0,0 +1,103 @@
+"""Test that the Objective-C syntax for dictionary/array literals and indexing works"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import lldb
+import platform
+import lldbsuite.test.lldbutil as lldbutil
+
+from distutils.version import StrictVersion
+
+from lldbsuite.test.lldbtest import *
+
+class ObjCNewSyntaxTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.m', '// Set breakpoint 0 here.')
+
+ @skipUnlessDarwin
+ @expectedFailureAll(oslist=['macosx'], compiler='clang', compiler_version=['<', '7.0.0'])
+ @unittest2.skipIf(platform.system() != "Darwin" or StrictVersion('12.0.0') > platform.release(), "Only supported on Darwin 12.0.0+")
+ def test_expr(self):
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break inside the foo function which takes a bar_ptr argument.
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # The breakpoint should have a hit count of 1.
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ self.expect("expr --object-description -- immutable_array[0]", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["foo"])
+
+ self.expect("expr --object-description -- mutable_array[0]", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["foo"])
+
+ self.expect("expr --object-description -- mutable_array[0] = @\"bar\"", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["bar"])
+
+ self.expect("expr --object-description -- mutable_array[0]", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["bar"])
+
+ self.expect("expr --object-description -- immutable_dictionary[@\"key\"]", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["value"])
+
+ self.expect("expr --object-description -- mutable_dictionary[@\"key\"]", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["value"])
+
+ self.expect("expr --object-description -- mutable_dictionary[@\"key\"] = @\"object\"", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["object"])
+
+ self.expect("expr --object-description -- mutable_dictionary[@\"key\"]", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["object"])
+
+ self.expect("expr --object-description -- @[ @\"foo\", @\"bar\" ]", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["NSArray", "foo", "bar"])
+
+ self.expect("expr --object-description -- @{ @\"key\" : @\"object\" }", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["key", "object"])
+
+ self.expect("expr --object-description -- @'a'", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = [str(ord('a'))])
+
+ self.expect("expr --object-description -- @1", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["1"])
+
+ self.expect("expr --object-description -- @1l", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["1"])
+
+ self.expect("expr --object-description -- @1ul", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["1"])
+
+ self.expect("expr --object-description -- @1ll", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["1"])
+
+ self.expect("expr --object-description -- @1ull", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["1"])
+
+ self.expect("expr -- @123.45", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["NSNumber", "123.45"])
+
+ self.expect("expr --object-description -- @( 1 + 3 )", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["4"])
+ self.expect("expr -- @((char*)\"Hello world\" + 6)", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["NSString", "world"])
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/main.m b/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/main.m
new file mode 100644
index 000000000000..d77ba5b10de9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-new-syntax/main.m
@@ -0,0 +1,21 @@
+#import <Foundation/Foundation.h>
+
+int main()
+{
+ @autoreleasepool
+ {
+ // NSArrays
+ NSArray *immutable_array = @[ @"foo", @"bar" ];
+ NSMutableArray *mutable_array = [NSMutableArray arrayWithCapacity:2];
+ [mutable_array addObjectsFromArray:immutable_array];
+
+ // NSDictionaries
+ NSDictionary *immutable_dictionary = @{ @"key" : @"value" };
+ NSMutableDictionary *mutable_dictionary = [NSMutableDictionary dictionaryWithCapacity:1];
+ [mutable_dictionary addEntriesFromDictionary:immutable_dictionary];
+
+ NSNumber *one = @1;
+
+ NSLog(@"Stop here"); // Set breakpoint 0 here.
+ }
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-optimized/Makefile b/packages/Python/lldbsuite/test/lang/objc/objc-optimized/Makefile
new file mode 100644
index 000000000000..aa6a7520525e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-optimized/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+
+CFLAGS ?= -arch $(ARCH) -g -O2
+LDFLAGS = $(CFLAGS) -lobjc -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-optimized/TestObjcOptimized.py b/packages/Python/lldbsuite/test/lang/objc/objc-optimized/TestObjcOptimized.py
new file mode 100644
index 000000000000..a4a202e3f940
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-optimized/TestObjcOptimized.py
@@ -0,0 +1,63 @@
+"""
+Test that objective-c expression parser continues to work for optimized build.
+
+http://llvm.org/viewvc/llvm-project?rev=126973&view=rev
+Fixed a bug in the expression parser where the 'this'
+or 'self' variable was not properly read if the compiler
+optimized it into a register.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+import re
+
+# rdar://problem/9087739
+# test failure: objc_optimized does not work for "-C clang -A i386"
+@skipUnlessDarwin
+class ObjcOptimizedTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+ myclass = "MyClass"
+ mymethod = "description"
+ method_spec = "-[%s %s]" % (myclass, mymethod)
+
+ def test_break(self):
+ """Test 'expr member' continues to work for optimized build."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_symbol (self, self.method_spec, num_expected_locations=1, sym_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+ self.expect("thread backtrace", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ["stop reason = breakpoint"],
+ patterns = ["frame.*0:.*%s %s" % (self.myclass, self.mymethod)])
+
+ self.expect('expression member',
+ startstr = "(int) $0 = 5")
+
+ # <rdar://problem/12693963>
+ interp = self.dbg.GetCommandInterpreter()
+ result = lldb.SBCommandReturnObject()
+ interp.HandleCommand('frame variable self', result)
+ output = result.GetOutput()
+
+ desired_pointer = "0x0"
+
+ mo = re.search("0x[0-9a-f]+", output)
+
+ if mo:
+ desired_pointer = mo.group(0)
+
+ self.expect('expression (self)',
+ substrs = [("(%s *) $1 = " % self.myclass), desired_pointer])
+
+ self.expect('expression self->non_member', error=True,
+ substrs = ["does not have a member named 'non_member'"])
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-optimized/main.m b/packages/Python/lldbsuite/test/lang/objc/objc-optimized/main.m
new file mode 100644
index 000000000000..df88eea0f86a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-optimized/main.m
@@ -0,0 +1,44 @@
+#import <Foundation/Foundation.h>
+
+@interface MyClass : NSObject {
+ int member;
+}
+
+- (id)initWithMember:(int)_member;
+- (NSString*)description;
+@end
+
+@implementation MyClass
+
+- (id)initWithMember:(int)_member
+{
+ if (self = [super init])
+ {
+ member = _member;
+ }
+ return self;
+}
+
+- (void)dealloc
+{
+ [super dealloc];
+}
+
+// Set a breakpoint on '-[MyClass description]' and test expressions: expr member
+- (NSString *)description
+{
+ return [NSString stringWithFormat:@"%d", member];
+}
+@end
+
+int main (int argc, char const *argv[])
+{
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+
+ MyClass *my_object = [[MyClass alloc] initWithMember:5];
+
+ NSLog(@"MyObject %@", [my_object description]);
+
+ [pool release];
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-property/Makefile b/packages/Python/lldbsuite/test/lang/objc/objc-property/Makefile
new file mode 100644
index 000000000000..a1608fe5a664
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-property/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+LDFLAGS = $(CFLAGS) -lobjc -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-property/TestObjCProperty.py b/packages/Python/lldbsuite/test/lang/objc/objc-property/TestObjCProperty.py
new file mode 100644
index 000000000000..c22a1f1ad532
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-property/TestObjCProperty.py
@@ -0,0 +1,114 @@
+"""
+Use lldb Python API to verify that expression evaluation for property references uses the correct getters and setters
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ObjCPropertyTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+
+ # Find the line number to break for main.c.
+ self.source_name = 'main.m'
+
+ @skipUnlessDarwin
+ @add_test_categories(['pyapi'])
+ def test_objc_properties(self):
+ """Test that expr uses the correct property getters and setters"""
+ if self.getArchitecture() == 'i386':
+ self.skipTest("requires modern objc runtime")
+
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target from the debugger.
+
+ target = self.dbg.CreateTarget (exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Set up our breakpoints:
+
+ main_bkpt = target.BreakpointCreateBySourceRegex ("Set a breakpoint here.", lldb.SBFileSpec (self.source_name))
+ self.assertTrue(main_bkpt and
+ main_bkpt.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, main_bkpt)
+ self.assertTrue (len(threads) == 1)
+ thread = threads[0]
+ frame = thread.GetFrameAtIndex(0)
+
+ mine = frame.FindVariable ("mine")
+ self.assertTrue (mine.IsValid())
+ access_count = mine.GetChildMemberWithName ("_access_count")
+ self.assertTrue (access_count.IsValid())
+ start_access_count = access_count.GetValueAsUnsigned (123456)
+ self.assertTrue (start_access_count != 123456)
+
+ #
+ # The first set of tests test calling the getter & setter of
+ # a property that actually only has a getter & setter and no
+ # @property.
+ #
+ nonexistant_value = frame.EvaluateExpression("mine.nonexistantInt", False)
+ nonexistant_error = nonexistant_value.GetError()
+ self.assertTrue (nonexistant_error.Success())
+ nonexistant_int = nonexistant_value.GetValueAsUnsigned (123456)
+ self.assertTrue (nonexistant_int == 6)
+
+ # Calling the getter function would up the access count, so make sure that happened.
+
+ new_access_count = access_count.GetValueAsUnsigned (123456)
+ self.assertTrue (new_access_count - start_access_count == 1)
+ start_access_count = new_access_count
+
+ #
+ # Now call the setter, then make sure that
+ nonexistant_change = frame.EvaluateExpression("mine.nonexistantInt = 10", False)
+ nonexistant_error = nonexistant_change.GetError()
+ self.assertTrue (nonexistant_error.Success())
+
+ # Calling the setter function would up the access count, so make sure that happened.
+
+ new_access_count = access_count.GetValueAsUnsigned (123456)
+ self.assertTrue (new_access_count - start_access_count == 1)
+ start_access_count = new_access_count
+
+ #
+ # Now we call the getter of a property that is backed by an ivar,
+ # make sure it works and that we actually update the backing ivar.
+ #
+
+ backed_value = frame.EvaluateExpression("mine.backedInt", False)
+ backed_error = backed_value.GetError()
+ self.assertTrue (backed_error.Success())
+ backing_value = mine.GetChildMemberWithName ("_backedInt")
+ self.assertTrue (backing_value.IsValid())
+ self.assertTrue (backed_value.GetValueAsUnsigned (12345) == backing_value.GetValueAsUnsigned(23456))
+
+ unbacked_value = frame.EvaluateExpression("mine.unbackedInt", False)
+ unbacked_error = unbacked_value.GetError()
+ self.assertTrue (unbacked_error.Success())
+
+ idWithProtocol_value = frame.EvaluateExpression("mine.idWithProtocol", False)
+ idWithProtocol_error = idWithProtocol_value.GetError()
+ self.assertTrue (idWithProtocol_error.Success())
+ self.assertTrue (idWithProtocol_value.GetTypeName() == "id")
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-property/main.m b/packages/Python/lldbsuite/test/lang/objc/objc-property/main.m
new file mode 100644
index 000000000000..2ef142be9b00
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-property/main.m
@@ -0,0 +1,100 @@
+#import <Foundation/Foundation.h>
+
+@protocol MyProtocol
+
+-(const char *)hello;
+
+@end
+
+@interface BaseClass : NSObject
+{
+ int _backedInt;
+ int _access_count;
+}
+
+- (int) nonexistantInt;
+- (void) setNonexistantInt: (int) in_int;
+
+- (int) myGetUnbackedInt;
+- (void) mySetUnbackedInt: (int) in_int;
+
+- (int) getAccessCount;
+
++(BaseClass *) baseClassWithBackedInt: (int) inInt andUnbackedInt: (int) inOtherInt;
+
+@property(getter=myGetUnbackedInt,setter=mySetUnbackedInt:) int unbackedInt;
+@property int backedInt;
+@property (nonatomic, assign) id <MyProtocol> idWithProtocol;
+@end
+
+@implementation BaseClass
+@synthesize unbackedInt;
+@synthesize backedInt = _backedInt;
+
++ (BaseClass *) baseClassWithBackedInt: (int) inInt andUnbackedInt: (int) inOtherInt
+{
+ BaseClass *new = [[BaseClass alloc] init];
+
+ new->_backedInt = inInt;
+ new->unbackedInt = inOtherInt;
+
+ return new;
+}
+
+- (int) myGetUnbackedInt
+{
+ // NSLog (@"Getting BaseClass::unbackedInt - %d.\n", unbackedInt);
+ _access_count++;
+ return unbackedInt;
+}
+
+- (void) mySetUnbackedInt: (int) in_int
+{
+ // NSLog (@"Setting BaseClass::unbackedInt from %d to %d.", unbackedInt, in_int);
+ _access_count++;
+ unbackedInt = in_int;
+}
+
+- (int) nonexistantInt
+{
+ // NSLog (@"Getting BaseClass::nonexistantInt - %d.\n", 5);
+ _access_count++;
+ return 6;
+}
+
+- (void) setNonexistantInt: (int) in_int
+{
+ // NSLog (@"Setting BaseClass::nonexistantInt from 7 to %d.", in_int);
+ _access_count++;
+}
+
+- (int) getAccessCount
+{
+ return _access_count;
+}
+@end
+
+int
+main ()
+{
+ BaseClass *mine = [BaseClass baseClassWithBackedInt: 10 andUnbackedInt: 20];
+
+ // Set a breakpoint here.
+ int nonexistant = mine.nonexistantInt;
+
+ int backedInt = mine.backedInt;
+
+ int unbackedInt = mine.unbackedInt;
+
+ id idWithProtocol = mine.idWithProtocol;
+
+ NSLog (@"Results for %p: nonexistant: %d backed: %d unbacked: %d accessCount: %d.",
+ mine,
+ nonexistant,
+ backedInt,
+ unbackedInt,
+ [mine getAccessCount]);
+ return 0;
+
+}
+
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/Makefile b/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/Makefile
new file mode 100644
index 000000000000..a1608fe5a664
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+LDFLAGS = $(CFLAGS) -lobjc -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/TestRuntimeIvars.py b/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/TestRuntimeIvars.py
new file mode 100644
index 000000000000..80305e303d03
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/TestRuntimeIvars.py
@@ -0,0 +1,4 @@
+import lldbsuite.test.lldbinline as lldbinline
+import lldbsuite.test.lldbtest as lldbtest
+
+lldbinline.MakeInlineTest(__file__, globals(), [lldbtest.skipIfFreeBSD,lldbtest.skipIfLinux,lldbtest.skipIfWindows])
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/main.m b/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/main.m
new file mode 100644
index 000000000000..1f5a9b077e27
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-runtime-ivars/main.m
@@ -0,0 +1,10 @@
+#import <Foundation/Foundation.h>
+
+int main ()
+{
+ @autoreleasepool
+ {
+ NSLog(@"Hello"); //% self.expect("expression -- *((NSConcretePointerArray*)[NSPointerArray strongObjectsPointerArray])", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["count", "capacity", "options", "mutations"]);
+ //% self.expect("expression -- ((NSConcretePointerArray*)[NSPointerArray strongObjectsPointerArray])->count", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["unsigned"]);
+ }
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/Makefile b/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/Makefile
new file mode 100644
index 000000000000..81e7f12dea2b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/Makefile
@@ -0,0 +1,15 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := static.m
+LDFLAGS = $(CFLAGS) -lobjc -framework Foundation
+
+default: a.out.stripped
+
+a.out.stripped: a.out.dSYM
+ strip -o a.out.stripped a.out
+
+clean::
+ rm -f a.out.stripped
+ rm -rf a.out.stripped.dSYM
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/TestObjCStaticMethodStripped.py b/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/TestObjCStaticMethodStripped.py
new file mode 100644
index 000000000000..4bcc10b8b882
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/TestObjCStaticMethodStripped.py
@@ -0,0 +1,65 @@
+"""Test calling functions in static methods with a stripped binary."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TestObjCStaticMethodStripped(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break inside main().
+ self.main_source = "static.m"
+ self.break_line = line_number(self.main_source, '// Set breakpoint here.')
+
+ @skipUnlessDarwin
+ @add_test_categories(['pyapi'])
+ @skipIfDwarf # This test requires a stripped binary and a dSYM
+ @skipIfDWO # This test requires a stripped binary and a dSYM
+ #<rdar://problem/12042992>
+ def test_with_python_api(self):
+ """Test calling functions in static methods with a stripped binary."""
+ if self.getArchitecture() == 'i386':
+ self.skipTest("requires modern objc runtime")
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out.stripped")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line)
+ self.assertTrue(bpt, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, bpt)
+
+ # Make sure we stopped at the first breakpoint.
+ self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.")
+ self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.")
+
+ # Now make sure we can call a function in the static method we've stopped in.
+ frame = thread_list[0].GetFrameAtIndex(0)
+ self.assertTrue (frame, "Got a valid frame 0 frame.")
+
+ cmd_value = frame.EvaluateExpression ("(char *) sel_getName (_cmd)")
+ self.assertTrue (cmd_value.IsValid())
+ sel_name = cmd_value.GetSummary()
+ self.assertTrue (sel_name == "\"doSomethingWithString:\"", "Got the right value for the selector as string.")
+
+ cmd_value = frame.EvaluateExpression ("[Foo doSomethingElseWithString:string]")
+ self.assertTrue (cmd_value.IsValid())
+ string_length = cmd_value.GetValueAsUnsigned()
+ self.assertTrue (string_length == 27, "Got the right value from another class method on the same class.")
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/static.m b/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/static.m
new file mode 100644
index 000000000000..ec7b2ef67195
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-static-method-stripped/static.m
@@ -0,0 +1,29 @@
+#import <Foundation/Foundation.h>
+
+@interface Foo : NSObject
++(void) doSomethingWithString: (NSString *) string;
+-(void) doSomethingWithNothing;
+@end
+
+@implementation Foo
++(void) doSomethingWithString: (NSString *) string
+{
+ NSLog (@"String is: %@.", string); // Set breakpoint here.
+}
+
++(int) doSomethingElseWithString: (NSString *) string
+{
+ NSLog (@"String is still: %@.", string);
+ return [string length];
+}
+
+-(void) doSomethingWithNothing
+{
+}
+@end
+
+int main()
+{
+ [Foo doSomethingWithString: @"Some string I have in mind."];
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-static-method/Makefile b/packages/Python/lldbsuite/test/lang/objc/objc-static-method/Makefile
new file mode 100644
index 000000000000..a8e973f6d3b1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-static-method/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := static.m
+LDFLAGS = $(CFLAGS) -lobjc -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-static-method/TestObjCStaticMethod.py b/packages/Python/lldbsuite/test/lang/objc/objc-static-method/TestObjCStaticMethod.py
new file mode 100644
index 000000000000..89ef1e7b6898
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-static-method/TestObjCStaticMethod.py
@@ -0,0 +1,61 @@
+"""Test calling functions in static methods."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TestObjCStaticMethod(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break inside main().
+ self.main_source = "static.m"
+ self.break_line = line_number(self.main_source, '// Set breakpoint here.')
+
+ @skipUnlessDarwin
+ @add_test_categories(['pyapi'])
+ #<rdar://problem/9745789> "expression" can't call functions in class methods
+ def test_with_python_api(self):
+ """Test calling functions in static methods."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line)
+ self.assertTrue(bpt, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, bpt)
+
+ # Make sure we stopped at the first breakpoint.
+ self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.")
+ self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.")
+
+ # Now make sure we can call a function in the static method we've stopped in.
+ frame = thread_list[0].GetFrameAtIndex(0)
+ self.assertTrue (frame, "Got a valid frame 0 frame.")
+
+ cmd_value = frame.EvaluateExpression ("(char *) sel_getName (_cmd)")
+ self.assertTrue (cmd_value.IsValid())
+ sel_name = cmd_value.GetSummary()
+ self.assertTrue (sel_name == "\"doSomethingWithString:\"", "Got the right value for the selector as string.")
+
+ cmd_value = frame.EvaluateExpression ("[self doSomethingElseWithString:string]")
+ self.assertTrue (cmd_value.IsValid())
+ string_length = cmd_value.GetValueAsUnsigned()
+ self.assertTrue (string_length == 27, "Got the right value from another class method on the same class.")
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-static-method/static.m b/packages/Python/lldbsuite/test/lang/objc/objc-static-method/static.m
new file mode 100644
index 000000000000..ec7b2ef67195
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-static-method/static.m
@@ -0,0 +1,29 @@
+#import <Foundation/Foundation.h>
+
+@interface Foo : NSObject
++(void) doSomethingWithString: (NSString *) string;
+-(void) doSomethingWithNothing;
+@end
+
+@implementation Foo
++(void) doSomethingWithString: (NSString *) string
+{
+ NSLog (@"String is: %@.", string); // Set breakpoint here.
+}
+
++(int) doSomethingElseWithString: (NSString *) string
+{
+ NSLog (@"String is still: %@.", string);
+ return [string length];
+}
+
+-(void) doSomethingWithNothing
+{
+}
+@end
+
+int main()
+{
+ [Foo doSomethingWithString: @"Some string I have in mind."];
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-stepping/Makefile b/packages/Python/lldbsuite/test/lang/objc/objc-stepping/Makefile
new file mode 100644
index 000000000000..b097fe65fce7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-stepping/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := stepping-tests.m
+LDFLAGS = $(CFLAGS) -lobjc -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-stepping/TestObjCStepping.py b/packages/Python/lldbsuite/test/lang/objc/objc-stepping/TestObjCStepping.py
new file mode 100644
index 000000000000..1df416d45133
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-stepping/TestObjCStepping.py
@@ -0,0 +1,172 @@
+"""Test stepping through ObjC method dispatch in various forms."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TestObjCStepping(TestBase):
+
+ def getCategories (self):
+ return ['basic_process']
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers that we will step to in main:
+ self.main_source = "stepping-tests.m"
+ self.source_randomMethod_line = line_number (self.main_source, '// Source randomMethod start line.')
+ self.sourceBase_randomMethod_line = line_number (self.main_source, '// SourceBase randomMethod start line.')
+ self.source_returnsStruct_start_line = line_number (self.main_source, '// Source returnsStruct start line.')
+ self.sourceBase_returnsStruct_start_line = line_number (self.main_source, '// SourceBase returnsStruct start line.')
+ self.stepped_past_nil_line = line_number (self.main_source, '// Step over nil should stop here.')
+
+ @skipUnlessDarwin
+ @add_test_categories(['pyapi'])
+ def test_with_python_api(self):
+ """Test stepping through ObjC method dispatch in various forms."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ self.main_source_spec = lldb.SBFileSpec (self.main_source)
+
+ breakpoints_to_disable = []
+
+ break1 = target.BreakpointCreateBySourceRegex ("// Set first breakpoint here.", self.main_source_spec)
+ self.assertTrue(break1, VALID_BREAKPOINT)
+ breakpoints_to_disable.append (break1)
+
+ break2 = target.BreakpointCreateBySourceRegex ("// Set second breakpoint here.", self.main_source_spec)
+ self.assertTrue(break2, VALID_BREAKPOINT)
+ breakpoints_to_disable.append (break2)
+
+ break3 = target.BreakpointCreateBySourceRegex ('// Set third breakpoint here.', self.main_source_spec)
+ self.assertTrue(break3, VALID_BREAKPOINT)
+ breakpoints_to_disable.append (break3)
+
+ break4 = target.BreakpointCreateBySourceRegex ('// Set fourth breakpoint here.', self.main_source_spec)
+ self.assertTrue(break4, VALID_BREAKPOINT)
+ breakpoints_to_disable.append (break4)
+
+ break5 = target.BreakpointCreateBySourceRegex ('// Set fifth breakpoint here.', self.main_source_spec)
+ self.assertTrue(break5, VALID_BREAKPOINT)
+ breakpoints_to_disable.append (break5)
+
+ break_returnStruct_call_super = target.BreakpointCreateBySourceRegex ('// Source returnsStruct call line.', self.main_source_spec)
+ self.assertTrue(break_returnStruct_call_super, VALID_BREAKPOINT)
+ breakpoints_to_disable.append (break_returnStruct_call_super)
+
+ break_step_nil = target.BreakpointCreateBySourceRegex ('// Set nil step breakpoint here.', self.main_source_spec)
+ self.assertTrue(break_step_nil, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, break1)
+ if len(threads) != 1:
+ self.fail ("Failed to stop at breakpoint 1.")
+
+ thread = threads[0]
+
+ mySource = thread.GetFrameAtIndex(0).FindVariable("mySource")
+ self.assertTrue(mySource, "Found mySource local variable.")
+ mySource_isa = mySource.GetChildMemberWithName ("isa")
+ self.assertTrue(mySource_isa, "Found mySource->isa local variable.")
+ className = mySource_isa.GetSummary ()
+
+ if self.TraceOn():
+ print(mySource_isa)
+
+ # Lets delete mySource so we can check that after stepping a child variable
+ # with no parent persists and is useful.
+ del (mySource)
+
+ # Now step in, that should leave us in the Source randomMethod:
+ thread.StepInto()
+ line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine()
+ self.assertTrue (line_number == self.source_randomMethod_line, "Stepped into Source randomMethod.")
+
+ # Now step in again, through the super call, and that should leave us in the SourceBase randomMethod:
+ thread.StepInto()
+ line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine()
+ self.assertTrue (line_number == self.sourceBase_randomMethod_line, "Stepped through super into SourceBase randomMethod.")
+
+ threads = lldbutil.continue_to_breakpoint (process, break2)
+ self.assertTrue (len(threads) == 1, "Continued to second breakpoint in main.")
+
+ # Again, step in twice gets us to a stret method and a stret super call:
+ thread = threads[0]
+ thread.StepInto()
+ line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine()
+ self.assertTrue (line_number == self.source_returnsStruct_start_line, "Stepped into Source returnsStruct.")
+
+ threads = lldbutil.continue_to_breakpoint (process, break_returnStruct_call_super)
+ self.assertTrue (len(threads) == 1, "Stepped to the call super line in Source returnsStruct.")
+ thread = threads[0]
+
+ thread.StepInto()
+ line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine()
+ self.assertTrue (line_number == self.sourceBase_returnsStruct_start_line, "Stepped through super into SourceBase returnsStruct.")
+
+ # Cool now continue to get past the call that initializes the Observer, and then do our steps in again to see that
+ # we can find our way when we're stepping through a KVO swizzled object.
+
+ threads = lldbutil.continue_to_breakpoint (process, break3)
+ self.assertTrue (len(threads) == 1, "Continued to third breakpoint in main, our object should now be swizzled.")
+
+ newClassName = mySource_isa.GetSummary ()
+
+ if self.TraceOn():
+ print(mySource_isa)
+
+ self.assertTrue (newClassName != className, "The isa did indeed change, swizzled!")
+
+ # Now step in, that should leave us in the Source randomMethod:
+ thread = threads[0]
+ thread.StepInto()
+ line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine()
+ self.assertTrue (line_number == self.source_randomMethod_line, "Stepped into Source randomMethod in swizzled object.")
+
+ # Now step in again, through the super call, and that should leave us in the SourceBase randomMethod:
+ thread.StepInto()
+ line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine()
+ self.assertTrue (line_number == self.sourceBase_randomMethod_line, "Stepped through super into SourceBase randomMethod in swizzled object.")
+
+ threads = lldbutil.continue_to_breakpoint (process, break4)
+ self.assertTrue (len(threads) == 1, "Continued to fourth breakpoint in main.")
+ thread = threads[0]
+
+ # Again, step in twice gets us to a stret method and a stret super call:
+ thread.StepInto()
+ line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine()
+ self.assertTrue (line_number == self.source_returnsStruct_start_line, "Stepped into Source returnsStruct in swizzled object.")
+
+ threads = lldbutil.continue_to_breakpoint(process, break_returnStruct_call_super)
+ self.assertTrue (len(threads) == 1, "Stepped to the call super line in Source returnsStruct - second time.")
+ thread = threads[0]
+
+ thread.StepInto()
+ line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine()
+ self.assertTrue (line_number == self.sourceBase_returnsStruct_start_line, "Stepped through super into SourceBase returnsStruct in swizzled object.")
+
+ for bkpt in breakpoints_to_disable:
+ bkpt.SetEnabled(False)
+
+ threads = lldbutil.continue_to_breakpoint (process, break_step_nil)
+ self.assertTrue (len(threads) == 1, "Continued to step nil breakpoint.")
+
+ thread.StepInto()
+ line_number = thread.GetFrameAtIndex(0).GetLineEntry().GetLine()
+ self.assertTrue (line_number == self.stepped_past_nil_line, "Step in over dispatch to nil stepped over.")
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-stepping/stepping-tests.m b/packages/Python/lldbsuite/test/lang/objc/objc-stepping/stepping-tests.m
new file mode 100644
index 000000000000..63db536dee49
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-stepping/stepping-tests.m
@@ -0,0 +1,138 @@
+#import <Foundation/Foundation.h>
+#include <stdio.h>
+
+struct return_me
+{
+ int first;
+ int second;
+};
+
+@interface SourceBase: NSObject
+{
+ struct return_me my_return;
+}
+- (SourceBase *) initWithFirst: (int) first andSecond: (int) second;
+- (void) randomMethod;
+- (struct return_me) returnsStruct;
+@end
+
+@implementation SourceBase
+- (void) randomMethod
+{
+ printf ("Called in SourceBase version of randomMethod.\n"); // SourceBase randomMethod start line.
+}
+
+- (struct return_me) returnsStruct
+{
+ return my_return; // SourceBase returnsStruct start line.
+}
+
+- (SourceBase *) initWithFirst: (int) first andSecond: (int) second
+{
+ my_return.first = first;
+ my_return.second = second;
+
+ return self;
+}
+@end
+
+@interface Source : SourceBase
+{
+ int _property;
+}
+- (void) setProperty: (int) newValue;
+- (void) randomMethod;
+- (struct return_me) returnsStruct;
+@end
+
+@implementation Source
+- (void) setProperty: (int) newValue
+{
+ _property = newValue;
+}
+
+- (void) randomMethod
+{
+ [super randomMethod]; // Source randomMethod start line.
+ printf ("Called in Source version of random method.");
+}
+
+- (struct return_me) returnsStruct
+{
+ printf ("Called in Source version of returnsStruct.\n"); // Source returnsStruct start line.
+ return [super returnsStruct]; // Source returnsStruct call line.
+}
+
+@end
+
+@interface Observer : NSObject
+{
+ Source *_source;
+}
++ (Observer *) observerWithSource: (Source *) source;
+- (Observer *) initWithASource: (Source *) source;
+- (void) observeValueForKeyPath: (NSString *) path
+ ofObject: (id) object
+ change: (NSDictionary *) change
+ context: (void *) context;
+@end
+
+@implementation Observer
+
++ (Observer *) observerWithSource: (Source *) inSource;
+{
+ Observer *retval;
+
+ retval = [[Observer alloc] initWithASource: inSource];
+ return retval;
+}
+
+- (Observer *) initWithASource: (Source *) source
+{
+ [super init];
+ _source = source;
+ [_source addObserver: self
+ forKeyPath: @"property"
+ options: (NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
+ context: NULL];
+ return self;
+}
+
+- (void) observeValueForKeyPath: (NSString *) path
+ ofObject: (id) object
+ change: (NSDictionary *) change
+ context: (void *) context
+{
+ printf ("Observer function called.\n");
+ return;
+}
+@end
+
+int main ()
+{
+ Source *mySource;
+ Observer *myObserver;
+ struct return_me ret_val;
+
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+
+ mySource = [[Source alloc] init];
+
+ [mySource randomMethod]; // Set first breakpoint here.
+ ret_val = [mySource returnsStruct]; // Set second breakpoint here.
+
+ myObserver = [Observer observerWithSource: mySource];
+
+ [mySource randomMethod]; // Set third breakpoint here.
+ ret_val = [mySource returnsStruct]; // Set fourth breakpoint here.
+ [mySource setProperty: 5]; // Set fifth breakpoint here.
+
+ // We also had a bug where stepping into a method dispatch to nil turned
+ // into continue. So make sure that works here:
+
+ mySource = nil;
+ [mySource randomMethod]; // Set nil step breakpoint here.
+ [pool release]; // Step over nil should stop here.
+ return 0;
+
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/Makefile b/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/Makefile
new file mode 100644
index 000000000000..c16802966cff
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := test.m
+LDFLAGS = $(CFLAGS) -lobjc -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/TestObjCStructArgument.py b/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/TestObjCStructArgument.py
new file mode 100644
index 000000000000..36cde21c9d66
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/TestObjCStructArgument.py
@@ -0,0 +1,57 @@
+"""Test passing structs to Objective-C methods."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TestObjCStructArgument(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break inside main().
+ self.main_source = "test.m"
+ self.break_line = line_number(self.main_source, '// Set breakpoint here.')
+
+ @skipUnlessDarwin
+ @add_test_categories(['pyapi'])
+ def test_with_python_api(self):
+ """Test passing structs to Objective-C methods."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line)
+ self.assertTrue(bpt, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, bpt)
+
+ # Make sure we stopped at the first breakpoint.
+ self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.")
+ self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.")
+
+ frame = thread_list[0].GetFrameAtIndex(0)
+ self.assertTrue (frame, "Got a valid frame 0 frame.")
+
+ self.expect("p [summer sumThings:tts]", substrs = ['9'])
+
+ self.expect("po [NSValue valueWithRect:rect]", substrs = ['NSRect: {{0, 0}, {10, 20}}'])
+
+ # Now make sure we can call a method that returns a struct without crashing.
+ cmd_value = frame.EvaluateExpression ("[provider getRange]")
+ self.assertTrue (cmd_value.IsValid())
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/test.m b/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/test.m
new file mode 100644
index 000000000000..8bf0ec07b710
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-struct-argument/test.m
@@ -0,0 +1,34 @@
+#import <Foundation/Foundation.h>
+
+struct things_to_sum {
+ int a;
+ int b;
+ int c;
+};
+
+@interface ThingSummer : NSObject {
+};
+-(int)sumThings:(struct things_to_sum)tts;
+@end
+
+@implementation ThingSummer
+-(int)sumThings:(struct things_to_sum)tts
+{
+ return tts.a + tts.b + tts.c;
+}
+@end
+
+int main()
+{
+ @autoreleasepool
+ {
+ ThingSummer *summer = [ThingSummer alloc];
+ struct things_to_sum tts = { 2, 3, 4 };
+ int ret = [summer sumThings:tts];
+
+ NSRect rect = {{0, 0}, {10, 20}};
+
+ // Set breakpoint here.
+ return rect.origin.x;
+ }
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/Makefile b/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/Makefile
new file mode 100644
index 000000000000..c16802966cff
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := test.m
+LDFLAGS = $(CFLAGS) -lobjc -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/TestObjCStructReturn.py b/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/TestObjCStructReturn.py
new file mode 100644
index 000000000000..010de2180825
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/TestObjCStructReturn.py
@@ -0,0 +1,53 @@
+"""Test calling functions in class methods."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TestObjCClassMethod(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break inside main().
+ self.main_source = "test.m"
+ self.break_line = line_number(self.main_source, '// Set breakpoint here.')
+
+ @skipUnlessDarwin
+ @add_test_categories(['pyapi'])
+ def test_with_python_api(self):
+ """Test calling functions in class methods."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line)
+ self.assertTrue(bpt, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, bpt)
+
+ # Make sure we stopped at the first breakpoint.
+ self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.")
+ self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.")
+
+ frame = thread_list[0].GetFrameAtIndex(0)
+ self.assertTrue (frame, "Got a valid frame 0 frame.")
+
+ # Now make sure we can call a method that returns a struct without crashing.
+ cmd_value = frame.EvaluateExpression ("[provider getRange]")
+ self.assertTrue (cmd_value.IsValid())
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/test.m b/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/test.m
new file mode 100644
index 000000000000..aafe231ea817
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-struct-return/test.m
@@ -0,0 +1,23 @@
+#import <Foundation/Foundation.h>
+
+@interface RangeProvider : NSObject {
+};
+-(NSRange)getRange;
+@end
+
+@implementation RangeProvider
+-(NSRange)getRange
+{
+ return NSMakeRange(0, 3);
+}
+@end
+
+int main()
+{
+ @autoreleasepool
+ {
+ RangeProvider *provider = [RangeProvider alloc];
+ NSRange range = [provider getRange]; // Set breakpoint here.
+ return 0;
+ }
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-super/Makefile b/packages/Python/lldbsuite/test/lang/objc/objc-super/Makefile
new file mode 100644
index 000000000000..c2d07910a6e8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-super/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := class.m
+LDFLAGS = $(CFLAGS) -lobjc -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-super/TestObjCSuper.py b/packages/Python/lldbsuite/test/lang/objc/objc-super/TestObjCSuper.py
new file mode 100644
index 000000000000..84d147f632da
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-super/TestObjCSuper.py
@@ -0,0 +1,59 @@
+"""Test calling methods on super."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TestObjCSuperMethod(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break inside main().
+ self.main_source = "class.m"
+ self.break_line = line_number(self.main_source, '// Set breakpoint here.')
+
+ @skipUnlessDarwin
+ @expectedFailurei386
+ @add_test_categories(['pyapi'])
+ def test_with_python_api(self):
+ """Test calling methods on super."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ bpt = target.BreakpointCreateByLocation(self.main_source, self.break_line)
+ self.assertTrue(bpt, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, bpt)
+
+ # Make sure we stopped at the first breakpoint.
+ self.assertTrue (len(thread_list) != 0, "No thread stopped at our breakpoint.")
+ self.assertTrue (len(thread_list) == 1, "More than one thread stopped at our breakpoint.")
+
+ # Now make sure we can call a function in the class method we've stopped in.
+ frame = thread_list[0].GetFrameAtIndex(0)
+ self.assertTrue (frame, "Got a valid frame 0 frame.")
+
+ cmd_value = frame.EvaluateExpression ("[self get]")
+ self.assertTrue (cmd_value.IsValid())
+ self.assertTrue (cmd_value.GetValueAsUnsigned() == 2)
+
+ cmd_value = frame.EvaluateExpression ("[super get]")
+ self.assertTrue (cmd_value.IsValid())
+ self.assertTrue (cmd_value.GetValueAsUnsigned() == 1)
diff --git a/packages/Python/lldbsuite/test/lang/objc/objc-super/class.m b/packages/Python/lldbsuite/test/lang/objc/objc-super/class.m
new file mode 100644
index 000000000000..b55b649aaaec
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/objc-super/class.m
@@ -0,0 +1,39 @@
+#import <Foundation/Foundation.h>
+
+@interface Foo : NSObject {
+}
+-(int)get;
+@end
+
+@implementation Foo
+-(int)get
+{
+ return 1;
+}
+@end
+
+@interface Bar : Foo {
+}
+-(int)get;
+@end
+
+@implementation Bar
+-(int)get
+{
+ return 2;
+}
+
+-(int)callme
+{
+ return [self get]; // Set breakpoint here.
+}
+@end
+
+int main()
+{
+ @autoreleasepool
+ {
+ Bar *bar = [Bar alloc];
+ return [bar callme];
+ }
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/print-obj/Makefile b/packages/Python/lldbsuite/test/lang/objc/print-obj/Makefile
new file mode 100644
index 000000000000..dba1065cd714
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/print-obj/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := blocked.m
+LDFLAGS = $(CFLAGS) -lobjc -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/print-obj/TestPrintObj.py b/packages/Python/lldbsuite/test/lang/objc/print-obj/TestPrintObj.py
new file mode 100644
index 000000000000..5c52cc0e0697
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/print-obj/TestPrintObj.py
@@ -0,0 +1,87 @@
+"""
+Test "print object" where another thread blocks the print object from making progress.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+
+@skipUnlessDarwin
+class PrintObjTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # My source program.
+ self.source = "blocked.m"
+ # Find the line numbers to break at.
+ self.line = line_number(self.source, '// Set a breakpoint here.')
+
+ def test_print_obj(self):
+ """
+ Test "print object" where another thread blocks the print object from making progress.
+
+ Set a breakpoint on the line in my_pthread_routine. Then switch threads
+ to the main thread, and do print the lock_me object. Since that will
+ try to get the lock already gotten by my_pthread_routime thread, it will
+ have to switch to running all threads, and that should then succeed.
+ """
+ d = {'EXE': 'b.out'}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ exe = os.path.join(os.getcwd(), 'b.out')
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+ self.runCmd("breakpoint list")
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.runCmd("thread backtrace all")
+
+ # Let's get the current stopped thread. We'd like to switch to the
+ # other thread to issue our 'po lock_me' command.
+ import lldbsuite.test.lldbutil as lldbutil
+ this_thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(this_thread)
+
+ # Find the other thread. The iteration protocol of SBProcess and the
+ # rich comparison methods (__eq__/__ne__) of SBThread come in handy.
+ other_thread = None
+ for t in process:
+ if t != this_thread:
+ other_thread = t
+ break
+
+ # Set the other thread as the selected thread to issue our 'po' command.other
+ self.assertTrue(other_thread)
+ process.SetSelectedThread(other_thread)
+ if self.TraceOn():
+ print("selected thread:" + lldbutil.get_description(other_thread))
+ self.runCmd("thread backtrace")
+
+ # We want to traverse the frame to the one corresponding to blocked.m to
+ # issue our 'po lock_me' command.
+
+ depth = other_thread.GetNumFrames()
+ for i in range(depth):
+ frame = other_thread.GetFrameAtIndex(i)
+ name = frame.GetFunctionName()
+ if name == 'main':
+ other_thread.SetSelectedFrame(i)
+ if self.TraceOn():
+ print("selected frame:" + lldbutil.get_description(frame))
+ break
+
+ self.expect("po lock_me", OBJECT_PRINTED_CORRECTLY,
+ substrs = ['I am pretty special.'])
diff --git a/packages/Python/lldbsuite/test/lang/objc/print-obj/blocked.m b/packages/Python/lldbsuite/test/lang/objc/print-obj/blocked.m
new file mode 100644
index 000000000000..ba2497554444
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/print-obj/blocked.m
@@ -0,0 +1,73 @@
+//===-- blocked.m --------------------------------------------------*- ObjC -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+// This file is for testing running "print object" in a case where another thread
+// blocks the print object from making progress. Set a breakpoint on the line in
+// my_pthread_routine as indicated. Then switch threads to the main thread, and
+// do print the lock_me object. Since that will try to get the lock already gotten
+// by my_pthread_routime thread, it will have to switch to running all threads, and
+// that should then succeed.
+//
+
+#include <Foundation/Foundation.h>
+#include <pthread.h>
+
+static pthread_mutex_t test_mutex;
+
+static void Mutex_Init (void)
+{
+ pthread_mutexattr_t tmp_mutex_attr;
+ pthread_mutexattr_init(&tmp_mutex_attr);
+ pthread_mutex_init(&test_mutex, &tmp_mutex_attr);
+}
+
+@interface LockMe :NSObject
+{
+
+}
+- (NSString *) description;
+@end
+
+@implementation LockMe
+- (NSString *) description
+{
+ printf ("LockMe trying to get the lock.\n");
+ pthread_mutex_lock(&test_mutex);
+ printf ("LockMe got the lock.\n");
+ pthread_mutex_unlock(&test_mutex);
+ return @"I am pretty special.\n";
+}
+@end
+
+void *
+my_pthread_routine (void *data)
+{
+ printf ("my_pthread_routine about to enter.\n");
+ pthread_mutex_lock(&test_mutex);
+ printf ("Releasing Lock.\n"); // Set a breakpoint here.
+ pthread_mutex_unlock(&test_mutex);
+ return NULL;
+}
+
+int
+main ()
+{
+ pthread_attr_t tmp_attr;
+ pthread_attr_init (&tmp_attr);
+ pthread_t my_pthread;
+
+ Mutex_Init ();
+
+ LockMe *lock_me = [[LockMe alloc] init];
+ pthread_create (&my_pthread, &tmp_attr, my_pthread_routine, NULL);
+
+ pthread_join (my_pthread, NULL);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/radar-9691614/Makefile b/packages/Python/lldbsuite/test/lang/objc/radar-9691614/Makefile
new file mode 100644
index 000000000000..ad3cb3fadcde
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/radar-9691614/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/lang/objc/radar-9691614/TestObjCMethodReturningBOOL.py b/packages/Python/lldbsuite/test/lang/objc/radar-9691614/TestObjCMethodReturningBOOL.py
new file mode 100644
index 000000000000..38551f671a92
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/radar-9691614/TestObjCMethodReturningBOOL.py
@@ -0,0 +1,45 @@
+"""
+Test that objective-c method returning BOOL works correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+@skipUnlessDarwin
+class MethodReturningBOOLTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # We'll use the test method name as the exe_name.
+ self.exe_name = self.testMethodName
+ # Find the line number to break inside main().
+ self.main_source = "main.m"
+ self.line = line_number(self.main_source, '// Set breakpoint here.')
+
+ def test_method_ret_BOOL(self):
+ """Test that objective-c method returning BOOL works correctly."""
+ d = {'EXE': self.exe_name}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+
+ exe = os.path.join(os.getcwd(), self.exe_name)
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+ self.expect("process status", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = [" at %s:%d" % (self.main_source, self.line),
+ "stop reason = breakpoint"])
+
+ # rdar://problem/9691614
+ self.runCmd('p (int)[my isValid]')
diff --git a/packages/Python/lldbsuite/test/lang/objc/radar-9691614/main.m b/packages/Python/lldbsuite/test/lang/objc/radar-9691614/main.m
new file mode 100644
index 000000000000..bb87d673452c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/radar-9691614/main.m
@@ -0,0 +1,67 @@
+#import <Foundation/Foundation.h>
+#include <stdio.h>
+
+@interface MyString : NSObject {
+ NSString *str;
+ NSDate *date;
+ BOOL _is_valid;
+}
+
+- (id)initWithNSString:(NSString *)string;
+- (BOOL)isValid;
+@end
+
+@implementation MyString
+- (id)initWithNSString:(NSString *)string
+{
+ if (self = [super init])
+ {
+ str = [NSString stringWithString:string];
+ date = [NSDate date];
+ }
+ _is_valid = YES;
+ return self;
+}
+
+- (BOOL)isValid
+{
+ return _is_valid;
+}
+
+- (void)dealloc
+{
+ [date release];
+ [str release];
+ [super dealloc];
+}
+
+- (NSString *)description
+{
+ return [str stringByAppendingFormat:@" with timestamp: %@", date];
+}
+@end
+
+void
+Test_MyString (const char *program)
+{
+ NSString *str = [NSString stringWithFormat:@"Hello from '%s'", program];
+ MyString *my = [[MyString alloc] initWithNSString:str];
+ if ([my isValid])
+ printf("my is valid!\n");
+
+ NSLog(@"NSString instance: %@", [str description]); // Set breakpoint here.
+ // Test 'p (int)[my isValid]'.
+ // The expression parser should not crash -- rdar://problem/9691614.
+
+ NSLog(@"MyString instance: %@", [my description]);
+}
+
+int main (int argc, char const *argv[])
+{
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+
+ Test_MyString (argv[0]);
+
+ [pool release];
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/Makefile b/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/Makefile
new file mode 100644
index 000000000000..ad3cb3fadcde
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/TestRdar10967107.py b/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/TestRdar10967107.py
new file mode 100644
index 000000000000..0902527d424c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/TestRdar10967107.py
@@ -0,0 +1,44 @@
+"""
+Test that CoreFoundation classes CFGregorianDate and CFRange are not improperly uniqued
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+@skipUnlessDarwin
+class Rdar10967107TestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # We'll use the test method name as the exe_name.
+ self.exe_name = self.testMethodName
+ # Find the line number to break inside main().
+ self.main_source = "main.m"
+ self.line = line_number(self.main_source, '// Set breakpoint here.')
+
+ def test_cfrange_diff_cfgregoriandate(self):
+ """Test that CoreFoundation classes CFGregorianDate and CFRange are not improperly uniqued."""
+ d = {'EXE': self.exe_name}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+
+ exe = os.path.join(os.getcwd(), self.exe_name)
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, self.main_source, self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+ # check that each type is correctly bound to its list of children
+ self.expect("frame variable cf_greg_date --raw", substrs = ['year','month','day','hour','minute','second'])
+ self.expect("frame variable cf_range --raw", substrs = ['location','length'])
+ # check that printing both does not somehow confuse LLDB
+ self.expect("frame variable --raw", substrs = ['year','month','day','hour','minute','second','location','length'])
diff --git a/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/main.m b/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/main.m
new file mode 100644
index 000000000000..386a458950b6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/rdar-10967107/main.m
@@ -0,0 +1,13 @@
+#import <Foundation/Foundation.h>
+
+int main (int argc, char const *argv[])
+{
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+
+ NSDate *date1 = [NSDate date];
+ CFGregorianDate cf_greg_date = CFAbsoluteTimeGetGregorianDate(CFDateGetAbsoluteTime((CFDateRef)date1), NULL);
+ CFRange cf_range = {4,4};
+
+ [pool release]; // Set breakpoint here.
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/Makefile b/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/Makefile
new file mode 100644
index 000000000000..ad3cb3fadcde
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/TestRdar11355592.py b/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/TestRdar11355592.py
new file mode 100644
index 000000000000..42120a57834c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/TestRdar11355592.py
@@ -0,0 +1,65 @@
+"""
+Test that we do not attempt to make a dynamic type for a 'const char*'
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+@skipUnlessDarwin
+class Rdar10967107TestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # We'll use the test method name as the exe_name.
+ self.exe_name = self.testMethodName
+ # Find the line number to break inside main().
+ self.main_source = "main.m"
+ self.line = line_number(self.main_source, '// Set breakpoint here.')
+
+ def test_charstar_dyntype(self):
+ """Test that we do not attempt to make a dynamic type for a 'const char*'"""
+ d = {'EXE': self.exe_name}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+
+ exe = os.path.join(os.getcwd(), self.exe_name)
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, self.main_source, self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+ # check that we correctly see the const char*, even with dynamic types on
+ self.expect("frame variable my_string", substrs = ['const char *'])
+ self.expect("frame variable my_string --dynamic-type run-target", substrs = ['const char *'])
+ # check that expr also gets it right
+ self.expect("expr my_string", substrs = ['const char *'])
+ self.expect("expr -d run -- my_string", substrs = ['const char *'])
+ # but check that we get the real Foolie as such
+ self.expect("frame variable my_foolie", substrs = ['FoolMeOnce *'])
+ self.expect("frame variable my_foolie --dynamic-type run-target", substrs = ['FoolMeOnce *'])
+ # check that expr also gets it right
+ self.expect("expr my_foolie", substrs = ['FoolMeOnce *'])
+ self.expect("expr -d run -- my_foolie", substrs = ['FoolMeOnce *'])
+ # now check that assigning a true string does not break anything
+ self.runCmd("next")
+ # check that we correctly see the const char*, even with dynamic types on
+ self.expect("frame variable my_string", substrs = ['const char *'])
+ self.expect("frame variable my_string --dynamic-type run-target", substrs = ['const char *'])
+ # check that expr also gets it right
+ self.expect("expr my_string", substrs = ['const char *'])
+ self.expect("expr -d run -- my_string", substrs = ['const char *'])
+ # but check that we get the real Foolie as such
+ self.expect("frame variable my_foolie", substrs = ['FoolMeOnce *'])
+ self.expect("frame variable my_foolie --dynamic-type run-target", substrs = ['FoolMeOnce *'])
+ # check that expr also gets it right
+ self.expect("expr my_foolie", substrs = ['FoolMeOnce *'])
+ self.expect("expr -d run -- my_foolie", substrs = ['FoolMeOnce *'])
diff --git a/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/main.m b/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/main.m
new file mode 100644
index 000000000000..09b3b18a7878
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/rdar-11355592/main.m
@@ -0,0 +1,37 @@
+#import <Foundation/Foundation.h>
+
+@interface FoolMeOnce : NSObject
+{
+ int32_t value_one; // ivars needed to make 32-bit happy
+ int32_t value_two;
+}
+- (FoolMeOnce *) initWithFirst: (int32_t) first andSecond: (int32_t) second;
+
+@property int32_t value_one;
+@property int32_t value_two;
+
+@end
+
+@implementation FoolMeOnce
+@synthesize value_one;
+@synthesize value_two;
+- (FoolMeOnce *) initWithFirst: (int32_t) first andSecond: (int32_t) second
+{
+ value_one = first;
+ value_two = second;
+ return self;
+}
+@end
+
+int main (int argc, char const *argv[])
+{
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+
+ FoolMeOnce *my_foolie = [[FoolMeOnce alloc] initWithFirst: 20 andSecond: 55];
+ const char *my_string = (char *) my_foolie;
+
+ my_string = "Now this is a REAL string..."; // Set breakpoint here.
+
+ [pool release];
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/Makefile b/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/Makefile
new file mode 100644
index 000000000000..385b557c9af0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/Makefile
@@ -0,0 +1,11 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+
+include $(LEVEL)/Makefile.rules
+
+ifneq (,$(findstring arm,$(ARCH)))
+ LD_EXTRAS = -framework Foundation -framework UIKit
+else
+ LD_EXTRAS = -framework Foundation -framework Cocoa
+endif
diff --git a/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/TestRdar12408181.py b/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/TestRdar12408181.py
new file mode 100644
index 000000000000..b95d95106032
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/TestRdar12408181.py
@@ -0,0 +1,48 @@
+"""
+Test that we are able to find out how many children NSWindow has
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+@skipUnlessDarwin
+class Rdar12408181TestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # We'll use the test method name as the exe_name.
+ self.exe_name = self.testMethodName
+ # Find the line number to break inside main().
+ self.main_source = "main.m"
+ self.line = line_number(self.main_source, '// Set breakpoint here.')
+
+ def test_nswindow_count(self):
+ """Test that we are able to find out how many children NSWindow has."""
+ d = {'EXE': self.exe_name}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+
+ exe = os.path.join(os.getcwd(), self.exe_name)
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, self.main_source, self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+ if self.frame().EvaluateExpression('(void*)_CGSDefaultConnection()').GetValueAsUnsigned() != 0:
+ window = self.frame().FindVariable("window")
+ window_dynamic = window.GetDynamicValue(lldb.eDynamicCanRunTarget)
+ self.assertTrue(window.GetNumChildren() > 1, "NSWindow (static) only has 1 child!")
+ self.assertTrue(window_dynamic.GetNumChildren() > 1, "NSWindow (dynamic) only has 1 child!")
+ self.assertTrue(window.GetChildAtIndex(0).IsValid(), "NSWindow (static) has an invalid child")
+ self.assertTrue(window_dynamic.GetChildAtIndex(0).IsValid(), "NSWindow (dynamic) has an invalid child")
+ else:
+ self.skipTest('no WindowServer connection')
diff --git a/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/main.m b/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/main.m
new file mode 100644
index 000000000000..858ba2a4a22f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/rdar-12408181/main.m
@@ -0,0 +1,24 @@
+#import <Foundation/Foundation.h>
+#if defined (__i386__) || defined (__x86_64__)
+#import <Cocoa/Cocoa.h>
+#else
+#import <UIKit/UIKit.h>
+#endif
+
+int main (int argc, char const *argv[])
+{
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+#if defined (__i386__) || defined (__x86_64__)
+
+ [NSApplication sharedApplication];
+ NSWindow* window = [[NSWindow alloc] initWithContentRect:NSMakeRect(0,0,100,100) styleMask:NSBorderlessWindowMask backing:NSBackingStoreRetained defer:NO];
+ [window setCanHide:YES];
+#else
+ [UIApplication sharedApplication];
+ CGRect rect = { 0, 0, 100, 100};
+ UIWindow* window = [[UIWindow alloc] initWithFrame:rect];
+#endif
+ [pool release]; // Set breakpoint here.
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/lang/objc/real-definition/Bar.h b/packages/Python/lldbsuite/test/lang/objc/real-definition/Bar.h
new file mode 100644
index 000000000000..20a81faa1017
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/real-definition/Bar.h
@@ -0,0 +1,12 @@
+#import <Foundation/Foundation.h>
+
+@class InternalClass;
+
+@interface Bar : NSObject {
+ @private
+ InternalClass *storage;
+}
+
+- (NSString *)description;
+
+@end \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/lang/objc/real-definition/Bar.m b/packages/Python/lldbsuite/test/lang/objc/real-definition/Bar.m
new file mode 100644
index 000000000000..46d7e3888751
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/real-definition/Bar.m
@@ -0,0 +1,43 @@
+#import "Bar.h"
+
+@interface InternalClass : NSObject {
+ @public
+ NSString *foo;
+ NSString *bar;
+}
+@end
+
+@implementation InternalClass
+@end
+
+@interface Bar ()
+{
+ NSString *_hidden_ivar;
+}
+
+@end
+
+@implementation Bar
+
+- (id)init
+{
+ self = [super init];
+ if (self) {
+ _hidden_ivar = [NSString stringWithFormat:@"%p: @Bar", self];
+ }
+ return self; // Set breakpoint where Bar is an implementation
+}
+
+- (void)dealloc
+{
+ [_hidden_ivar release];
+ [super dealloc];
+}
+
+- (NSString *)description
+{
+ return [_hidden_ivar copyWithZone:NULL];
+}
+
+@end
+ \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/lang/objc/real-definition/Foo.h b/packages/Python/lldbsuite/test/lang/objc/real-definition/Foo.h
new file mode 100644
index 000000000000..14ff9eed50fd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/real-definition/Foo.h
@@ -0,0 +1,11 @@
+#import <Foundation/Foundation.h>
+
+#import "Bar.h"
+
+@interface Foo : NSObject {
+ Bar *_bar;
+}
+
+- (NSString *)description;
+
+@end \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/lang/objc/real-definition/Foo.m b/packages/Python/lldbsuite/test/lang/objc/real-definition/Foo.m
new file mode 100644
index 000000000000..bcdeaeffc29a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/real-definition/Foo.m
@@ -0,0 +1,25 @@
+#import "Foo.h"
+
+@implementation Foo
+
+- (id)init
+{
+ self = [super init];
+ if (self) {
+ _bar = [[Bar alloc] init];
+ }
+ return self; // Set breakpoint where Bar is an interface
+}
+
+- (void)dealloc
+{
+ [_bar release];
+ [super dealloc];
+}
+
+- (NSString *)description
+{
+ return [NSString stringWithFormat:@"%p: @Foo { _bar = %@ }", self, _bar];
+}
+
+@end
diff --git a/packages/Python/lldbsuite/test/lang/objc/real-definition/Makefile b/packages/Python/lldbsuite/test/lang/objc/real-definition/Makefile
new file mode 100644
index 000000000000..61cc3b3b6db8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/real-definition/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := Bar.m Foo.m main.m
+LDFLAGS = $(CFLAGS) -lobjc -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/real-definition/TestRealDefinition.py b/packages/Python/lldbsuite/test/lang/objc/real-definition/TestRealDefinition.py
new file mode 100644
index 000000000000..30fd2a5b0f6d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/real-definition/TestRealDefinition.py
@@ -0,0 +1,86 @@
+"""Test that types defined in shared libraries work correctly."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TestRealDefinition(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipUnlessDarwin
+ def test_frame_var_after_stop_at_interface(self):
+ """Test that we can find the implementation for an objective C type"""
+ if self.getArchitecture() == 'i386':
+ self.skipTest("requires modern objc runtime")
+ self.build()
+ self.common_setup()
+
+ line = line_number('Foo.m', '// Set breakpoint where Bar is an interface')
+ lldbutil.run_break_set_by_file_and_line (self, 'Foo.m', line, num_expected_locations=1, loc_exact=True);
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Run and stop at Foo
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ self.runCmd("continue", RUN_SUCCEEDED)
+
+ # Run at stop at main
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ # This should display correctly.
+ self.expect("frame variable foo->_bar->_hidden_ivar", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["(NSString *)", "foo->_bar->_hidden_ivar = 0x"])
+
+ @skipUnlessDarwin
+ def test_frame_var_after_stop_at_implementation(self):
+ """Test that we can find the implementation for an objective C type"""
+ if self.getArchitecture() == 'i386':
+ self.skipTest("requires modern objc runtime")
+ self.build()
+ self.common_setup()
+
+ line = line_number('Bar.m', '// Set breakpoint where Bar is an implementation')
+ lldbutil.run_break_set_by_file_and_line (self, 'Bar.m', line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # Run and stop at Foo
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ self.runCmd("continue", RUN_SUCCEEDED)
+
+ # Run at stop at main
+ self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
+ substrs = [' resolved, hit count = 1'])
+
+ # This should display correctly.
+ self.expect("frame variable foo->_bar->_hidden_ivar", VARIABLES_DISPLAYED_CORRECTLY,
+ substrs = ["(NSString *)", "foo->_bar->_hidden_ivar = 0x"])
+
+ def common_setup(self):
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Break inside the foo function which takes a bar_ptr argument.
+ line = line_number('main.m', '// Set breakpoint in main')
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", line, num_expected_locations=1, loc_exact=True)
diff --git a/packages/Python/lldbsuite/test/lang/objc/real-definition/main.m b/packages/Python/lldbsuite/test/lang/objc/real-definition/main.m
new file mode 100644
index 000000000000..8c31dc9abb31
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/real-definition/main.m
@@ -0,0 +1,13 @@
+#include <stdio.h>
+#include <stdint.h>
+#import <Foundation/Foundation.h>
+#import "Foo.h"
+
+int main (int argc, char const *argv[])
+{
+ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
+ Foo *foo = [[Foo alloc] init];
+ NSLog (@"foo is %@", foo); // Set breakpoint in main
+ [pool release];
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/sample/Makefile b/packages/Python/lldbsuite/test/lang/objc/sample/Makefile
new file mode 100644
index 000000000000..a1608fe5a664
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/sample/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+LDFLAGS = $(CFLAGS) -lobjc -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/sample/main.m b/packages/Python/lldbsuite/test/lang/objc/sample/main.m
new file mode 100644
index 000000000000..9dffc71aaac6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/sample/main.m
@@ -0,0 +1,70 @@
+#import <Foundation/Foundation.h>
+
+
+@interface MyString : NSObject {
+ NSString *_string;
+ NSDate *_date;
+}
+- (id)initWithNSString:(NSString *)string;
+
+@property (copy) NSString *string;
+@property (readonly,getter=getTheDate) NSDate *date;
+
+- (NSDate *) getTheDate;
+@end
+
+@implementation MyString
+
+@synthesize string = _string;
+@synthesize date = _date;
+
+- (id)initWithNSString:(NSString *)string
+{
+ if (self = [super init])
+ {
+ _string = [NSString stringWithString:string];
+ _date = [NSDate date];
+ }
+ return self;
+}
+
+- (void) dealloc
+{
+ [_date release];
+ [_string release];
+ [super dealloc];
+}
+
+- (NSDate *) getTheDate
+{
+ return _date;
+}
+
+- (NSString *)description
+{
+ return [_string stringByAppendingFormat:@" with timestamp: %@", _date];
+}
+@end
+
+int main (int argc, char const *argv[])
+{
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+ static NSString *g_global_nsstr = @"Howdy";
+
+ MyString *myStr = [[MyString alloc] initWithNSString: [NSString stringWithFormat:@"string %i", 1]];
+ NSString *str1 = myStr.string;
+ NSString *str2 = [NSString stringWithFormat:@"string %i", 2];
+ NSString *str3 = [NSString stringWithFormat:@"string %i", 3];
+ NSArray *array = [NSArray arrayWithObjects: str1, str2, str3, nil];
+ NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
+ str1, @"1",
+ str2, @"2",
+ str3, @"3",
+ myStr.date, @"date",
+ nil];
+
+ id str_id = str1;
+ SEL sel = @selector(length);
+ [pool release];
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lang/objc/self/Makefile b/packages/Python/lldbsuite/test/lang/objc/self/Makefile
new file mode 100644
index 000000000000..bdae30428be4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/self/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+OBJC_SOURCES := main.m
+LD_EXTRAS ?= -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objc/self/TestObjCSelf.py b/packages/Python/lldbsuite/test/lang/objc/self/TestObjCSelf.py
new file mode 100644
index 000000000000..37db151f9ae3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/self/TestObjCSelf.py
@@ -0,0 +1,36 @@
+"""
+Tests that ObjC member variables are available where they should be.
+"""
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ObjCSelfTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipUnlessDarwin
+ def test_with_run_command(self):
+ """Test that the appropriate member variables are available when stopped in Objective-C class and instance methods"""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ self.set_breakpoint(line_number('main.m', '// breakpoint 1'))
+ self.set_breakpoint(line_number('main.m', '// breakpoint 2'))
+
+ self.runCmd("process launch", RUN_SUCCEEDED)
+
+ self.expect("expression -- m_a = 2",
+ startstr = "(int) $0 = 2")
+
+ self.runCmd("process continue")
+
+ # This would be disallowed if we enforced const. But we don't.
+ self.expect("expression -- m_a = 2",
+ error=True)
+
+ self.expect("expression -- s_a",
+ startstr = "(int) $1 = 5")
+
+ def set_breakpoint(self, line):
+ lldbutil.run_break_set_by_file_and_line (self, "main.m", line, num_expected_locations=1, loc_exact=True)
diff --git a/packages/Python/lldbsuite/test/lang/objc/self/main.m b/packages/Python/lldbsuite/test/lang/objc/self/main.m
new file mode 100644
index 000000000000..928aaf2ff024
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objc/self/main.m
@@ -0,0 +1,54 @@
+//===-- main.m ------------------------------------------*- Objective-C -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#import <Foundation/Foundation.h>
+
+@interface A : NSObject
+{
+ int m_a;
+}
+-(id)init;
+-(void)accessMember:(int)a;
++(void)accessStaticMember:(int)a;
+@end
+
+static int s_a = 5;
+
+@implementation A
+-(id)init
+{
+ self = [super init];
+
+ if (self)
+ m_a = 2;
+
+ return self;
+}
+
+-(void)accessMember:(int)a
+{
+ m_a = a; // breakpoint 1
+}
+
++(void)accessStaticMember:(int)a
+{
+ s_a = a; // breakpoint 2
+}
+@end
+
+int main()
+{
+ NSAutoreleasePool *pool = [NSAutoreleasePool alloc];
+ A *my_a = [[A alloc] init];
+
+ [my_a accessMember:3];
+ [A accessStaticMember:5];
+
+ [pool release];
+}
diff --git a/packages/Python/lldbsuite/test/lang/objcxx/objcxx-ivar-vector/TestIvarVector.py b/packages/Python/lldbsuite/test/lang/objcxx/objcxx-ivar-vector/TestIvarVector.py
new file mode 100644
index 000000000000..80305e303d03
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objcxx/objcxx-ivar-vector/TestIvarVector.py
@@ -0,0 +1,4 @@
+import lldbsuite.test.lldbinline as lldbinline
+import lldbsuite.test.lldbtest as lldbtest
+
+lldbinline.MakeInlineTest(__file__, globals(), [lldbtest.skipIfFreeBSD,lldbtest.skipIfLinux,lldbtest.skipIfWindows])
diff --git a/packages/Python/lldbsuite/test/lang/objcxx/objcxx-ivar-vector/main.mm b/packages/Python/lldbsuite/test/lang/objcxx/objcxx-ivar-vector/main.mm
new file mode 100644
index 000000000000..36eda1da2acb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objcxx/objcxx-ivar-vector/main.mm
@@ -0,0 +1,33 @@
+#import <Foundation/Foundation.h>
+
+#include <vector>
+
+@interface MyElement : NSObject {
+}
+@end
+
+@interface MyClass : NSObject {
+ std::vector<MyElement *> elements;
+};
+
+-(void)doSomething;
+
+@end
+
+@implementation MyClass
+
+-(void)doSomething
+{
+ NSLog(@"Hello"); //% self.expect("expression -- elements", DATA_TYPES_DISPLAYED_CORRECTLY, substrs = ["vector", "MyElement"]);
+}
+
+@end
+
+int main ()
+{
+ @autoreleasepool
+ {
+ MyClass *c = [MyClass alloc];
+ [c doSomething];
+ }
+}
diff --git a/packages/Python/lldbsuite/test/lang/objcxx/sample/Makefile b/packages/Python/lldbsuite/test/lang/objcxx/sample/Makefile
new file mode 100644
index 000000000000..edd3430de7c8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objcxx/sample/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+OBJCXX_SOURCES := main.mm
+LDFLAGS = $(CFLAGS) -lobjc -framework Foundation
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/lang/objcxx/sample/main.mm b/packages/Python/lldbsuite/test/lang/objcxx/sample/main.mm
new file mode 100644
index 000000000000..c9a2172c368c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lang/objcxx/sample/main.mm
@@ -0,0 +1,71 @@
+#import <Foundation/Foundation.h>
+#include <iostream>
+
+@interface MyString : NSObject {
+ NSString *_string;
+ NSDate *_date;
+}
+- (id)initWithNSString:(NSString *)string;
+
+@property (copy) NSString *string;
+@property (readonly,getter=getTheDate) NSDate *date;
+
+- (NSDate *) getTheDate;
+@end
+
+@implementation MyString
+
+@synthesize string = _string;
+@synthesize date = _date;
+
+- (id)initWithNSString:(NSString *)string
+{
+ if (self = [super init])
+ {
+ _string = [NSString stringWithString:string];
+ _date = [NSDate date];
+ }
+ return self;
+}
+
+- (void) dealloc
+{
+ [_date release];
+ [_string release];
+ [super dealloc];
+}
+
+- (NSDate *) getTheDate
+{
+ return _date;
+}
+
+- (NSString *)description
+{
+ return [_string stringByAppendingFormat:@" with timestamp: %@", _date];
+}
+@end
+
+int main (int argc, char const *argv[])
+{
+ NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
+ static NSString *g_global_nsstr = @"Howdy";
+
+ MyString *myStr = [[MyString alloc] initWithNSString: [NSString stringWithFormat:@"string %i", 1]];
+ NSString *str1 = myStr.string;
+ NSString *str2 = [NSString stringWithFormat:@"string %i", 2];
+ NSString *str3 = [NSString stringWithFormat:@"string %i", 3];
+ NSArray *array = [NSArray arrayWithObjects: str1, str2, str3, nil];
+ NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
+ str1, @"1",
+ str2, @"2",
+ str3, @"3",
+ myStr.date, @"date",
+ nil];
+
+ id str_id = str1;
+ SEL sel = @selector(length);
+ [pool release];
+ std::cout << "Hello, objc++!\n";
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/linux/builtin_trap/Makefile b/packages/Python/lldbsuite/test/linux/builtin_trap/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/linux/builtin_trap/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/linux/builtin_trap/TestBuiltinTrap.py b/packages/Python/lldbsuite/test/linux/builtin_trap/TestBuiltinTrap.py
new file mode 100644
index 000000000000..ea742341512c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/linux/builtin_trap/TestBuiltinTrap.py
@@ -0,0 +1,51 @@
+"""
+Test lldb ability to unwind a stack with a function containing a call to the
+'__builtin_trap' intrinsic, which GCC (4.6) encodes to an illegal opcode.
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class BuiltinTrapTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ @expectedFailureAll("llvm.org/pr15936", compiler="gcc", compiler_version=["<=","4.6"])
+ @expectedFailureAll(archs="arm", compiler="gcc", triple=".*-android") # gcc generates incorrect linetable
+ @skipIfWindows
+ def test_with_run_command(self):
+ """Test that LLDB handles a function with __builtin_trap correctly."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line,
+ num_expected_locations=1,
+ loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # print backtrace, expect both 'bar' and 'main' functions to be listed
+ self.expect('bt', substrs = ['bar', 'main'])
+
+ # go up one frame
+ self.runCmd("up", RUN_SUCCEEDED)
+
+ # evaluate a local
+ self.expect('p foo', substrs = ['= 5'])
diff --git a/packages/Python/lldbsuite/test/linux/builtin_trap/main.cpp b/packages/Python/lldbsuite/test/linux/builtin_trap/main.cpp
new file mode 100644
index 000000000000..84156ef2ac4f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/linux/builtin_trap/main.cpp
@@ -0,0 +1,17 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+void bar(int const *foo) {
+ __builtin_trap(); // Set break point at this line.
+}
+
+int main() {
+ int foo = 5;
+ bar(&foo);
+}
diff --git a/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/Makefile b/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/Makefile
new file mode 100644
index 000000000000..67aa16625bff
--- /dev/null
+++ b/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+ENABLE_THREADS := YES
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/TestCreateDuringInstructionStep.py b/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/TestCreateDuringInstructionStep.py
new file mode 100644
index 000000000000..c6d9afb02003
--- /dev/null
+++ b/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/TestCreateDuringInstructionStep.py
@@ -0,0 +1,66 @@
+"""
+This tests that we do not lose control of the inferior, while doing an instruction-level step
+over a thread creation instruction.
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class CreateDuringInstructionStepTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+
+ @skipUnlessPlatform(['linux'])
+ @expectedFailureAndroid('llvm.org/pr24737', archs=['arm'])
+ def test_step_inst(self):
+ self.build(dictionary=self.getBuildFlags())
+ exe = os.path.join(os.getcwd(), "a.out")
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target and target.IsValid(), "Target is valid")
+
+ # This should create a breakpoint in the stepping thread.
+ breakpoint = target.BreakpointCreateByName("main")
+ self.assertTrue(breakpoint and breakpoint.IsValid(), "Breakpoint is valid")
+
+ # Run the program.
+ process = target.LaunchSimple(None, None, self.get_process_working_directory())
+ self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ self.assertEqual(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED)
+
+ threads = lldbutil.get_threads_stopped_at_breakpoint(process, breakpoint)
+ self.assertEqual(len(threads), 1, STOPPED_DUE_TO_BREAKPOINT)
+
+ thread = threads[0]
+ self.assertTrue(thread and thread.IsValid(), "Thread is valid")
+
+ # Make sure we see only one threads
+ self.assertEqual(process.GetNumThreads(), 1, 'Number of expected threads and actual threads do not match.')
+
+ # Keep stepping until we see the thread creation
+ while process.GetNumThreads() < 2:
+ thread.StepInstruction(False)
+ self.assertEqual(process.GetState(), lldb.eStateStopped, PROCESS_STOPPED)
+ self.assertEqual(thread.GetStopReason(), lldb.eStopReasonPlanComplete, "Step operation succeeded")
+ if self.TraceOn():
+ self.runCmd("disassemble --pc")
+
+ if self.TraceOn():
+ self.runCmd("thread list")
+
+ # We have successfully caught thread creation. Now just run to completion
+ process.Continue()
+
+ # At this point, the inferior process should have exited.
+ self.assertEqual(process.GetState(), lldb.eStateExited, PROCESS_EXITED)
diff --git a/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/main.cpp b/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/main.cpp
new file mode 100644
index 000000000000..079e8b13798c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/linux/thread/create_during_instruction_step/main.cpp
@@ -0,0 +1,55 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+// This file deliberately uses low level linux-specific API for thread creation because:
+// - instruction-stepping over thread creation using higher-level functions was very slow
+// - it was also unreliable due to single-stepping bugs unrelated to this test
+// - some threading libraries do not create or destroy threads when we would expect them to
+
+#include <sched.h>
+
+#include <atomic>
+#include <cstdio>
+
+enum { STACK_SIZE = 0x2000 };
+
+static uint8_t child_stack[STACK_SIZE];
+
+pid_t child_tid;
+
+std::atomic<bool> flag(false);
+
+int thread_main(void *)
+{
+ while (! flag) // Make sure the thread does not exit prematurely
+ ;
+
+ return 0;
+}
+
+int main ()
+{
+ int ret = clone(thread_main,
+ child_stack + STACK_SIZE/2, // Don't care whether the stack grows up or down,
+ // just point to the middle
+ CLONE_CHILD_CLEARTID | CLONE_FILES | CLONE_FS | CLONE_PARENT_SETTID |
+ CLONE_SIGHAND | CLONE_SYSVSEM | CLONE_THREAD | CLONE_VM,
+ nullptr, // thread_main argument
+ &child_tid);
+
+ if (ret == -1)
+ {
+ perror("clone");
+ return 1;
+ }
+
+ flag = true;
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/lldb_pylint_helper.py b/packages/Python/lldbsuite/test/lldb_pylint_helper.py
new file mode 100644
index 000000000000..1cc09441a2d6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lldb_pylint_helper.py
@@ -0,0 +1,181 @@
+"""
+ The LLVM Compiler Infrastructure
+
+This file is distributed under the University of Illinois Open Source
+License. See LICENSE.TXT for details.
+
+Sync lldb and related source from a local machine to a remote machine.
+
+This facilitates working on the lldb sourcecode on multiple machines
+and multiple OS types, verifying changes across all.
+
+Provides helper support for adding lldb test paths to the python path.
+"""
+
+from __future__ import print_function
+from __future__ import absolute_import
+
+# System modules
+import os
+import platform
+import subprocess
+import sys
+
+# Third-party modules
+
+# LLDB modules
+
+
+def add_lldb_test_paths(check_dir):
+ # pylint: disable=line-too-long
+ """Adds lldb test-related paths to the python path.
+
+ Starting with the given directory and working upward through
+ each parent directory up to the root, it looks for the lldb
+ test directory. When found, the lldb test directory and its
+ child test_runner/lib directory will be added to the python
+ system path.
+
+ Instructions for use:
+
+ This method supports a simple way of getting pylint to be able
+ to reliably lint lldb python test scripts (including the test
+ infrastructure itself). To do so, add the following to a
+ .pylintrc file in your home directory:
+
+ [Master]
+ init-hook='import os; import sys; sys.path.append(os.path.expanduser("~/path/to/lldb/packages/Python/lldbsuite/test")); import lldb_pylint_helper; lldb_pylint_helper.add_lldb_test_paths(os.getcwd()); print("sys.path={}\n".format(sys.path))'
+
+ Replace ~/path/to/lldb with a valid path to your local lldb source
+ tree. Note you can have multiple lldb source trees on your system, and
+ this will work just fine. The path in your .pylintrc is just needed to
+ find the paths needed for pylint in whatever lldb source tree you're in.
+ pylint will use the python files in whichever tree it is run from.
+
+ Note it is critical that the init-hook line be contained on a single line.
+ You can remove the print line at the end once you know the pythonpath is
+ getting set up the way you expect.
+
+ With these changes, you will be able to run the following, for example.
+
+ cd lldb/sourcetree/1-of-many/test/lang/c/anonymous
+ pylint TestAnonymous.py
+
+ This will work, and include all the lldb/sourcetree/1-of-many lldb-specific
+ python directories to your path.
+
+ You can then run it in another lldb source tree on the same machine like
+ so:
+
+ cd lldb/sourcetree/2-of-many/test/functionalities/inferior-assert
+ pyline TestInferiorAssert.py
+
+ and this will properly lint that file, using the lldb-specific python
+ directories from the 2-of-many source tree.
+
+ Note at the time I'm writing this, our tests are in pretty sad shape
+ as far as a stock pylint setup goes. But we need to start somewhere :-)
+
+ @param check_dir specifies a directory that will be used to start
+ looking for the lldb test infrastructure python library paths.
+ """
+ # Add the test-related packages themselves.
+ add_lldb_test_package_paths(check_dir)
+
+ # Add the lldb directory itself
+ add_lldb_module_directory()
+
+
+def add_lldb_module_directory():
+ """
+ Desired Approach:
+
+ Part A: find an lldb
+
+ 1. Walk up the parent chain from the current directory, looking for
+ a directory matching *build*. If we find that, use it as the
+ root of a directory search for an lldb[.exe] executable.
+
+ 2. If 1 fails, use the path and look for an lldb[.exe] in there.
+
+ If Part A ends up with an lldb, go to part B. Otherwise, give up
+ on the lldb python module path.
+
+ Part B: use the output from 'lldb[.exe] -P' to find the lldb dir.
+
+ Current approach:
+ If Darwin, use 'xcrun lldb -P'; others: find lldb on path.
+
+ Drawback to current approach:
+ If the tester is changing the SB API (adding new methods), pylint
+ will not know about them as it is using the wrong lldb python module.
+ In practice, this should be minor.
+ """
+ try:
+ lldb_module_path = None
+
+ if platform.system() == 'Darwin':
+ # Use xcrun to find the selected lldb.
+ lldb_module_path = subprocess.check_output(["xcrun", "lldb", "-P"])
+ elif platform.system() == 'Windows':
+ lldb_module_path = subprocess.check_output(
+ ["lldb.exe", "-P"], shell=True)
+ else:
+ # Use the shell to run lldb from the path.
+ lldb_module_path = subprocess.check_output(
+ ["lldb", "-P"], shell=True)
+
+ # Trim the result.
+ if lldb_module_path is not None:
+ lldb_module_path = lldb_module_path.strip()
+
+ # If we have a result, add it to the path
+ if lldb_module_path is not None and len(lldb_module_path) > 0:
+ sys.path.insert(0, lldb_module_path)
+ # pylint: disable=broad-except
+ except Exception as exception:
+ print("failed to find python path: {}".format(exception))
+
+
+def add_lldb_test_package_paths(check_dir):
+ """Adds the lldb test infrastructure modules to the python path.
+
+ See add_lldb_test_paths for more details.
+
+ @param check_dir the directory of the test.
+ """
+
+ def child_dirs(parent_dir):
+ return [os.path.join(parent_dir, child)
+ for child in os.listdir(parent_dir)
+ if os.path.isdir(os.path.join(parent_dir, child))]
+
+ check_dir = os.path.realpath(check_dir)
+ while check_dir and len(check_dir) > 0:
+ # If the current directory contains a packages/Python
+ # directory, add that directory to the path.
+ packages_python_child_dir = os.path.join(
+ check_dir, "packages", "Python")
+ if os.path.exists(packages_python_child_dir):
+ sys.path.insert(0, packages_python_child_dir)
+ sys.path.insert(0, os.path.join(
+ packages_python_child_dir, "test_runner", "lib"))
+
+ # Handle third_party module/package directory.
+ third_party_module_dir = os.path.join(
+ check_dir, "third_party", "Python", "module")
+ for child_dir in child_dirs(third_party_module_dir):
+ # Yes, we embed the module in the module parent dir
+ sys.path.insert(0, child_dir)
+
+ # We're done.
+ break
+
+ # Continue looking up the parent chain until we have no more
+ # directories to check.
+ new_check_dir = os.path.dirname(check_dir)
+ # We're done when the new check dir is not different
+ # than the current one.
+ if new_check_dir == check_dir:
+ break
+ check_dir = new_check_dir
diff --git a/packages/Python/lldbsuite/test/lldbbench.py b/packages/Python/lldbsuite/test/lldbbench.py
new file mode 100644
index 000000000000..6b568f874661
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lldbbench.py
@@ -0,0 +1,118 @@
+from __future__ import absolute_import
+
+# System modules
+import time
+
+# Third-party modules
+
+# LLDB modules
+from .lldbtest import *
+
+class Stopwatch(object):
+ """Stopwatch provides a simple utility to start/stop your stopwatch multiple
+ times. Each start/stop is equal to a lap, with its elapsed time accumulated
+ while measurment is in progress.
+
+ When you're ready to start from scratch for another round of measurements,
+ be sure to call the reset() method.
+
+ For example,
+
+ sw = Stopwatch()
+ for i in range(1000):
+ with sw:
+ # Do some length operations...
+ ...
+ # Get the average time.
+ avg_time = sw.avg()
+
+ # Reset the stopwatch as we are about to perform other kind of operations.
+ sw.reset()
+ ...
+ """
+
+ #############################################################
+ #
+ # Context manager interfaces to support the 'with' statement.
+ #
+ #############################################################
+
+ def __enter__(self):
+ """
+ Context management protocol on entry to the body of the with statement.
+ """
+ return self.start()
+
+ def __exit__(self, type, value, tb):
+ """
+ Context management protocol on exit from the body of the with statement.
+ """
+ self.stop()
+
+ def reset(self):
+ self.__laps__ = 0
+ self.__total_elapsed__ = 0.0
+ self.__start__ = None
+ self.__stop__ = None
+ self.__elapsed__ = 0.0
+ self.__nums__ = []
+
+ def __init__(self):
+ self.reset()
+
+ def start(self):
+ if self.__start__ is None:
+ self.__start__ = time.time()
+ else:
+ raise Exception("start() already called, did you forget to stop() first?")
+ # Return self to facilitate the context manager __enter__ protocol.
+ return self
+
+ def stop(self):
+ if self.__start__ is not None:
+ self.__stop__ = time.time()
+ elapsed = self.__stop__ - self.__start__
+ self.__total_elapsed__ += elapsed
+ self.__laps__ += 1
+ self.__nums__.append(elapsed)
+ self.__start__ = None # Reset __start__ to be None again.
+ else:
+ raise Exception("stop() called without first start()?")
+
+ def laps(self):
+ """Gets the number of laps. One lap is equal to a start/stop action."""
+ return self.__laps__
+
+ def avg(self):
+ """Equal to total elapsed time divided by the number of laps."""
+ return self.__total_elapsed__ / self.__laps__
+
+ #def sigma(self):
+ # """Return the standard deviation of the available samples."""
+ # if self.__laps__ <= 0:
+ # return None
+ # return numpy.std(self.__nums__)
+
+ def __str__(self):
+ return "Avg: %f (Laps: %d, Total Elapsed Time: %f, min=%f, max=%f)" % (self.avg(),
+ self.__laps__,
+ self.__total_elapsed__,
+ min(self.__nums__),
+ max(self.__nums__))
+
+class BenchBase(TestBase):
+ """
+ Abstract base class for benchmark tests.
+ """
+ def setUp(self):
+ """Fixture for unittest test case setup."""
+ super(BenchBase, self).setUp()
+ #TestBase.setUp(self)
+ self.stopwatch = Stopwatch()
+
+ def tearDown(self):
+ """Fixture for unittest test case teardown."""
+ super(BenchBase, self).tearDown()
+ #TestBase.tearDown(self)
+ del self.stopwatch
+
diff --git a/packages/Python/lldbsuite/test/lldbcurses.py b/packages/Python/lldbsuite/test/lldbcurses.py
new file mode 100644
index 000000000000..bc1fbf00d372
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lldbcurses.py
@@ -0,0 +1,1143 @@
+from __future__ import absolute_import
+
+# System modules
+import curses
+import curses.panel
+import sys
+import time
+
+# Third-party modules
+import six
+
+# LLDB modules
+
+class Point(object):
+ def __init__(self, x, y):
+ self.x = x
+ self.y = y
+
+ def __repr__(self):
+ return str(self)
+
+ def __str__(self):
+ return "(x=%u, y=%u)" % (self.x, self.y)
+
+ def __eq__(self, rhs):
+ return self.x == rhs.x and self.y == rhs.y
+
+ def __ne__(self, rhs):
+ return self.x != rhs.x or self.y != rhs.y
+
+ def is_valid_coordinate(self):
+ return self.x >= 0 and self.y >= 0
+
+class Size(object):
+ def __init__(self, w, h):
+ self.w = w
+ self.h = h
+
+ def __repr__(self):
+ return str(self)
+
+ def __str__(self):
+ return "(w=%u, h=%u)" % (self.w, self.h)
+
+ def __eq__(self, rhs):
+ return self.w == rhs.w and self.h == rhs.h
+
+ def __ne__(self, rhs):
+ return self.w != rhs.w or self.h != rhs.h
+
+class Rect(object):
+ def __init__(self, x=0, y=0, w=0, h=0):
+ self.origin = Point(x, y)
+ self.size = Size(w, h)
+
+ def __repr__(self):
+ return str(self)
+
+ def __str__(self):
+ return "{ %s, %s }" % (str(self.origin), str(self.size))
+
+ def get_min_x(self):
+ return self.origin.x
+
+ def get_max_x(self):
+ return self.origin.x + self.size.w
+
+ def get_min_y(self):
+ return self.origin.y
+
+ def get_max_y(self):
+ return self.origin.y + self.size.h
+
+ def contains_point(self, pt):
+ if pt.x < self.get_max_x():
+ if pt.y < self.get_max_y():
+ if pt.x >= self.get_min_y():
+ return pt.y >= self.get_min_y()
+ return False
+
+ def __eq__(self, rhs):
+ return self.origin == rhs.origin and self.size == rhs.size
+
+ def __ne__(self, rhs):
+ return self.origin != rhs.origin or self.size != rhs.size
+
+class QuitException(Exception):
+ def __init__(self):
+ super(QuitException, self).__init__('QuitException')
+
+class Window(object):
+ def __init__(self, window, delegate = None, can_become_first_responder = True):
+ self.window = window
+ self.parent = None
+ self.delegate = delegate
+ self.children = list()
+ self.first_responders = list()
+ self.can_become_first_responder = can_become_first_responder
+ self.key_actions = dict()
+
+ def add_child(self, window):
+ self.children.append(window)
+ window.parent = self
+
+ def resize(self, size):
+ self.window.resize(size.h, size.w)
+
+ def resize_child(self, child, delta_size, adjust_neighbors):
+ if child in self.children:
+ frame = self.get_frame()
+ orig_frame = child.get_frame()
+ new_frame = Rect(x=orig_frame.origin.x, y=orig_frame.origin.y, w=orig_frame.size.w + delta_size.w, h=orig_frame.size.h + delta_size.h)
+ old_child_max_x = orig_frame.get_max_x()
+ new_child_max_x = new_frame.get_max_x()
+ window_max_x = frame.get_max_x()
+ if new_child_max_x < window_max_x:
+ child.resize(new_frame.size)
+ if old_child_max_x == window_max_x:
+ new_frame.origin.x += window_max_x - new_child_max_x
+ child.set_position(new_frame.origin)
+ elif new_child_max_x > window_max_x:
+ new_frame.origin.x -= new_child_max_x - window_max_x
+ child.set_position(new_frame.origin)
+ child.resize(new_frame.size)
+
+ if adjust_neighbors:
+ #print('orig_frame = %s\r\n' % (str(orig_frame)), end='')
+ for curr_child in self.children:
+ if curr_child is child:
+ continue
+ curr_child_frame = curr_child.get_frame()
+ if delta_size.w != 0:
+ #print('curr_child_frame = %s\r\n' % (str(curr_child_frame)), end='')
+ if curr_child_frame.get_min_x() == orig_frame.get_max_x():
+ curr_child_frame.origin.x += delta_size.w
+ curr_child_frame.size.w -= delta_size.w
+ #print('adjusted curr_child_frame = %s\r\n' % (str(curr_child_frame)), end='')
+ curr_child.resize (curr_child_frame.size)
+ curr_child.slide_position (Size(w=delta_size.w, h=0))
+ elif curr_child_frame.get_max_x() == orig_frame.get_min_x():
+ curr_child_frame.size.w -= delta_size.w
+ #print('adjusted curr_child_frame = %s\r\n' % (str(curr_child_frame)), end='')
+ curr_child.resize (curr_child_frame.size)
+
+ def add_key_action(self, arg, callback, decription):
+ if isinstance(arg, list):
+ for key in arg:
+ self.add_key_action(key, callback, description)
+ else:
+ if isinstance(arg, six.integer_types):
+ key_action_dict = { 'key' : arg,
+ 'callback' : callback,
+ 'description' : decription }
+ self.key_actions[arg] = key_action_dict
+ elif isinstance(arg, basestring):
+ key_integer = ord(arg)
+ key_action_dict = { 'key' : key_integer,
+ 'callback' : callback,
+ 'description' : decription }
+ self.key_actions[key_integer] = key_action_dict
+ else:
+ raise ValueError
+
+ def draw_title_box(self, title):
+ is_in_first_responder_chain = self.is_in_first_responder_chain()
+ if is_in_first_responder_chain:
+ self.attron (curses.A_REVERSE)
+ self.box()
+ if is_in_first_responder_chain:
+ self.attroff (curses.A_REVERSE)
+ if title:
+ self.addstr(Point(x=2, y=0), ' ' + title + ' ')
+
+ def remove_child(self, window):
+ self.children.remove(window)
+
+ def get_first_responder(self):
+ if len(self.first_responders):
+ return self.first_responders[-1]
+ else:
+ return None
+
+ def set_first_responder(self, window):
+ if window.can_become_first_responder:
+ if six.callable(getattr(window, "hidden", None)) and window.hidden():
+ return False
+ if not window in self.children:
+ self.add_child(window)
+ # See if we have a current first responder, and if we do, let it know that
+ # it will be resigning as first responder
+ first_responder = self.get_first_responder()
+ if first_responder:
+ first_responder.relinquish_first_responder()
+ # Now set the first responder to "window"
+ if len(self.first_responders) == 0:
+ self.first_responders.append(window)
+ else:
+ self.first_responders[-1] = window
+ return True
+ else:
+ return False
+
+ def push_first_responder(self, window):
+ # Only push the window as the new first responder if the window isn't already the first responder
+ if window != self.get_first_responder():
+ self.first_responders.append(window)
+
+ def pop_first_responder(self, window):
+ # Only pop the window from the first responder list if it is the first responder
+ if window == self.get_first_responder():
+ old_first_responder = self.first_responders.pop()
+ old_first_responder.relinquish_first_responder()
+ return True
+ else:
+ return False
+
+ def relinquish_first_responder(self):
+ '''Override if there is something that you need to do when you lose first responder status.'''
+ pass
+
+ # def resign_first_responder(self, remove_from_parent, new_first_responder):
+ # success = False
+ # if self.parent:
+ # if self.is_first_responder():
+ # self.relinquish_first_responder()
+ # if len(self.parent.first_responder):
+ # self.parent.first_responder = None
+ # success = True
+ # if remove_from_parent:
+ # self.parent.remove_child(self)
+ # if new_first_responder:
+ # self.parent.set_first_responder(new_first_responder)
+ # else:
+ # self.parent.select_next_first_responder()
+ # return success
+
+ def is_first_responder(self):
+ if self.parent:
+ return self.parent.get_first_responder() == self
+ else:
+ return False
+
+ def is_in_first_responder_chain(self):
+ if self.parent:
+ return self in self.parent.first_responders
+ else:
+ return False
+
+ def select_next_first_responder(self):
+ if len(self.first_responders) > 1:
+ self.pop_first_responder(self.first_responders[-1])
+ else:
+ num_children = len(self.children)
+ if num_children == 1:
+ return self.set_first_responder(self.children[0])
+ for (i,window) in enumerate(self.children):
+ if window.is_first_responder():
+ break
+ if i < num_children:
+ for i in range(i+1,num_children):
+ if self.set_first_responder(self.children[i]):
+ return True
+ for i in range(0, i):
+ if self.set_first_responder(self.children[i]):
+ return True
+
+ def point_in_window(self, pt):
+ size = self.get_size()
+ return pt.x >= 0 and pt.x < size.w and pt.y >= 0 and pt.y < size.h
+
+ def addch(self, c):
+ try:
+ self.window.addch(c)
+ except:
+ pass
+
+ def addch_at_point(self, pt, c):
+ try:
+ self.window.addch(pt.y, pt.x, c)
+ except:
+ pass
+
+ def addstr(self, pt, str):
+ try:
+ self.window.addstr(pt.y, pt.x, str)
+ except:
+ pass
+
+ def addnstr_at_point(self, pt, str, n):
+ try:
+ self.window.addnstr(pt.y, pt.x, str, n)
+ except:
+ pass
+ def addnstr(self, str, n):
+ try:
+ self.window.addnstr(str, n)
+ except:
+ pass
+
+ def attron(self, attr):
+ return self.window.attron (attr)
+
+ def attroff(self, attr):
+ return self.window.attroff (attr)
+
+ def box(self, vertch=0, horch=0):
+ if vertch == 0:
+ vertch = curses.ACS_VLINE
+ if horch == 0:
+ horch = curses.ACS_HLINE
+ self.window.box(vertch, horch)
+
+ def get_contained_rect(self, top_inset=0, bottom_inset=0, left_inset=0, right_inset=0, height=-1, width=-1):
+ '''Get a rectangle based on the top "height" lines of this window'''
+ rect = self.get_frame()
+ x = rect.origin.x + left_inset
+ y = rect.origin.y + top_inset
+ if height == -1:
+ h = rect.size.h - (top_inset + bottom_inset)
+ else:
+ h = height
+ if width == -1:
+ w = rect.size.w - (left_inset + right_inset)
+ else:
+ w = width
+ return Rect (x = x, y = y, w = w, h = h)
+
+ def erase(self):
+ self.window.erase()
+
+ def get_cursor(self):
+ (y, x) = self.window.getyx()
+ return Point(x=x, y=y)
+
+ def get_frame(self):
+ position = self.get_position()
+ size = self.get_size()
+ return Rect(x=position.x, y=position.y, w=size.w, h=size.h)
+
+ def get_frame_in_parent(self):
+ position = self.get_position_in_parent()
+ size = self.get_size()
+ return Rect(x=position.x, y=position.y, w=size.w, h=size.h)
+
+ def get_position_in_parent(self):
+ (y, x) = self.window.getparyx()
+ return Point(x, y)
+
+ def get_position(self):
+ (y, x) = self.window.getbegyx()
+ return Point(x, y)
+
+ def get_size(self):
+ (y, x) = self.window.getmaxyx()
+ return Size(w=x, h=y)
+
+ def move(self, pt):
+ self.window.move(pt.y, pt.x)
+
+ def refresh(self):
+ self.update()
+ curses.panel.update_panels()
+ self.move(Point(x=0, y=0))
+ return self.window.refresh()
+
+ def resize(self, size):
+ return self.window.resize(size.h, size.w)
+
+ def timeout(self, timeout_msec):
+ return self.window.timeout(timeout_msec)
+
+ def handle_key(self, key, check_parent=True):
+ '''Handle a key press in this window.'''
+
+ # First try the first responder if this window has one, but don't allow
+ # it to check with its parent (False second parameter) so we don't recurse
+ # and get a stack overflow
+ for first_responder in reversed(self.first_responders):
+ if first_responder.handle_key(key, False):
+ return True
+
+ # Check our key map to see if we have any actions. Actions don't take
+ # any arguments, they must be callable
+ if key in self.key_actions:
+ key_action = self.key_actions[key]
+ key_action['callback']()
+ return True
+ # Check if there is a wildcard key for any key
+ if -1 in self.key_actions:
+ key_action = self.key_actions[-1]
+ key_action['callback']()
+ return True
+ # Check if the window delegate wants to handle this key press
+ if self.delegate:
+ if six.callable(getattr(self.delegate, "handle_key", None)):
+ if self.delegate.handle_key(self, key):
+ return True
+ if self.delegate(self, key):
+ return True
+ # Check if we have a parent window and if so, let the parent
+ # window handle the key press
+ if check_parent and self.parent:
+ return self.parent.handle_key(key, True)
+ else:
+ return False # Key not handled
+
+ def update(self):
+ for child in self.children:
+ child.update()
+
+ def quit_action(self):
+ raise QuitException
+
+ def get_key(self, timeout_msec=-1):
+ self.timeout(timeout_msec)
+ done = False
+ c = self.window.getch()
+ if c == 27:
+ self.timeout(0)
+ escape_key = 0
+ while True:
+ escape_key = self.window.getch()
+ if escape_key == -1:
+ break
+ else:
+ c = c << 8 | escape_key
+ self.timeout(timeout_msec)
+ return c
+
+ def key_event_loop(self, timeout_msec=-1, n=sys.maxsize):
+ '''Run an event loop to receive key presses and pass them along to the
+ responder chain.
+
+ timeout_msec is the timeout it milliseconds. If the value is -1, an
+ infinite wait will be used. It the value is zero, a non-blocking mode
+ will be used, and if greater than zero it will wait for a key press
+ for timeout_msec milliseconds.
+
+ n is the number of times to go through the event loop before exiting'''
+ done = False
+ while not done and n > 0:
+ c = self.get_key(timeout_msec)
+ if c != -1:
+ try:
+ self.handle_key(c)
+ except QuitException:
+ done = True
+ n -= 1
+
+class Panel(Window):
+ def __init__(self, frame, delegate = None, can_become_first_responder = True):
+ window = curses.newwin(frame.size.h,frame.size.w, frame.origin.y, frame.origin.x)
+ super(Panel, self).__init__(window, delegate, can_become_first_responder)
+ self.panel = curses.panel.new_panel(window)
+
+ def hide(self):
+ return self.panel.hide()
+
+ def hidden(self):
+ return self.panel.hidden()
+
+ def show(self):
+ return self.panel.show()
+
+ def top(self):
+ return self.panel.top()
+
+ def set_position(self, pt):
+ self.panel.move(pt.y, pt.x)
+
+ def slide_position(self, size):
+ new_position = self.get_position()
+ new_position.x = new_position.x + size.w
+ new_position.y = new_position.y + size.h
+ self.set_position(new_position)
+
+class BoxedPanel(Panel):
+ def __init__(self, frame, title, delegate = None, can_become_first_responder = True):
+ super(BoxedPanel, self).__init__(frame, delegate, can_become_first_responder)
+ self.title = title
+ self.lines = list()
+ self.first_visible_idx = 0
+ self.selected_idx = -1
+ self.add_key_action(curses.KEY_UP, self.select_prev, "Select the previous item")
+ self.add_key_action(curses.KEY_DOWN, self.select_next, "Select the next item")
+ self.add_key_action(curses.KEY_HOME, self.scroll_begin, "Go to the beginning of the list")
+ self.add_key_action(curses.KEY_END, self.scroll_end, "Go to the end of the list")
+ self.add_key_action(0x1b4f48, self.scroll_begin, "Go to the beginning of the list")
+ self.add_key_action(0x1b4f46, self.scroll_end, "Go to the end of the list")
+ self.add_key_action(curses.KEY_PPAGE, self.scroll_page_backward, "Scroll to previous page")
+ self.add_key_action(curses.KEY_NPAGE, self.scroll_page_forward, "Scroll to next forward")
+ self.update()
+
+ def clear(self, update=True):
+ self.lines = list()
+ self.first_visible_idx = 0
+ self.selected_idx = -1
+ if update:
+ self.update()
+
+ def get_usable_width(self):
+ '''Valid usable width is 0 to (width - 3) since the left and right lines display the box around
+ this frame and we skip a leading space'''
+ w = self.get_size().w
+ if w > 3:
+ return w-3
+ else:
+ return 0
+
+ def get_usable_height(self):
+ '''Valid line indexes are 0 to (height - 2) since the top and bottom lines display the box around this frame.'''
+ h = self.get_size().h
+ if h > 2:
+ return h-2
+ else:
+ return 0
+
+ def get_point_for_line(self, global_line_idx):
+ '''Returns the point to use when displaying a line whose index is "line_idx"'''
+ line_idx = global_line_idx - self.first_visible_idx
+ num_lines = self.get_usable_height()
+ if line_idx < num_lines:
+ return Point(x=2, y=1+line_idx)
+ else:
+ return Point(x=-1, y=-1) # return an invalid coordinate if the line index isn't valid
+
+ def set_title (self, title, update=True):
+ self.title = title
+ if update:
+ self.update()
+
+ def scroll_to_line (self, idx):
+ if idx < len(self.lines):
+ self.selected_idx = idx
+ max_visible_lines = self.get_usable_height()
+ if idx < self.first_visible_idx or idx >= self.first_visible_idx + max_visible_lines:
+ self.first_visible_idx = idx
+ self.refresh()
+
+ def scroll_begin (self):
+ self.first_visible_idx = 0
+ if len(self.lines) > 0:
+ self.selected_idx = 0
+ else:
+ self.selected_idx = -1
+ self.update()
+
+ def scroll_end (self):
+ max_visible_lines = self.get_usable_height()
+ num_lines = len(self.lines)
+ if num_lines > max_visible_lines:
+ self.first_visible_idx = num_lines - max_visible_lines
+ else:
+ self.first_visible_idx = 0
+ self.selected_idx = num_lines-1
+ self.update()
+
+ def scroll_page_backward(self):
+ num_lines = len(self.lines)
+ max_visible_lines = self.get_usable_height()
+ new_index = self.first_visible_idx - max_visible_lines
+ if new_index < 0:
+ self.first_visible_idx = 0
+ else:
+ self.first_visible_idx = new_index
+ self.refresh()
+
+ def scroll_page_forward(self):
+ max_visible_lines = self.get_usable_height()
+ self.first_visible_idx += max_visible_lines
+ self._adjust_first_visible_line()
+ self.refresh()
+
+ def select_next (self):
+ self.selected_idx += 1
+ if self.selected_idx >= len(self.lines):
+ self.selected_idx = len(self.lines) - 1
+ self.refresh()
+
+ def select_prev (self):
+ self.selected_idx -= 1
+ if self.selected_idx < 0:
+ if len(self.lines) > 0:
+ self.selected_idx = 0
+ else:
+ self.selected_idx = -1
+ self.refresh()
+
+ def get_selected_idx(self):
+ return self.selected_idx
+
+ def _adjust_first_visible_line(self):
+ num_lines = len(self.lines)
+ max_visible_lines = self.get_usable_height()
+ if (self.first_visible_idx >= num_lines) or (num_lines - self.first_visible_idx) > max_visible_lines:
+ self.first_visible_idx = num_lines - max_visible_lines
+
+ def append_line(self, s, update=True):
+ self.lines.append(s)
+ self._adjust_first_visible_line()
+ if update:
+ self.update()
+
+ def set_line(self, line_idx, s, update=True):
+ '''Sets a line "line_idx" within the boxed panel to be "s"'''
+ if line_idx < 0:
+ return
+ while line_idx >= len(self.lines):
+ self.lines.append('')
+ self.lines[line_idx] = s
+ self._adjust_first_visible_line()
+ if update:
+ self.update()
+
+ def update(self):
+ self.erase()
+ self.draw_title_box(self.title)
+ max_width = self.get_usable_width()
+ for line_idx in range(self.first_visible_idx, len(self.lines)):
+ pt = self.get_point_for_line(line_idx)
+ if pt.is_valid_coordinate():
+ is_selected = line_idx == self.selected_idx
+ if is_selected:
+ self.attron (curses.A_REVERSE)
+ self.move(pt)
+ self.addnstr(self.lines[line_idx], max_width)
+ if is_selected:
+ self.attroff (curses.A_REVERSE)
+ else:
+ return
+
+ def load_file(self, path):
+ f = open(path)
+ if f:
+ self.lines = f.read().splitlines()
+ for (idx, line) in enumerate(self.lines):
+ # Remove any tabs from lines since they hose up the display
+ if "\t" in line:
+ self.lines[idx] = (8*' ').join(line.split('\t'))
+ self.selected_idx = 0
+ self.first_visible_idx = 0
+ self.refresh()
+
+class Item(object):
+ def __init__(self, title, action):
+ self.title = title
+ self.action = action
+
+class TreeItemDelegate(object):
+
+ def might_have_children(self):
+ return False
+
+ def update_children(self, item):
+ '''Return a list of child Item objects'''
+ return None
+
+ def draw_item_string(self, tree_window, item, s):
+ pt = tree_window.get_cursor()
+ width = tree_window.get_size().w - 1
+ if width > pt.x:
+ tree_window.addnstr(s, width - pt.x)
+
+ def draw_item(self, tree_window, item):
+ self.draw_item_string(tree_window, item, item.title)
+
+ def do_action(self):
+ pass
+
+class TreeItem(object):
+ def __init__(self, delegate, parent = None, title = None, action = None, is_expanded = False):
+ self.parent = parent
+ self.title = title
+ self.action = action
+ self.delegate = delegate
+ self.is_expanded = not parent or is_expanded == True
+ self._might_have_children = None
+ self.children = None
+ self._children_might_have_children = False
+
+ def get_children(self):
+ if self.is_expanded and self.might_have_children():
+ if self.children is None:
+ self._children_might_have_children = False
+ self.children = self.update_children()
+ for child in self.children:
+ if child.might_have_children():
+ self._children_might_have_children = True
+ break
+ else:
+ self._children_might_have_children = False
+ self.children = None
+ return self.children
+
+ def append_visible_items(self, items):
+ items.append(self)
+ children = self.get_children()
+ if children:
+ for child in children:
+ child.append_visible_items(items)
+
+ def might_have_children(self):
+ if self._might_have_children is None:
+ if not self.parent:
+ # Root item always might have children
+ self._might_have_children = True
+ else:
+ # Check with the delegate to see if the item might have children
+ self._might_have_children = self.delegate.might_have_children()
+ return self._might_have_children
+
+ def children_might_have_children(self):
+ return self._children_might_have_children
+
+ def update_children(self):
+ if self.is_expanded and self.might_have_children():
+ self.children = self.delegate.update_children(self)
+ for child in self.children:
+ child.update_children()
+ else:
+ self.children = None
+ return self.children
+
+ def get_num_visible_rows(self):
+ rows = 1
+ if self.is_expanded:
+ children = self.get_children()
+ if children:
+ for child in children:
+ rows += child.get_num_visible_rows()
+ return rows
+ def draw(self, tree_window, row):
+ display_row = tree_window.get_display_row(row)
+ if display_row >= 0:
+ tree_window.move(tree_window.get_item_draw_point(row))
+ if self.parent:
+ self.parent.draw_tree_for_child(tree_window, self, 0)
+ if self.might_have_children():
+ tree_window.addch (curses.ACS_DIAMOND)
+ tree_window.addch (curses.ACS_HLINE)
+ elif self.parent and self.parent.children_might_have_children():
+ if self.parent.parent:
+ tree_window.addch (curses.ACS_HLINE)
+ tree_window.addch (curses.ACS_HLINE)
+ else:
+ tree_window.addch (' ')
+ tree_window.addch (' ')
+ is_selected = tree_window.is_selected(row)
+ if is_selected:
+ tree_window.attron (curses.A_REVERSE)
+ self.delegate.draw_item(tree_window, self)
+ if is_selected:
+ tree_window.attroff (curses.A_REVERSE)
+
+ def draw_tree_for_child (self, tree_window, child, reverse_depth):
+ if self.parent:
+ self.parent.draw_tree_for_child (tree_window, self, reverse_depth + 1)
+ if self.children[-1] == child:
+ # Last child
+ if reverse_depth == 0:
+ tree_window.addch (curses.ACS_LLCORNER)
+ tree_window.addch (curses.ACS_HLINE)
+ else:
+ tree_window.addch (' ')
+ tree_window.addch (' ')
+ else:
+ # Middle child
+ if reverse_depth == 0:
+ tree_window.addch (curses.ACS_LTEE)
+ tree_window.addch (curses.ACS_HLINE)
+ else:
+ tree_window.addch (curses.ACS_VLINE)
+ tree_window.addch (' ')
+
+ def was_selected(self):
+ self.delegate.do_action()
+
+class TreePanel(Panel):
+ def __init__(self, frame, title, root_item):
+ self.root_item = root_item
+ self.title = title
+ self.first_visible_idx = 0
+ self.selected_idx = 0
+ self.items = None
+ super(TreePanel, self).__init__(frame)
+ self.add_key_action(curses.KEY_UP, self.select_prev, "Select the previous item")
+ self.add_key_action(curses.KEY_DOWN, self.select_next, "Select the next item")
+ self.add_key_action(curses.KEY_RIGHT,self.right_arrow, "Expand an item")
+ self.add_key_action(curses.KEY_LEFT, self.left_arrow, "Unexpand an item or navigate to parent")
+ self.add_key_action(curses.KEY_HOME, self.scroll_begin, "Go to the beginning of the tree")
+ self.add_key_action(curses.KEY_END, self.scroll_end, "Go to the end of the tree")
+ self.add_key_action(0x1b4f48, self.scroll_begin, "Go to the beginning of the tree")
+ self.add_key_action(0x1b4f46, self.scroll_end, "Go to the end of the tree")
+ self.add_key_action(curses.KEY_PPAGE, self.scroll_page_backward, "Scroll to previous page")
+ self.add_key_action(curses.KEY_NPAGE, self.scroll_page_forward, "Scroll to next forward")
+
+ def get_selected_item(self):
+ if self.selected_idx < len(self.items):
+ return self.items[self.selected_idx]
+ else:
+ return None
+
+ def select_item(self, item):
+ if self.items and item in self.items:
+ self.selected_idx = self.items.index(item)
+ return True
+ else:
+ return False
+
+ def get_visible_items(self):
+ # Clear self.items when you want to update all chidren
+ if self.items is None:
+ self.items = list()
+ children = self.root_item.get_children()
+ if children:
+ for child in children:
+ child.append_visible_items(self.items)
+ return self.items
+
+ def update(self):
+ self.erase()
+ self.draw_title_box(self.title)
+ visible_items = self.get_visible_items()
+ for (row, child) in enumerate(visible_items):
+ child.draw(self, row)
+
+ def get_item_draw_point(self, row):
+ display_row = self.get_display_row(row)
+ if display_row >= 0:
+ return Point(2, display_row + 1)
+ else:
+ return Point(-1, -1)
+
+ def get_display_row(self, row):
+ if row >= self.first_visible_idx:
+ display_row = row - self.first_visible_idx
+ if display_row < self.get_size().h-2:
+ return display_row
+ return -1
+
+ def is_selected(self, row):
+ return row == self.selected_idx
+
+ def get_num_lines(self):
+ self.get_visible_items()
+ return len(self.items)
+
+ def get_num_visible_lines(self):
+ return self.get_size().h-2
+ def select_next (self):
+ self.selected_idx += 1
+ num_lines = self.get_num_lines()
+ if self.selected_idx >= num_lines:
+ self.selected_idx = num_lines - 1
+ self._selection_changed()
+ self.refresh()
+
+ def select_prev (self):
+ self.selected_idx -= 1
+ if self.selected_idx < 0:
+ num_lines = self.get_num_lines()
+ if num_lines > 0:
+ self.selected_idx = 0
+ else:
+ self.selected_idx = -1
+ self._selection_changed()
+ self.refresh()
+
+ def scroll_begin (self):
+ self.first_visible_idx = 0
+ num_lines = self.get_num_lines()
+ if num_lines > 0:
+ self.selected_idx = 0
+ else:
+ self.selected_idx = -1
+ self.refresh()
+
+ def redisplay_tree(self):
+ self.items = None
+ self.refresh()
+
+ def right_arrow(self):
+ selected_item = self.get_selected_item()
+ if selected_item and selected_item.is_expanded == False:
+ selected_item.is_expanded = True
+ self.redisplay_tree()
+
+ def left_arrow(self):
+ selected_item = self.get_selected_item()
+ if selected_item:
+ if selected_item.is_expanded == True:
+ selected_item.is_expanded = False
+ self.redisplay_tree()
+ elif selected_item.parent:
+ if self.select_item(selected_item.parent):
+ self.refresh()
+
+
+ def scroll_end (self):
+ num_visible_lines = self.get_num_visible_lines()
+ num_lines = self.get_num_lines()
+ if num_lines > num_visible_lines:
+ self.first_visible_idx = num_lines - num_visible_lines
+ else:
+ self.first_visible_idx = 0
+ self.selected_idx = num_lines-1
+ self.refresh()
+
+ def scroll_page_backward(self):
+ num_visible_lines = self.get_num_visible_lines()
+ new_index = self.selected_idx - num_visible_lines
+ if new_index < 0:
+ self.selected_idx = 0
+ else:
+ self.selected_idx = new_index
+ self._selection_changed()
+ self.refresh()
+
+ def scroll_page_forward(self):
+ num_lines = self.get_num_lines()
+ num_visible_lines = self.get_num_visible_lines()
+ new_index = self.selected_idx + num_visible_lines
+ if new_index >= num_lines:
+ new_index = num_lines - 1
+ self.selected_idx = new_index
+ self._selection_changed()
+ self.refresh()
+
+ def _selection_changed(self):
+ num_lines = self.get_num_lines()
+ num_visible_lines = self.get_num_visible_lines()
+ last_visible_index = self.first_visible_idx + num_visible_lines
+ if self.selected_idx >= last_visible_index:
+ self.first_visible_idx += (self.selected_idx - last_visible_index + 1)
+ if self.selected_idx < self.first_visible_idx:
+ self.first_visible_idx = self.selected_idx
+ if self.selected_idx >= 0 and self.selected_idx < len(self.items):
+ item = self.items[self.selected_idx]
+ item.was_selected()
+
+
+class Menu(BoxedPanel):
+ def __init__(self, title, items):
+ max_title_width = 0
+ for item in items:
+ if max_title_width < len(item.title):
+ max_title_width = len(item.title)
+ frame = Rect(x=0, y=0, w=max_title_width+4, h=len(items)+2)
+ super(Menu, self).__init__(frame, title=None, delegate=None, can_become_first_responder=True)
+ self.selected_idx = 0
+ self.title = title
+ self.items = items
+ for (item_idx, item) in enumerate(items):
+ self.set_line(item_idx, item.title)
+ self.hide()
+
+ def update(self):
+ super(Menu, self).update()
+
+ def relinquish_first_responder(self):
+ if not self.hidden():
+ self.hide()
+
+ def perform_action(self):
+ selected_idx = self.get_selected_idx()
+ if selected_idx < len(self.items):
+ action = self.items[selected_idx].action
+ if action:
+ action()
+
+class MenuBar(Panel):
+ def __init__(self, frame):
+ super(MenuBar, self).__init__(frame, can_become_first_responder=True)
+ self.menus = list()
+ self.selected_menu_idx = -1
+ self.add_key_action(curses.KEY_LEFT, self.select_prev, "Select the previous menu")
+ self.add_key_action(curses.KEY_RIGHT, self.select_next, "Select the next menu")
+ self.add_key_action(curses.KEY_DOWN, lambda: self.select(0), "Select the first menu")
+ self.add_key_action(27, self.relinquish_first_responder, "Hide current menu")
+ self.add_key_action(curses.KEY_ENTER, self.perform_action, "Select the next menu item")
+ self.add_key_action(10, self.perform_action, "Select the next menu item")
+
+ def insert_menu(self, menu, index=sys.maxsize):
+ if index >= len(self.menus):
+ self.menus.append(menu)
+ else:
+ self.menus.insert(index, menu)
+ pt = self.get_position()
+ for menu in self.menus:
+ menu.set_position(pt)
+ pt.x += len(menu.title) + 5
+
+ def perform_action(self):
+ '''If no menu is visible, show the first menu. If a menu is visible, perform the action
+ associated with the selected menu item in the menu'''
+ menu_visible = False
+ for menu in self.menus:
+ if not menu.hidden():
+ menu_visible = True
+ break
+ if menu_visible:
+ menu.perform_action()
+ self.selected_menu_idx = -1
+ self._selected_menu_changed()
+ else:
+ self.select(0)
+
+ def relinquish_first_responder(self):
+ if self.selected_menu_idx >= 0:
+ self.selected_menu_idx = -1
+ self._selected_menu_changed()
+
+ def _selected_menu_changed(self):
+ for (menu_idx, menu) in enumerate(self.menus):
+ is_hidden = menu.hidden()
+ if menu_idx != self.selected_menu_idx:
+ if not is_hidden:
+ if self.parent.pop_first_responder(menu) == False:
+ menu.hide()
+ for (menu_idx, menu) in enumerate(self.menus):
+ is_hidden = menu.hidden()
+ if menu_idx == self.selected_menu_idx:
+ if is_hidden:
+ menu.show()
+ self.parent.push_first_responder(menu)
+ menu.top()
+ self.parent.refresh()
+
+ def select(self, index):
+ if index < len(self.menus):
+ self.selected_menu_idx = index
+ self._selected_menu_changed()
+
+ def select_next (self):
+ num_menus = len(self.menus)
+ if self.selected_menu_idx == -1:
+ if num_menus > 0:
+ self.selected_menu_idx = 0
+ self._selected_menu_changed()
+ else:
+ if self.selected_menu_idx + 1 < num_menus:
+ self.selected_menu_idx += 1
+ else:
+ self.selected_menu_idx = -1
+ self._selected_menu_changed()
+
+ def select_prev (self):
+ num_menus = len(self.menus)
+ if self.selected_menu_idx == -1:
+ if num_menus > 0:
+ self.selected_menu_idx = num_menus - 1
+ self._selected_menu_changed()
+ else:
+ if self.selected_menu_idx - 1 >= 0:
+ self.selected_menu_idx -= 1
+ else:
+ self.selected_menu_idx = -1
+ self._selected_menu_changed()
+
+ def update(self):
+ self.erase()
+ is_in_first_responder_chain = self.is_in_first_responder_chain()
+ if is_in_first_responder_chain:
+ self.attron (curses.A_REVERSE)
+ pt = Point(x=0, y=0)
+ for menu in self.menus:
+ self.addstr(pt, '| ' + menu.title + ' ')
+ pt.x += len(menu.title) + 5
+ self.addstr(pt, '|')
+ width = self.get_size().w
+ while pt.x < width:
+ self.addch_at_point(pt, ' ')
+ pt.x += 1
+ if is_in_first_responder_chain:
+ self.attroff (curses.A_REVERSE)
+
+ for menu in self.menus:
+ menu.update()
+
+
+class StatusPanel(Panel):
+ def __init__(self, frame):
+ super(StatusPanel, self).__init__(frame, delegate=None, can_become_first_responder=False)
+ self.status_items = list()
+ self.status_dicts = dict()
+ self.next_status_x = 1
+
+ def add_status_item(self, name, title, format, width, value, update=True):
+ status_item_dict = { 'name': name,
+ 'title' : title,
+ 'width' : width,
+ 'format' : format,
+ 'value' : value,
+ 'x' : self.next_status_x }
+ index = len(self.status_items)
+ self.status_items.append(status_item_dict)
+ self.status_dicts[name] = index
+ self.next_status_x += width + 2;
+ if update:
+ self.update()
+
+ def increment_status(self, name, update=True):
+ if name in self.status_dicts:
+ status_item_idx = self.status_dicts[name]
+ status_item_dict = self.status_items[status_item_idx]
+ status_item_dict['value'] = status_item_dict['value'] + 1
+ if update:
+ self.update()
+
+ def update_status(self, name, value, update=True):
+ if name in self.status_dicts:
+ status_item_idx = self.status_dicts[name]
+ status_item_dict = self.status_items[status_item_idx]
+ status_item_dict['value'] = status_item_dict['format'] % (value)
+ if update:
+ self.update()
+ def update(self):
+ self.erase();
+ for status_item_dict in self.status_items:
+ self.addnstr_at_point(Point(x=status_item_dict['x'], y=0), '%s: %s' % (status_item_dict['title'], status_item_dict['value']), status_item_dict['width'])
+
+stdscr = None
+
+def intialize_curses():
+ global stdscr
+ stdscr = curses.initscr()
+ curses.noecho()
+ curses.cbreak()
+ stdscr.keypad(1)
+ try:
+ curses.start_color()
+ except:
+ pass
+ return Window(stdscr)
+
+def terminate_curses():
+ global stdscr
+ if stdscr:
+ stdscr.keypad(0)
+ curses.echo()
+ curses.nocbreak()
+ curses.endwin()
+
diff --git a/packages/Python/lldbsuite/test/lldbinline.py b/packages/Python/lldbsuite/test/lldbinline.py
new file mode 100644
index 000000000000..691a3fba6dc2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lldbinline.py
@@ -0,0 +1,210 @@
+from __future__ import print_function
+from __future__ import absolute_import
+
+# System modules
+import os
+import sys
+
+# Third-party modules
+
+# LLDB modules
+import lldb
+from .lldbtest import *
+from . import lldbutil
+
+def source_type(filename):
+ _, extension = os.path.splitext(filename)
+ return {
+ '.c' : 'C_SOURCES',
+ '.cpp' : 'CXX_SOURCES',
+ '.cxx' : 'CXX_SOURCES',
+ '.cc' : 'CXX_SOURCES',
+ '.m' : 'OBJC_SOURCES',
+ '.mm' : 'OBJCXX_SOURCES'
+ }.get(extension, None)
+
+class CommandParser:
+ def __init__(self):
+ self.breakpoints = []
+
+ def parse_one_command(self, line):
+ parts = line.split('//%')
+
+ command = None
+ new_breakpoint = True
+
+ if len(parts) == 2:
+ command = parts[1].strip() # take off whitespace
+ new_breakpoint = parts[0].strip() != ""
+
+ return (command, new_breakpoint)
+
+ def parse_source_files(self, source_files):
+ for source_file in source_files:
+ file_handle = open(source_file)
+ lines = file_handle.readlines()
+ line_number = 0
+ current_breakpoint = None # non-NULL means we're looking through whitespace to find additional commands
+ for line in lines:
+ line_number = line_number + 1 # 1-based, so we do this first
+ (command, new_breakpoint) = self.parse_one_command(line)
+
+ if new_breakpoint:
+ current_breakpoint = None
+
+ if command != None:
+ if current_breakpoint == None:
+ current_breakpoint = {}
+ current_breakpoint['file_name'] = source_file
+ current_breakpoint['line_number'] = line_number
+ current_breakpoint['command'] = command
+ self.breakpoints.append(current_breakpoint)
+ else:
+ current_breakpoint['command'] = current_breakpoint['command'] + "\n" + command
+
+ def set_breakpoints(self, target):
+ for breakpoint in self.breakpoints:
+ breakpoint['breakpoint'] = target.BreakpointCreateByLocation(breakpoint['file_name'], breakpoint['line_number'])
+
+ def handle_breakpoint(self, test, breakpoint_id):
+ for breakpoint in self.breakpoints:
+ if breakpoint['breakpoint'].GetID() == breakpoint_id:
+ test.execute_user_command(breakpoint['command'])
+ return
+
+class InlineTest(TestBase):
+ # Internal implementation
+
+ def getRerunArgs(self):
+ # The -N option says to NOT run a if it matches the option argument, so
+ # if we are using dSYM we say to NOT run dwarf (-N dwarf) and vice versa.
+ if self.using_dsym is None:
+ # The test was skipped altogether.
+ return ""
+ elif self.using_dsym:
+ return "-N dwarf %s" % (self.mydir)
+ else:
+ return "-N dsym %s" % (self.mydir)
+
+ def BuildMakefile(self):
+ if os.path.exists("Makefile"):
+ return
+
+ categories = {}
+
+ for f in os.listdir(os.getcwd()):
+ t = source_type(f)
+ if t:
+ if t in list(categories.keys()):
+ categories[t].append(f)
+ else:
+ categories[t] = [f]
+
+ makefile = open("Makefile", 'w+')
+
+ level = os.sep.join([".."] * len(self.mydir.split(os.sep))) + os.sep + "make"
+
+ makefile.write("LEVEL = " + level + "\n")
+
+ for t in list(categories.keys()):
+ line = t + " := " + " ".join(categories[t])
+ makefile.write(line + "\n")
+
+ if ('OBJCXX_SOURCES' in list(categories.keys())) or ('OBJC_SOURCES' in list(categories.keys())):
+ makefile.write("LDFLAGS = $(CFLAGS) -lobjc -framework Foundation\n")
+
+ if ('CXX_SOURCES' in list(categories.keys())):
+ makefile.write("CXXFLAGS += -std=c++11\n")
+
+ makefile.write("include $(LEVEL)/Makefile.rules\n")
+ makefile.flush()
+ makefile.close()
+
+
+ @skipUnlessDarwin
+ def __test_with_dsym(self):
+ self.using_dsym = True
+ self.BuildMakefile()
+ self.buildDsym()
+ self.do_test()
+
+ def __test_with_dwarf(self):
+ self.using_dsym = False
+ self.BuildMakefile()
+ self.buildDwarf()
+ self.do_test()
+
+ def __test_with_dwo(self):
+ self.using_dsym = False
+ self.BuildMakefile()
+ self.buildDwo()
+ self.do_test()
+
+ def execute_user_command(self, __command):
+ exec(__command, globals(), locals())
+
+ def do_test(self):
+ exe_name = "a.out"
+ exe = os.path.join(os.getcwd(), exe_name)
+ source_files = [ f for f in os.listdir(os.getcwd()) if source_type(f) ]
+ target = self.dbg.CreateTarget(exe)
+
+ parser = CommandParser()
+ parser.parse_source_files(source_files)
+ parser.set_breakpoints(target)
+
+ process = target.LaunchSimple(None, None, os.getcwd())
+
+ while lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint):
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ breakpoint_id = thread.GetStopReasonDataAtIndex (0)
+ parser.handle_breakpoint(self, breakpoint_id)
+ process.Continue()
+
+
+ # Utilities for testcases
+
+ def check_expression (self, expression, expected_result, use_summary = True):
+ value = self.frame().EvaluateExpression (expression)
+ self.assertTrue(value.IsValid(), expression+"returned a valid value")
+ if self.TraceOn():
+ print(value.GetSummary())
+ print(value.GetValue())
+ if use_summary:
+ answer = value.GetSummary()
+ else:
+ answer = value.GetValue()
+ report_str = "%s expected: %s got: %s"%(expression, expected_result, answer)
+ self.assertTrue(answer == expected_result, report_str)
+
+def ApplyDecoratorsToFunction(func, decorators):
+ tmp = func
+ if type(decorators) == list:
+ for decorator in decorators:
+ tmp = decorator(tmp)
+ elif hasattr(decorators, '__call__'):
+ tmp = decorators(tmp)
+ return tmp
+
+
+def MakeInlineTest(__file, __globals, decorators=None):
+ # Derive the test name from the current file name
+ file_basename = os.path.basename(__file)
+ InlineTest.mydir = TestBase.compute_mydir(__file)
+
+ test_name, _ = os.path.splitext(file_basename)
+ # Build the test case
+ test = type(test_name, (InlineTest,), {'using_dsym': None})
+ test.name = test_name
+
+ test.test_with_dsym = ApplyDecoratorsToFunction(test._InlineTest__test_with_dsym, decorators)
+ test.test_with_dwarf = ApplyDecoratorsToFunction(test._InlineTest__test_with_dwarf, decorators)
+ test.test_with_dwo = ApplyDecoratorsToFunction(test._InlineTest__test_with_dwo, decorators)
+
+ # Add the test case to the globals, and hide InlineTest
+ __globals.update({test_name : test})
+
+ # Store the name of the originating file.o
+ test.test_filename = __file
+ return test
+
diff --git a/packages/Python/lldbsuite/test/lldbpexpect.py b/packages/Python/lldbsuite/test/lldbpexpect.py
new file mode 100644
index 000000000000..55b958a55972
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lldbpexpect.py
@@ -0,0 +1,63 @@
+from __future__ import print_function
+from __future__ import absolute_import
+
+# System modules
+import os
+import sys
+
+# Third-party modules
+import pexpect
+
+# LLDB Modules
+import lldb
+from .lldbtest import *
+from . import lldbutil
+
+class PExpectTest(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ TestBase.setUp(self)
+
+ def launchArgs(self):
+ pass
+
+ def launch(self, timeout=None):
+ if timeout is None: timeout = 30
+ logfile = sys.stdout if self.TraceOn() else None
+ self.child = pexpect.spawn('%s %s' % (lldbtest_config.lldbExec, self.launchArgs()), logfile=logfile)
+ self.child.timeout = timeout
+ self.timeout = timeout
+
+ def expect(self, patterns=None, timeout=None, exact=None):
+ if patterns is None: return None
+ if timeout is None: timeout = self.timeout
+ if exact is None: exact = False
+ if exact:
+ return self.child.expect_exact(patterns, timeout=timeout)
+ else:
+ return self.child.expect(patterns, timeout=timeout)
+
+ def expectall(self, patterns=None, timeout=None, exact=None):
+ if patterns is None: return None
+ if timeout is None: timeout = self.timeout
+ if exact is None: exact = False
+ for pattern in patterns:
+ self.expect(pattern, timeout=timeout, exact=exact)
+
+ def sendimpl(self, sender, command, patterns=None, timeout=None, exact=None):
+ sender(command)
+ return self.expect(patterns=patterns, timeout=timeout, exact=exact)
+
+ def send(self, command, patterns=None, timeout=None, exact=None):
+ return self.sendimpl(self.child.send, command, patterns, timeout, exact)
+
+ def sendline(self, command, patterns=None, timeout=None, exact=None):
+ return self.sendimpl(self.child.sendline, command, patterns, timeout, exact)
+
+ def quit(self, gracefully=None):
+ if gracefully is None: gracefully = True
+ self.child.sendeof()
+ self.child.close(force=not gracefully)
+ self.child = None
diff --git a/packages/Python/lldbsuite/test/lldbplatformutil.py b/packages/Python/lldbsuite/test/lldbplatformutil.py
new file mode 100644
index 000000000000..f51c016c13c2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lldbplatformutil.py
@@ -0,0 +1,27 @@
+""" This module contains functions used by the test cases to hide the
+architecture and/or the platform dependent nature of the tests. """
+
+from __future__ import absolute_import
+
+# System modules
+
+# Third-party modules
+
+# LLDB modules
+
+import re
+
+def check_first_register_readable(test_case):
+ arch = test_case.getArchitecture()
+
+ if arch in ['x86_64', 'i386']:
+ test_case.expect("register read eax", substrs = ['eax = 0x'])
+ elif arch in ['arm']:
+ test_case.expect("register read r0", substrs = ['r0 = 0x'])
+ elif arch in ['aarch64']:
+ test_case.expect("register read x0", substrs = ['x0 = 0x'])
+ elif re.match("mips",arch):
+ test_case.expect("register read zero", substrs = ['zero = 0x'])
+ else:
+ # TODO: Add check for other architectures
+ test_case.fail("Unsupported architecture for test case (arch: %s)" % test_case.getArchitecture())
diff --git a/packages/Python/lldbsuite/test/lldbtest.py b/packages/Python/lldbsuite/test/lldbtest.py
new file mode 100644
index 000000000000..43d02c521d18
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lldbtest.py
@@ -0,0 +1,2775 @@
+"""
+LLDB module which provides the abstract base class of lldb test case.
+
+The concrete subclass can override lldbtest.TesBase in order to inherit the
+common behavior for unitest.TestCase.setUp/tearDown implemented in this file.
+
+The subclass should override the attribute mydir in order for the python runtime
+to locate the individual test cases when running as part of a large test suite
+or when running each test case as a separate python invocation.
+
+./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
+$
+"""
+
+from __future__ import print_function
+from __future__ import absolute_import
+
+# System modules
+import abc
+import collections
+from distutils.version import LooseVersion
+import gc
+import glob
+import inspect
+import os, sys, traceback
+import os.path
+import re
+import signal
+from subprocess import *
+import time
+import types
+
+# Third-party modules
+import unittest2
+from six import add_metaclass
+from six import StringIO as SixStringIO
+from six.moves.urllib import parse as urlparse
+import six
+
+# LLDB modules
+import lldb
+from . import configuration
+from . import lldbtest_config
+from . import lldbutil
+from . import test_categories
+
+from .result_formatter import EventBuilder
+
+# dosep.py starts lots and lots of dotest instances
+# This option helps you find if two (or more) dotest instances are using the same
+# directory at the same time
+# Enable it to cause test failures and stderr messages if dotest instances try to run in
+# the same directory simultaneously
+# it is disabled by default because it litters the test directories with ".dirlock" files
+debug_confirm_directory_exclusivity = False
+
+# See also dotest.parseOptionsAndInitTestdirs(), where the environment variables
+# LLDB_COMMAND_TRACE and LLDB_DO_CLEANUP are set from '-t' and '-r dir' options.
+
+# 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 cout = 1"
+
+BREAKPOINT_HIT_TWICE = "Breakpoint resolved with hit cout = 2"
+
+BREAKPOINT_HIT_THRICE = "Breakpoint resolved with hit cout = 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_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_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(str):
+ '''A generic "Command '%s' returns successfully" message generator.'''
+ return "Command '%s' returns successfully" % str
+
+def COMPLETION_MSG(str_before, str_after):
+ '''A generic message generator for the completion mechanism.'''
+ return "'%s' successfully completes to '%s'" % (str_before, str_after)
+
+def EXP_MSG(str, exe):
+ '''A generic "'%s' returns expected result" message generator if exe.
+ Otherwise, it generates "'%s' matches expected result" message.'''
+ return "'%s' %s expected result" % (str, 'returns' if exe else 'matches')
+
+def SETTING_MSG(setting):
+ '''A generic "Value of setting '%s' is correct" message generator.'''
+ return "Value of setting '%s' is correct" % setting
+
+def EnvArray():
+ """Returns an env variable array from the os.environ map object."""
+ return list(map(lambda k,v: k+"="+v, list(os.environ.keys()), list(os.environ.values())))
+
+def line_number(filename, string_to_match):
+ """Helper function to return the line number of the first matched string."""
+ with open(filename, 'r') 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 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."""
+ 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 recording(SixStringIO):
+ """
+ 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 SixStringIO instance; record the session obj and trace flag."""
+ SixStringIO.__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 SixStringIO 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 SixStringIO object, too.
+ """
+ if self.trace:
+ print(self.getvalue(), file=sys.stderr)
+ if self.session:
+ print(self.getvalue(), file=self.session)
+ self.close()
+
+@add_metaclass(abc.ABCMeta)
+class _BaseProcess(object):
+
+ @abc.abstractproperty
+ def pid(self):
+ """Returns process PID if has been launched already."""
+
+ @abc.abstractmethod
+ def launch(self, executable, args):
+ """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):
+ self._proc = Popen([executable] + args,
+ stdout = open(os.devnull) if not self._trace_on else None,
+ stdin = PIPE)
+
+ def terminate(self):
+ if self._proc.poll() == 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() != 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() != None:
+ return
+ self._proc.kill()
+ time.sleep(self._delayafterterminate)
+
+ def poll(self):
+ return self._proc.poll()
+
+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):
+ if self._install_remote:
+ src_path = executable
+ dst_path = lldbutil.append_to_process_working_directory(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)
+
+ 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)
+
+# From 2.7's subprocess.check_output() convenience function.
+# Return a tuple (stdoutdata, stderrdata).
+def system(commands, **kwargs):
+ r"""Run an os command with arguments and return its output as a byte string.
+
+ If the exit code was non-zero it raises a CalledProcessError. The
+ CalledProcessError object will have the return code in the returncode
+ attribute and output in the output attribute.
+
+ The arguments are the same as for the Popen constructor. Example:
+
+ >>> check_output(["ls", "-l", "/dev/null"])
+ 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
+
+ The stdout argument is not allowed as it is used internally.
+ To capture standard error in the result, use stderr=STDOUT.
+
+ >>> check_output(["/bin/sh", "-c",
+ ... "ls -l non_existent_file ; exit 0"],
+ ... stderr=STDOUT)
+ 'ls: non_existent_file: No such file or directory\n'
+ """
+
+ # Assign the sender object to variable 'test' and remove it from kwargs.
+ test = kwargs.pop('sender', None)
+
+ # [['make', 'clean', 'foo'], ['make', 'foo']] -> ['make clean foo', 'make foo']
+ commandList = [' '.join(x) for x in commands]
+ output = ""
+ error = ""
+ for shellCommand in commandList:
+ if 'stdout' in kwargs:
+ raise ValueError('stdout argument not allowed, it will be overridden.')
+ if 'shell' in kwargs and kwargs['shell']==False:
+ raise ValueError('shell=False not allowed')
+ process = Popen(shellCommand, stdout=PIPE, stderr=PIPE, shell=True, universal_newlines=True, **kwargs)
+ pid = process.pid
+ this_output, this_error = process.communicate()
+ retcode = process.poll()
+
+ # Enable trace on failure return while tracking down FreeBSD buildbot issues
+ trace = traceAlways
+ if not trace and retcode and sys.platform.startswith("freebsd"):
+ trace = True
+
+ with recording(test, trace) as sbuf:
+ print(file=sbuf)
+ print("os command:", shellCommand, file=sbuf)
+ print("with pid:", pid, file=sbuf)
+ print("stdout:", this_output, file=sbuf)
+ print("stderr:", this_error, file=sbuf)
+ print("retcode:", retcode, file=sbuf)
+ print(file=sbuf)
+
+ if retcode:
+ cmd = kwargs.get("args")
+ if cmd is None:
+ cmd = shellCommand
+ raise CalledProcessError(retcode, cmd)
+ output = output + this_output
+ error = error + this_error
+ return (output, error)
+
+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():
+ if sys.platform.startswith("freebsd"):
+ return __import__("builder_freebsd")
+ if sys.platform.startswith("netbsd"):
+ return __import__("builder_netbsd")
+ return __import__("builder_" + sys.platform)
+
+def run_adb_command(cmd, device_id):
+ device_id_args = []
+ if device_id:
+ device_id_args = ["-s", device_id]
+ full_cmd = ["adb"] + device_id_args + cmd
+ p = Popen(full_cmd, stdout=PIPE, stderr=PIPE)
+ stdout, stderr = p.communicate()
+ return p.returncode, stdout, stderr
+
+def append_android_envs(dictionary):
+ if dictionary is None:
+ dictionary = {}
+ dictionary["OS"] = "Android"
+ if android_device_api() >= 16:
+ dictionary["PIE"] = 1
+ return dictionary
+
+def target_is_android():
+ if not hasattr(target_is_android, 'result'):
+ triple = lldb.DBG.GetSelectedPlatform().GetTriple()
+ match = re.match(".*-.*-.*-android", triple)
+ target_is_android.result = match is not None
+ return target_is_android.result
+
+def android_device_api():
+ if not hasattr(android_device_api, 'result'):
+ assert configuration.lldb_platform_url is not None
+ device_id = None
+ parsed_url = urlparse.urlparse(configuration.lldb_platform_url)
+ host_name = parsed_url.netloc.split(":")[0]
+ if host_name != 'localhost':
+ device_id = host_name
+ if device_id.startswith('[') and device_id.endswith(']'):
+ device_id = device_id[1:-1]
+ retcode, stdout, stderr = run_adb_command(
+ ["shell", "getprop", "ro.build.version.sdk"], device_id)
+ if retcode == 0:
+ android_device_api.result = int(stdout)
+ else:
+ raise LookupError(
+ ">>> Unable to determine the API level of the Android device.\n"
+ ">>> stdout:\n%s\n"
+ ">>> stderr:\n%s\n" % (stdout, stderr))
+ return android_device_api.result
+
+def check_expected_version(comparison, expected, actual):
+ def fn_leq(x,y): return x <= y
+ def fn_less(x,y): return x < y
+ def fn_geq(x,y): return x >= y
+ def fn_greater(x,y): return x > y
+ def fn_eq(x,y): return x == y
+ def fn_neq(x,y): return x != y
+
+ op_lookup = {
+ "==": fn_eq,
+ "=": fn_eq,
+ "!=": fn_neq,
+ "<>": fn_neq,
+ ">": fn_greater,
+ "<": fn_less,
+ ">=": fn_geq,
+ "<=": fn_leq
+ }
+ expected_str = '.'.join([str(x) for x in expected])
+ actual_str = '.'.join([str(x) for x in actual])
+
+ return op_lookup[comparison](LooseVersion(actual_str), LooseVersion(expected_str))
+
+#
+# Decorators for categorizing test cases.
+#
+from functools import wraps
+
+def add_test_categories(cat):
+ """Add test categories to a TestCase method"""
+ cat = test_categories.validate(cat, True)
+ def impl(func):
+ if isinstance(func, type) and issubclass(func, unittest2.TestCase):
+ raise Exception("@add_test_categories can only be used to decorate a test method")
+ if hasattr(func, "categories"):
+ cat.extend(func.categories)
+ func.categories = cat
+ return func
+
+ return impl
+
+def benchmarks_test(func):
+ """Decorate the item as a benchmarks test."""
+ if isinstance(func, type) and issubclass(func, unittest2.TestCase):
+ raise Exception("@benchmarks_test can only be used to decorate a test method")
+ @wraps(func)
+ def wrapper(self, *args, **kwargs):
+ self.skipTest("benchmarks test")
+ return func(self, *args, **kwargs)
+
+ # Mark this function as such to separate them from the regular tests.
+ wrapper.__benchmarks_test__ = True
+ return wrapper
+
+def no_debug_info_test(func):
+ """Decorate the item as a test what don't use any debug info. If this annotation is specified
+ then the test runner won't generate a separate test for each debug info format. """
+ if isinstance(func, type) and issubclass(func, unittest2.TestCase):
+ raise Exception("@no_debug_info_test can only be used to decorate a test method")
+ @wraps(func)
+ def wrapper(self, *args, **kwargs):
+ return func(self, *args, **kwargs)
+
+ # Mark this function as such to separate them from the regular tests.
+ wrapper.__no_debug_info_test__ = True
+ return wrapper
+
+def debugserver_test(func):
+ """Decorate the item as a debugserver test."""
+ if isinstance(func, type) and issubclass(func, unittest2.TestCase):
+ raise Exception("@debugserver_test can only be used to decorate a test method")
+ @wraps(func)
+ def wrapper(self, *args, **kwargs):
+ if configuration.dont_do_debugserver_test:
+ self.skipTest("debugserver tests")
+ return func(self, *args, **kwargs)
+
+ # Mark this function as such to separate them from the regular tests.
+ wrapper.__debugserver_test__ = True
+ return wrapper
+
+def llgs_test(func):
+ """Decorate the item as a lldb-server test."""
+ if isinstance(func, type) and issubclass(func, unittest2.TestCase):
+ raise Exception("@llgs_test can only be used to decorate a test method")
+ @wraps(func)
+ def wrapper(self, *args, **kwargs):
+ if configuration.dont_do_llgs_test:
+ self.skipTest("llgs tests")
+ return func(self, *args, **kwargs)
+
+ # Mark this function as such to separate them from the regular tests.
+ wrapper.__llgs_test__ = True
+ return wrapper
+
+def not_remote_testsuite_ready(func):
+ """Decorate the item as a test which is not ready yet for remote testsuite."""
+ if isinstance(func, type) and issubclass(func, unittest2.TestCase):
+ raise Exception("@not_remote_testsuite_ready can only be used to decorate a test method")
+ @wraps(func)
+ def wrapper(self, *args, **kwargs):
+ if lldb.remote_platform:
+ self.skipTest("not ready for remote testsuite")
+ return func(self, *args, **kwargs)
+
+ # Mark this function as such to separate them from the regular tests.
+ wrapper.__not_ready_for_remote_testsuite_test__ = True
+ return wrapper
+
+def expectedFailure(expected_fn, bugnumber=None):
+ def expectedFailure_impl(func):
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ from unittest2 import case
+ self = args[0]
+ if expected_fn(self):
+ if configuration.results_formatter_object is not None:
+ # Mark this test as expected to fail.
+ configuration.results_formatter_object.handle_event(
+ EventBuilder.event_for_mark_test_expected_failure(self))
+ xfail_func = unittest2.expectedFailure(func)
+ xfail_func(*args, **kwargs)
+ else:
+ func(*args, **kwargs)
+ return wrapper
+ # if bugnumber is not-callable(incluing None), that means decorator function is called with optional arguments
+ # return decorator in this case, so it will be used to decorating original method
+ if six.callable(bugnumber):
+ return expectedFailure_impl(bugnumber)
+ else:
+ return expectedFailure_impl
+
+# You can also pass not_in(list) to reverse the sense of the test for the arguments that
+# are simple lists, namely oslist, compiler, and debug_info.
+
+def not_in(iterable):
+ return lambda x : x not in iterable
+
+def check_list_or_lambda(list_or_lambda, value):
+ if six.callable(list_or_lambda):
+ return list_or_lambda(value)
+ elif isinstance(list_or_lambda, list):
+ for item in list_or_lambda:
+ if value in item:
+ return True
+ return False
+ elif isinstance(list_or_lambda, str):
+ return value is None or value in list_or_lambda
+ else:
+ return list_or_lambda is None or value is None or list_or_lambda == value
+
+# provide a function to xfail on defined oslist, compiler version, and archs
+# if none is specified for any argument, that argument won't be checked and thus means for all
+# for example,
+# @expectedFailureAll, xfail for all platform/compiler/arch,
+# @expectedFailureAll(compiler='gcc'), xfail for gcc on all platform/architecture
+# @expectedFailureAll(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), xfail for gcc>=4.9 on linux with i386
+def expectedFailureAll(bugnumber=None, oslist=None, hostoslist=None, compiler=None, compiler_version=None, archs=None, triple=None, debug_info=None, swig_version=None, py_version=None):
+ def fn(self):
+ oslist_passes = check_list_or_lambda(oslist, self.getPlatform())
+ hostoslist_passes = check_list_or_lambda(hostoslist, getHostPlatform())
+ compiler_passes = check_list_or_lambda(self.getCompiler(), compiler) and self.expectedCompilerVersion(compiler_version)
+ arch_passes = check_list_or_lambda(archs, self.getArchitecture())
+ triple_passes = triple is None or re.match(triple, lldb.DBG.GetSelectedPlatform().GetTriple())
+ debug_info_passes = check_list_or_lambda(debug_info, self.debug_info)
+ swig_version_passes = (swig_version is None) or (not hasattr(lldb, 'swig_version')) or (check_expected_version(swig_version[0], swig_version[1], lldb.swig_version))
+ py_version_passes = (py_version is None) or check_expected_version(py_version[0], py_version[1], sys.version_info)
+
+ return (oslist_passes and
+ hostoslist_passes and
+ compiler_passes and
+ arch_passes and
+ triple_passes and
+ debug_info_passes and
+ swig_version_passes and
+ py_version_passes)
+ return expectedFailure(fn, bugnumber)
+
+def expectedFailureDwarf(bugnumber=None):
+ return expectedFailureAll(bugnumber=bugnumber, debug_info="dwarf")
+
+def expectedFailureDwo(bugnumber=None):
+ return expectedFailureAll(bugnumber=bugnumber, debug_info="dwo")
+
+def expectedFailureDsym(bugnumber=None):
+ return expectedFailureAll(bugnumber=bugnumber, debug_info="dsym")
+
+def expectedFailureCompiler(compiler, compiler_version=None, bugnumber=None):
+ if compiler_version is None:
+ compiler_version=['=', None]
+ return expectedFailureAll(bugnumber=bugnumber, compiler=compiler, compiler_version=compiler_version)
+
+# to XFAIL a specific clang versions, try this
+# @expectedFailureClang('bugnumber', ['<=', '3.4'])
+def expectedFailureClang(bugnumber=None, compiler_version=None):
+ return expectedFailureCompiler('clang', compiler_version, bugnumber)
+
+def expectedFailureGcc(bugnumber=None, compiler_version=None):
+ return expectedFailureCompiler('gcc', compiler_version, bugnumber)
+
+def expectedFailureIcc(bugnumber=None):
+ return expectedFailureCompiler('icc', None, bugnumber)
+
+def expectedFailureArch(arch, bugnumber=None):
+ def fn(self):
+ return arch in self.getArchitecture()
+ return expectedFailure(fn, bugnumber)
+
+def expectedFailurei386(bugnumber=None):
+ return expectedFailureArch('i386', bugnumber)
+
+def expectedFailurex86_64(bugnumber=None):
+ return expectedFailureArch('x86_64', bugnumber)
+
+def expectedFailureOS(oslist, bugnumber=None, compilers=None, debug_info=None):
+ def fn(self):
+ return (self.getPlatform() in oslist and
+ self.expectedCompiler(compilers) and
+ (debug_info is None or self.debug_info in debug_info))
+ return expectedFailure(fn, bugnumber)
+
+def expectedFailureHostOS(oslist, bugnumber=None, compilers=None):
+ def fn(self):
+ return (getHostPlatform() in oslist and
+ self.expectedCompiler(compilers))
+ return expectedFailure(fn, bugnumber)
+
+def expectedFailureDarwin(bugnumber=None, compilers=None, debug_info=None):
+ # For legacy reasons, we support both "darwin" and "macosx" as OS X triples.
+ return expectedFailureOS(getDarwinOSTriples(), bugnumber, compilers, debug_info=debug_info)
+
+def expectedFailureFreeBSD(bugnumber=None, compilers=None, debug_info=None):
+ return expectedFailureOS(['freebsd'], bugnumber, compilers, debug_info=debug_info)
+
+def expectedFailureLinux(bugnumber=None, compilers=None, debug_info=None):
+ return expectedFailureOS(['linux'], bugnumber, compilers, debug_info=debug_info)
+
+def expectedFailureNetBSD(bugnumber=None, compilers=None, debug_info=None):
+ return expectedFailureOS(['netbsd'], bugnumber, compilers, debug_info=debug_info)
+
+def expectedFailureWindows(bugnumber=None, compilers=None, debug_info=None):
+ return expectedFailureOS(['windows'], bugnumber, compilers, debug_info=debug_info)
+
+def expectedFailureHostWindows(bugnumber=None, compilers=None):
+ return expectedFailureHostOS(['windows'], bugnumber, compilers)
+
+def matchAndroid(api_levels=None, archs=None):
+ def match(self):
+ if not target_is_android():
+ return False
+ if archs is not None and self.getArchitecture() not in archs:
+ return False
+ if api_levels is not None and android_device_api() not in api_levels:
+ return False
+ return True
+ return match
+
+
+def expectedFailureAndroid(bugnumber=None, api_levels=None, archs=None):
+ """ Mark a test as xfail for Android.
+
+ Arguments:
+ bugnumber - The LLVM pr associated with the problem.
+ api_levels - A sequence of numbers specifying the Android API levels
+ for which a test is expected to fail. None means all API level.
+ arch - A sequence of architecture names specifying the architectures
+ for which a test is expected to fail. None means all architectures.
+ """
+ return expectedFailure(matchAndroid(api_levels, archs), bugnumber)
+
+# Flakey tests get two chances to run. If they fail the first time round, the result formatter
+# makes sure it is run one more time.
+def expectedFlakey(expected_fn, bugnumber=None):
+ def expectedFailure_impl(func):
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ self = args[0]
+ if expected_fn(self):
+ # Send event marking test as explicitly eligible for rerunning.
+ if configuration.results_formatter_object is not None:
+ # Mark this test as rerunnable.
+ configuration.results_formatter_object.handle_event(
+ EventBuilder.event_for_mark_test_rerun_eligible(self))
+ func(*args, **kwargs)
+ return wrapper
+ # if bugnumber is not-callable(incluing None), that means decorator function is called with optional arguments
+ # return decorator in this case, so it will be used to decorating original method
+ if six.callable(bugnumber):
+ return expectedFailure_impl(bugnumber)
+ else:
+ return expectedFailure_impl
+
+def expectedFlakeyDwarf(bugnumber=None):
+ def fn(self):
+ return self.debug_info == "dwarf"
+ return expectedFlakey(fn, bugnumber)
+
+def expectedFlakeyDsym(bugnumber=None):
+ def fn(self):
+ return self.debug_info == "dwarf"
+ return expectedFlakey(fn, bugnumber)
+
+def expectedFlakeyOS(oslist, bugnumber=None, compilers=None):
+ def fn(self):
+ return (self.getPlatform() in oslist and
+ self.expectedCompiler(compilers))
+ return expectedFlakey(fn, bugnumber)
+
+def expectedFlakeyDarwin(bugnumber=None, compilers=None):
+ # For legacy reasons, we support both "darwin" and "macosx" as OS X triples.
+ return expectedFlakeyOS(getDarwinOSTriples(), bugnumber, compilers)
+
+def expectedFlakeyFreeBSD(bugnumber=None, compilers=None):
+ return expectedFlakeyOS(['freebsd'], bugnumber, compilers)
+
+def expectedFlakeyLinux(bugnumber=None, compilers=None):
+ return expectedFlakeyOS(['linux'], bugnumber, compilers)
+
+def expectedFlakeyNetBSD(bugnumber=None, compilers=None):
+ return expectedFlakeyOS(['netbsd'], bugnumber, compilers)
+
+def expectedFlakeyCompiler(compiler, compiler_version=None, bugnumber=None):
+ if compiler_version is None:
+ compiler_version=['=', None]
+ def fn(self):
+ return compiler in self.getCompiler() and self.expectedCompilerVersion(compiler_version)
+ return expectedFlakey(fn, bugnumber)
+
+# @expectedFlakeyClang('bugnumber', ['<=', '3.4'])
+def expectedFlakeyClang(bugnumber=None, compiler_version=None):
+ return expectedFlakeyCompiler('clang', compiler_version, bugnumber)
+
+# @expectedFlakeyGcc('bugnumber', ['<=', '3.4'])
+def expectedFlakeyGcc(bugnumber=None, compiler_version=None):
+ return expectedFlakeyCompiler('gcc', compiler_version, bugnumber)
+
+def expectedFlakeyAndroid(bugnumber=None, api_levels=None, archs=None):
+ return expectedFlakey(matchAndroid(api_levels, archs), bugnumber)
+
+def skipIfRemote(func):
+ """Decorate the item to skip tests if testing remotely."""
+ if isinstance(func, type) and issubclass(func, unittest2.TestCase):
+ raise Exception("@skipIfRemote can only be used to decorate a test method")
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ from unittest2 import case
+ if lldb.remote_platform:
+ self = args[0]
+ self.skipTest("skip on remote platform")
+ else:
+ func(*args, **kwargs)
+ return wrapper
+
+def skipUnlessListedRemote(remote_list=None):
+ def myImpl(func):
+ if isinstance(func, type) and issubclass(func, unittest2.TestCase):
+ raise Exception("@skipIfRemote can only be used to decorate a "
+ "test method")
+
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ if remote_list and lldb.remote_platform:
+ self = args[0]
+ triple = self.dbg.GetSelectedPlatform().GetTriple()
+ for r in remote_list:
+ if r in triple:
+ func(*args, **kwargs)
+ return
+ self.skipTest("skip on remote platform %s" % str(triple))
+ else:
+ func(*args, **kwargs)
+ return wrapper
+
+ return myImpl
+
+def skipIfRemoteDueToDeadlock(func):
+ """Decorate the item to skip tests if testing remotely due to the test deadlocking."""
+ if isinstance(func, type) and issubclass(func, unittest2.TestCase):
+ raise Exception("@skipIfRemote can only be used to decorate a test method")
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ from unittest2 import case
+ if lldb.remote_platform:
+ self = args[0]
+ self.skipTest("skip on remote platform (deadlocks)")
+ else:
+ func(*args, **kwargs)
+ return wrapper
+
+def skipIfNoSBHeaders(func):
+ """Decorate the item to mark tests that should be skipped when LLDB is built with no SB API headers."""
+ if isinstance(func, type) and issubclass(func, unittest2.TestCase):
+ raise Exception("@skipIfNoSBHeaders can only be used to decorate a test method")
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ from unittest2 import case
+ self = args[0]
+ if sys.platform.startswith("darwin"):
+ header = os.path.join(os.environ["LLDB_LIB_DIR"], 'LLDB.framework', 'Versions','Current','Headers','LLDB.h')
+ else:
+ header = os.path.join(os.environ["LLDB_SRC"], "include", "lldb", "API", "LLDB.h")
+ platform = sys.platform
+ if not os.path.exists(header):
+ self.skipTest("skip because LLDB.h header not found")
+ else:
+ func(*args, **kwargs)
+ return wrapper
+
+def skipIfiOSSimulator(func):
+ """Decorate the item to skip tests that should be skipped on the iOS Simulator."""
+ return unittest2.skipIf(configuration.lldb_platform_name == 'ios-simulator', 'skip on the iOS Simulator')(func)
+
+def skipIfFreeBSD(func):
+ """Decorate the item to skip tests that should be skipped on FreeBSD."""
+ return skipIfPlatform(["freebsd"])(func)
+
+def skipIfNetBSD(func):
+ """Decorate the item to skip tests that should be skipped on NetBSD."""
+ return skipIfPlatform(["netbsd"])(func)
+
+def getDarwinOSTriples():
+ return ['darwin', 'macosx', 'ios']
+
+def skipIfDarwin(func):
+ """Decorate the item to skip tests that should be skipped on Darwin."""
+ return skipIfPlatform(getDarwinOSTriples())(func)
+
+def skipIfLinux(func):
+ """Decorate the item to skip tests that should be skipped on Linux."""
+ return skipIfPlatform(["linux"])(func)
+
+def skipUnlessHostLinux(func):
+ """Decorate the item to skip tests that should be skipped on any non Linux host."""
+ return skipUnlessHostPlatform(["linux"])(func)
+
+def skipIfWindows(func):
+ """Decorate the item to skip tests that should be skipped on Windows."""
+ return skipIfPlatform(["windows"])(func)
+
+def skipIfHostWindows(func):
+ """Decorate the item to skip tests that should be skipped on Windows."""
+ return skipIfHostPlatform(["windows"])(func)
+
+def skipUnlessWindows(func):
+ """Decorate the item to skip tests that should be skipped on any non-Windows platform."""
+ return skipUnlessPlatform(["windows"])(func)
+
+def skipUnlessDarwin(func):
+ """Decorate the item to skip tests that should be skipped on any non Darwin platform."""
+ return skipUnlessPlatform(getDarwinOSTriples())(func)
+
+def skipUnlessGoInstalled(func):
+ """Decorate the item to skip tests when no Go compiler is available."""
+ if isinstance(func, type) and issubclass(func, unittest2.TestCase):
+ raise Exception("@skipIfGcc can only be used to decorate a test method")
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ from unittest2 import case
+ self = args[0]
+ compiler = self.getGoCompilerVersion()
+ if not compiler:
+ self.skipTest("skipping because go compiler not found")
+ else:
+ # Ensure the version is the minimum version supported by
+ # the LLDB go support.
+ match_version = re.search(r"(\d+\.\d+(\.\d+)?)", compiler)
+ if not match_version:
+ # Couldn't determine version.
+ self.skipTest(
+ "skipping because go version could not be parsed "
+ "out of {}".format(compiler))
+ else:
+ from distutils.version import StrictVersion
+ min_strict_version = StrictVersion("1.4.0")
+ compiler_strict_version = StrictVersion(match_version.group(1))
+ if compiler_strict_version < min_strict_version:
+ self.skipTest(
+ "skipping because available go version ({}) does "
+ "not meet minimum required go version ({})".format(
+ compiler_strict_version,
+ min_strict_version))
+ func(*args, **kwargs)
+ return wrapper
+
+def getPlatform():
+ """Returns the target platform which the tests are running on."""
+ platform = lldb.DBG.GetSelectedPlatform().GetTriple().split('-')[2]
+ if platform.startswith('freebsd'):
+ platform = 'freebsd'
+ elif platform.startswith('netbsd'):
+ platform = 'netbsd'
+ return platform
+
+def getHostPlatform():
+ """Returns the host platform running the test suite."""
+ # Attempts to return a platform name matching a target Triple platform.
+ if sys.platform.startswith('linux'):
+ return 'linux'
+ elif sys.platform.startswith('win32'):
+ return 'windows'
+ elif sys.platform.startswith('darwin'):
+ return 'darwin'
+ elif sys.platform.startswith('freebsd'):
+ return 'freebsd'
+ elif sys.platform.startswith('netbsd'):
+ return 'netbsd'
+ else:
+ return sys.platform
+
+def platformIsDarwin():
+ """Returns true if the OS triple for the selected platform is any valid apple OS"""
+ return getPlatform() in getDarwinOSTriples()
+
+def skipIfHostIncompatibleWithRemote(func):
+ """Decorate the item to skip tests if binaries built on this host are incompatible."""
+ if isinstance(func, type) and issubclass(func, unittest2.TestCase):
+ raise Exception("@skipIfHostIncompatibleWithRemote can only be used to decorate a test method")
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ from unittest2 import case
+ self = args[0]
+ host_arch = self.getLldbArchitecture()
+ host_platform = getHostPlatform()
+ target_arch = self.getArchitecture()
+ target_platform = 'darwin' if self.platformIsDarwin() else self.getPlatform()
+ if not (target_arch == 'x86_64' and host_arch == 'i386') and host_arch != target_arch:
+ self.skipTest("skipping because target %s is not compatible with host architecture %s" % (target_arch, host_arch))
+ elif target_platform != host_platform:
+ self.skipTest("skipping because target is %s but host is %s" % (target_platform, host_platform))
+ else:
+ func(*args, **kwargs)
+ return wrapper
+
+def skipIfHostPlatform(oslist):
+ """Decorate the item to skip tests if running on one of the listed host platforms."""
+ return unittest2.skipIf(getHostPlatform() in oslist,
+ "skip on %s" % (", ".join(oslist)))
+
+def skipUnlessHostPlatform(oslist):
+ """Decorate the item to skip tests unless running on one of the listed host platforms."""
+ return unittest2.skipUnless(getHostPlatform() in oslist,
+ "requires on of %s" % (", ".join(oslist)))
+
+def skipUnlessArch(archlist):
+ """Decorate the item to skip tests unless running on one of the listed architectures."""
+ def myImpl(func):
+ if isinstance(func, type) and issubclass(func, unittest2.TestCase):
+ raise Exception("@skipUnlessArch can only be used to decorate a test method")
+
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ self = args[0]
+ if self.getArchitecture() not in archlist:
+ self.skipTest("skipping for architecture %s (requires one of %s)" %
+ (self.getArchitecture(), ", ".join(archlist)))
+ else:
+ func(*args, **kwargs)
+ return wrapper
+
+ return myImpl
+
+def skipIfPlatform(oslist):
+ """Decorate the item to skip tests if running on one of the listed platforms."""
+ return unittest2.skipIf(getPlatform() in oslist,
+ "skip on %s" % (", ".join(oslist)))
+
+def skipUnlessPlatform(oslist):
+ """Decorate the item to skip tests unless running on one of the listed platforms."""
+ return unittest2.skipUnless(getPlatform() in oslist,
+ "requires on of %s" % (", ".join(oslist)))
+
+def skipIfLinuxClang(func):
+ """Decorate the item to skip tests that should be skipped if building on
+ Linux with clang.
+ """
+ if isinstance(func, type) and issubclass(func, unittest2.TestCase):
+ raise Exception("@skipIfLinuxClang can only be used to decorate a test method")
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ from unittest2 import case
+ self = args[0]
+ compiler = self.getCompiler()
+ platform = self.getPlatform()
+ if "clang" in compiler and platform == "linux":
+ self.skipTest("skipping because Clang is used on Linux")
+ else:
+ func(*args, **kwargs)
+ return wrapper
+
+# provide a function to skip on defined oslist, compiler version, and archs
+# if none is specified for any argument, that argument won't be checked and thus means for all
+# for example,
+# @skipIf, skip for all platform/compiler/arch,
+# @skipIf(compiler='gcc'), skip for gcc on all platform/architecture
+# @skipIf(bugnumber, ["linux"], "gcc", ['>=', '4.9'], ['i386']), skip for gcc>=4.9 on linux with i386
+
+# TODO: refactor current code, to make skipIfxxx functions to call this function
+def skipIf(bugnumber=None, oslist=None, compiler=None, compiler_version=None, archs=None, debug_info=None, swig_version=None, py_version=None, remote=None):
+ def fn(self):
+ oslist_passes = check_list_or_lambda(oslist, self.getPlatform())
+ compiler_passes = check_list_or_lambda(self.getCompiler(), compiler) and self.expectedCompilerVersion(compiler_version)
+ arch_passes = check_list_or_lambda(archs, self.getArchitecture())
+ debug_info_passes = check_list_or_lambda(debug_info, self.debug_info)
+ swig_version_passes = (swig_version is None) or (not hasattr(lldb, 'swig_version')) or (check_expected_version(swig_version[0], swig_version[1], lldb.swig_version))
+ py_version_passes = (py_version is None) or check_expected_version(py_version[0], py_version[1], sys.version_info)
+ remote_passes = (remote is None) or (remote == (lldb.remote_platform is not None))
+
+ return (oslist_passes and
+ compiler_passes and
+ arch_passes and
+ debug_info_passes and
+ swig_version_passes and
+ py_version_passes and
+ remote_passes)
+
+ local_vars = locals()
+ args = [x for x in inspect.getargspec(skipIf).args]
+ arg_vals = [eval(x, globals(), local_vars) for x in args]
+ args = [x for x in zip(args, arg_vals) if x[1] is not None]
+ reasons = ['%s=%s' % (x, str(y)) for (x,y) in args]
+ return skipTestIfFn(fn, bugnumber, skipReason='skipping because ' + ' && '.join(reasons))
+
+def skipIfDebugInfo(bugnumber=None, debug_info=None):
+ return skipIf(bugnumber=bugnumber, debug_info=debug_info)
+
+def skipIfDWO(bugnumber=None):
+ return skipIfDebugInfo(bugnumber, ["dwo"])
+
+def skipIfDwarf(bugnumber=None):
+ return skipIfDebugInfo(bugnumber, ["dwarf"])
+
+def skipIfDsym(bugnumber=None):
+ return skipIfDebugInfo(bugnumber, ["dsym"])
+
+def skipTestIfFn(expected_fn, bugnumber=None, skipReason=None):
+ def skipTestIfFn_impl(func):
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ from unittest2 import case
+ self = args[0]
+ if expected_fn(self):
+ self.skipTest(skipReason)
+ else:
+ func(*args, **kwargs)
+ return wrapper
+ if six.callable(bugnumber):
+ return skipTestIfFn_impl(bugnumber)
+ else:
+ return skipTestIfFn_impl
+
+def skipIfGcc(func):
+ """Decorate the item to skip tests that should be skipped if building with gcc ."""
+ if isinstance(func, type) and issubclass(func, unittest2.TestCase):
+ raise Exception("@skipIfGcc can only be used to decorate a test method")
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ from unittest2 import case
+ self = args[0]
+ compiler = self.getCompiler()
+ if "gcc" in compiler:
+ self.skipTest("skipping because gcc is the test compiler")
+ else:
+ func(*args, **kwargs)
+ return wrapper
+
+def skipIfIcc(func):
+ """Decorate the item to skip tests that should be skipped if building with icc ."""
+ if isinstance(func, type) and issubclass(func, unittest2.TestCase):
+ raise Exception("@skipIfIcc can only be used to decorate a test method")
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ from unittest2 import case
+ self = args[0]
+ compiler = self.getCompiler()
+ if "icc" in compiler:
+ self.skipTest("skipping because icc is the test compiler")
+ else:
+ func(*args, **kwargs)
+ return wrapper
+
+def skipIfi386(func):
+ """Decorate the item to skip tests that should be skipped if building 32-bit."""
+ if isinstance(func, type) and issubclass(func, unittest2.TestCase):
+ raise Exception("@skipIfi386 can only be used to decorate a test method")
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ from unittest2 import case
+ self = args[0]
+ if "i386" == self.getArchitecture():
+ self.skipTest("skipping because i386 is not a supported architecture")
+ else:
+ func(*args, **kwargs)
+ return wrapper
+
+def skipIfTargetAndroid(api_levels=None, archs=None):
+ """Decorator to skip tests when the target is Android.
+
+ Arguments:
+ api_levels - The API levels for which the test should be skipped. If
+ it is None, then the test will be skipped for all API levels.
+ arch - A sequence of architecture names specifying the architectures
+ for which a test is skipped. None means all architectures.
+ """
+ def myImpl(func):
+ if isinstance(func, type) and issubclass(func, unittest2.TestCase):
+ raise Exception("@skipIfTargetAndroid can only be used to "
+ "decorate a test method")
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ from unittest2 import case
+ self = args[0]
+ if matchAndroid(api_levels, archs)(self):
+ self.skipTest("skiped on Android target with API %d and architecture %s" %
+ (android_device_api(), self.getArchitecture()))
+ func(*args, **kwargs)
+ return wrapper
+ return myImpl
+
+def skipUnlessCompilerRt(func):
+ """Decorate the item to skip tests if testing remotely."""
+ if isinstance(func, type) and issubclass(func, unittest2.TestCase):
+ raise Exception("@skipUnless can only be used to decorate a test method")
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ from unittest2 import case
+ import os.path
+ compilerRtPath = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "llvm","projects","compiler-rt")
+ print(compilerRtPath)
+ if not os.path.exists(compilerRtPath):
+ self = args[0]
+ self.skipTest("skip if compiler-rt not found")
+ else:
+ func(*args, **kwargs)
+ return wrapper
+
+class _PlatformContext(object):
+ """Value object class which contains platform-specific options."""
+
+ def __init__(self, shlib_environment_var, shlib_prefix, shlib_extension):
+ self.shlib_environment_var = shlib_environment_var
+ self.shlib_prefix = shlib_prefix
+ self.shlib_extension = shlib_extension
+
+
+class Base(unittest2.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
+
+ @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__)'''
+ test_dir = os.path.dirname(test_file)
+ return test_dir[len(os.environ["LLDB_TEST"])+1:]
+
+ def TraceOn(self):
+ """Returns True if we are in trace mode (tracing detailed test execution)."""
+ return traceAlways
+
+ @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 or len(cls.mydir) == 0:
+ raise Exception("Subclasses must override the 'mydir' attribute.")
+
+ # Save old working directory.
+ cls.oldcwd = os.getcwd()
+
+ # Change current working directory if ${LLDB_TEST} is defined.
+ # See also dotest.py which sets up ${LLDB_TEST}.
+ if ("LLDB_TEST" in os.environ):
+ full_dir = os.path.join(os.environ["LLDB_TEST"], cls.mydir)
+ if traceAlways:
+ print("Change dir to:", full_dir, file=sys.stderr)
+ os.chdir(os.path.join(os.environ["LLDB_TEST"], cls.mydir))
+
+ if debug_confirm_directory_exclusivity:
+ import lock
+ cls.dir_lock = lock.Lock(os.path.join(full_dir, ".dirlock"))
+ try:
+ cls.dir_lock.try_acquire()
+ # write the class that owns the lock into the lock file
+ cls.dir_lock.handle.write(cls.__name__)
+ except IOError as ioerror:
+ # nothing else should have this directory lock
+ # wait here until we get a lock
+ cls.dir_lock.acquire()
+ # read the previous owner from the lock file
+ lock_id = cls.dir_lock.handle.read()
+ print("LOCK ERROR: {} wants to lock '{}' but it is already locked by '{}'".format(cls.__name__, full_dir, lock_id), file=sys.stderr)
+ raise ioerror
+
+ # Set platform context.
+ if platformIsDarwin():
+ cls.platformContext = _PlatformContext('DYLD_LIBRARY_PATH', 'lib', 'dylib')
+ elif getPlatform() in ("freebsd", "linux", "netbsd"):
+ cls.platformContext = _PlatformContext('LD_LIBRARY_PATH', 'lib', 'so')
+ else:
+ cls.platformContext = None
+
+ @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)
+
+ if debug_confirm_directory_exclusivity:
+ cls.dir_lock.release()
+ del cls.dir_lock
+
+ # Restore old working directory.
+ if traceAlways:
+ print("Restore dir to:", cls.oldcwd, file=sys.stderr)
+ os.chdir(cls.oldcwd)
+
+ @classmethod
+ def skipLongRunningTest(cls):
+ """
+ By default, we skip long running test case.
+ This can be overridden by passing '-l' to the test driver (dotest.py).
+ """
+ if "LLDB_SKIP_LONG_RUNNING_TEST" in os.environ and "NO" == os.environ["LLDB_SKIP_LONG_RUNNING_TEST"]:
+ return False
+ else:
+ return True
+
+ 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()
+
+ 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":
+ # 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
+ server_log_path = "{}-server.log".format(log_basename)
+ open(server_log_path, 'w').close()
+ os.environ["LLDB_DEBUGSERVER_LOG_FILE"] = server_log_path
+
+ # Communicate channels to lldb-server
+ os.environ["LLDB_SERVER_LOG_CHANNELS"] = ":".join(lldbtest_config.channels)
+
+ if len(lldbtest_config.channels) == 0:
+ return
+
+ 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)')
+
+ 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 "LIBCXX_PATH" in os.environ:
+ self.libcxxPath = os.environ["LIBCXX_PATH"]
+ else:
+ self.libcxxPath = None
+
+ if "LLDBMI_EXEC" in os.environ:
+ self.lldbMiExec = os.environ["LLDBMI_EXEC"]
+ else:
+ self.lldbMiExec = None
+
+ # If we spawn an lldb process for test (via pexpect), do not load the
+ # init file unless told otherwise.
+ if "NO_LLDBINIT" in os.environ and "NO" == os.environ["NO_LLDBINIT"]:
+ self.lldbOption = ""
+ else:
+ 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 forked process PIDs
+ self.forkedProcessPids = []
+
+ # Create a string buffer to record the session info, to be dumped into a
+ # test case specific file if test failure is encountered.
+ self.log_basename = self.getLogBasenameForCurrentTest()
+
+ session_file = "{}.log".format(self.log_basename)
+ # Python 3 doesn't support unbuffered I/O in text mode. Open buffered.
+ self.session = open(session_file, "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 if necessary.
+ try:
+ self.dbg = lldb.DBG
+ except AttributeError:
+ self.dbg = lldb.SBDebugger.Create()
+
+ 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.enableLogChannelsForCurrentTest()
+
+ #Initialize debug_info
+ self.debug_info = None
+
+ 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):
+ # Ensure any subprocesses are cleaned up
+ for p in self.subprocesses:
+ p.terminate()
+ del p
+ del self.subprocesses[:]
+ # Ensure any forked processes are cleaned up
+ for pid in self.forkedProcessPids:
+ if os.path.exists("/proc/" + str(pid)):
+ os.kill(pid, signal.SIGTERM)
+
+ def spawnSubprocess(self, executable, args=[], install_remote=True):
+ """ Creates a subprocess.Popen object with the specified executable and arguments,
+ saves it in self.subprocesses, and returns the object.
+ NOTE: if using this function, ensure you also call:
+
+ self.addTearDownHook(self.cleanupSubprocesses)
+
+ otherwise the test suite will leak processes.
+ """
+ proc = _RemoteProcess(install_remote) if lldb.remote_platform else _LocalProcess(self.TraceOn())
+ proc.launch(executable, args)
+ self.subprocesses.append(proc)
+ return proc
+
+ def forkSubprocess(self, executable, args=[]):
+ """ Fork a subprocess with its own group ID.
+ NOTE: if using this function, ensure you also call:
+
+ self.addTearDownHook(self.cleanupSubprocesses)
+
+ otherwise the test suite will leak processes.
+ """
+ child_pid = os.fork()
+ if child_pid == 0:
+ # If more I/O support is required, this can be beefed up.
+ fd = os.open(os.devnull, os.O_RDWR)
+ os.dup2(fd, 1)
+ os.dup2(fd, 2)
+ # This call causes the child to have its of group ID
+ os.setpgid(0,0)
+ os.execvp(executable, [executable] + args)
+ # Give the child time to get through the execvp() call
+ time.sleep(0.1)
+ self.forkedProcessPids.append(child_pid)
+ return child_pid
+
+ def HideStdout(self):
+ """Hide output to stdout from the user.
+
+ During test execution, there might be cases where we don't want to show the
+ standard output to the user. For example,
+
+ self.runCmd(r'''sc print("\n\n\tHello!\n")''')
+
+ tests whether command abbreviation for 'script' works or not. There is no
+ need to show the 'Hello' output to the user as long as the 'script' command
+ succeeds and we are not in TraceOn() mode (see the '-t' option).
+
+ In this case, the test method calls self.HideStdout(self) to redirect the
+ sys.stdout to a null device, and restores the sys.stdout upon teardown.
+
+ Note that you should only call this method at most once during a test case
+ execution. Any subsequent call has no effect at all."""
+ if self.sys_stdout_hidden:
+ return
+
+ self.sys_stdout_hidden = True
+ old_stdout = sys.stdout
+ sys.stdout = open(os.devnull, 'w')
+ def restore_stdout():
+ sys.stdout = old_stdout
+ self.addTearDownHook(restore_stdout)
+
+ # =======================================================================
+ # Methods for customized teardown cleanups as well as execution of hooks.
+ # =======================================================================
+
+ def setTearDownCleanup(self, dictionary=None):
+ """Register a cleanup action at tearDown() time with a dictinary"""
+ self.dict = dictionary
+ self.doTearDownCleanup = True
+
+ def addTearDownCleanup(self, dictionary):
+ """Add a cleanup action at tearDown() time with a dictinary"""
+ self.dicts.append(dictionary)
+ self.doTearDownCleanups = True
+
+ def addTearDownHook(self, hook):
+ """
+ Add a function to be run during tearDown() time.
+
+ Hooks are executed in a first come first serve manner.
+ """
+ if six.callable(hook):
+ with recording(self, traceAlways) as sbuf:
+ print("Adding tearDown hook:", getsource_if_available(hook), file=sbuf)
+ self.hooks.append(hook)
+
+ return self
+
+ def deletePexpectChild(self):
+ # This is for the case of directly spawning 'lldb' and interacting with it
+ # using pexpect.
+ if self.child and self.child.isalive():
+ import pexpect
+ with recording(self, traceAlways) as sbuf:
+ print("tearing down the child process....", file=sbuf)
+ try:
+ if self.child_in_script_interpreter:
+ self.child.sendline('quit()')
+ self.child.expect_exact(self.child_prompt)
+ self.child.sendline('settings set interpreter.prompt-on-quit false')
+ self.child.sendline('quit')
+ self.child.expect(pexpect.EOF)
+ except (ValueError, pexpect.ExceptionPexpect):
+ # child is already terminated
+ pass
+ except OSError as exception:
+ import errno
+ if exception.errno != errno.EIO:
+ # unexpected error
+ raise
+ # child is already terminated
+ pass
+ finally:
+ # Give it one final blow to make sure the child is terminated.
+ self.child.close()
+
+ def tearDown(self):
+ """Fixture for unittest test case teardown."""
+ #import traceback
+ #traceback.print_stack()
+
+ self.deletePexpectChild()
+
+ # Check and run any hook functions.
+ for hook in reversed(self.hooks):
+ with recording(self, traceAlways) as sbuf:
+ print("Executing tearDown hook:", getsource_if_available(hook), file=sbuf)
+ import inspect
+ hook_argc = len(inspect.getargspec(hook).args)
+ if hook_argc == 0 or getattr(hook,'im_self',None):
+ hook()
+ elif hook_argc == 1:
+ hook(self)
+ else:
+ hook() # try the plain call and hope it works
+
+ del self.hooks
+
+ # Perform registered teardown cleanup.
+ if doCleanup and self.doTearDownCleanup:
+ self.cleanup(dictionary=self.dict)
+
+ # In rare cases where there are multiple teardown cleanups added.
+ if doCleanup and self.doTearDownCleanups:
+ if self.dicts:
+ for dict in reversed(self.dicts):
+ self.cleanup(dictionary=dict)
+
+ self.disableLogChannelsForCurrentTest()
+
+ # =========================================================
+ # Various callbacks to allow introspection of test progress
+ # =========================================================
+
+ def markError(self):
+ """Callback invoked when an error (unexpected exception) errored."""
+ self.__errored__ = True
+ with recording(self, False) as sbuf:
+ # False because there's no need to write "ERROR" to the stderr twice.
+ # Once by the Python unittest framework, and a second time by us.
+ print("ERROR", file=sbuf)
+
+ def markCleanupError(self):
+ """Callback invoked when an error occurs while a test is cleaning up."""
+ self.__cleanup_errored__ = True
+ with recording(self, False) as sbuf:
+ # False because there's no need to write "CLEANUP_ERROR" to the stderr twice.
+ # Once by the Python unittest framework, and a second time by us.
+ print("CLEANUP_ERROR", file=sbuf)
+
+ def markFailure(self):
+ """Callback invoked when a failure (test assertion failure) occurred."""
+ self.__failed__ = True
+ with recording(self, False) as sbuf:
+ # False because there's no need to write "FAIL" to the stderr twice.
+ # Once by the Python unittest framework, and a second time by us.
+ print("FAIL", file=sbuf)
+
+ def markExpectedFailure(self,err,bugnumber):
+ """Callback invoked when an expected failure/error occurred."""
+ self.__expected__ = True
+ with recording(self, False) as sbuf:
+ # False because there's no need to write "expected failure" to the
+ # stderr twice.
+ # Once by the Python unittest framework, and a second time by us.
+ if bugnumber == None:
+ print("expected failure", file=sbuf)
+ else:
+ print("expected failure (problem id:" + str(bugnumber) + ")", file=sbuf)
+
+ def markSkippedTest(self):
+ """Callback invoked when a test is skipped."""
+ self.__skipped__ = True
+ with recording(self, False) as sbuf:
+ # False because there's no need to write "skipped test" to the
+ # stderr twice.
+ # Once by the Python unittest framework, and a second time by us.
+ print("skipped test", file=sbuf)
+
+ def markUnexpectedSuccess(self, bugnumber):
+ """Callback invoked when an unexpected success occurred."""
+ self.__unexpected__ = True
+ with recording(self, False) as sbuf:
+ # False because there's no need to write "unexpected success" to the
+ # stderr twice.
+ # Once by the Python unittest framework, and a second time by us.
+ if bugnumber == None:
+ print("unexpected success", file=sbuf)
+ else:
+ print("unexpected success (problem id:" + str(bugnumber) + ")", file=sbuf)
+
+ def getRerunArgs(self):
+ return " -f %s.%s" % (self.__class__.__name__, self._testMethodName)
+
+ def getLogBasenameForCurrentTest(self, prefix=None):
+ """
+ returns a partial path that can be used as the beginning of the name of multiple
+ log files pertaining to this test
+
+ <session-dir>/<arch>-<compiler>-<test-file>.<test-class>.<test-method>
+ """
+ dname = os.path.join(os.environ["LLDB_TEST"],
+ os.environ["LLDB_SESSION_DIRNAME"])
+ if not os.path.isdir(dname):
+ os.mkdir(dname)
+
+ compiler = self.getCompiler()
+
+ if compiler[1] == ':':
+ compiler = compiler[2:]
+ if os.path.altsep is not None:
+ compiler = compiler.replace(os.path.altsep, os.path.sep)
+
+ fname = "{}-{}-{}".format(self.id(), self.getArchitecture(), "_".join(compiler.split(os.path.sep)))
+ if len(fname) > 200:
+ fname = "{}-{}-{}".format(self.id(), self.getArchitecture(), compiler.split(os.path.sep)[-1])
+
+ if prefix is not None:
+ fname = "{}-{}".format(prefix, fname)
+
+ return os.path.join(dname, fname)
+
+ def dumpSessionInfo(self):
+ """
+ Dump the debugger interactions leading to a test error/failure. This
+ allows for more convenient postmortem analysis.
+
+ See also LLDBTestResult (dotest.py) which is a singlton class derived
+ from TextTestResult and overwrites addError, addFailure, and
+ addExpectedFailure methods to allow us to to mark the test instance as
+ such.
+ """
+
+ # We are here because self.tearDown() detected that this test instance
+ # either errored or failed. The lldb.test_result singleton contains
+ # two lists (erros and failures) which get populated by the unittest
+ # framework. Look over there for stack trace information.
+ #
+ # The lists contain 2-tuples of TestCase instances and strings holding
+ # formatted tracebacks.
+ #
+ # See http://docs.python.org/library/unittest.html#unittest.TestResult.
+
+ # output tracebacks into session
+ pairs = []
+ if self.__errored__:
+ pairs = configuration.test_result.errors
+ prefix = 'Error'
+ elif self.__cleanup_errored__:
+ pairs = configuration.test_result.cleanup_errors
+ prefix = 'CleanupError'
+ elif self.__failed__:
+ pairs = configuration.test_result.failures
+ prefix = 'Failure'
+ elif self.__expected__:
+ pairs = configuration.test_result.expectedFailures
+ prefix = 'ExpectedFailure'
+ elif self.__skipped__:
+ prefix = 'SkippedTest'
+ elif self.__unexpected__:
+ prefix = 'UnexpectedSuccess'
+ else:
+ prefix = 'Success'
+
+ if not self.__unexpected__ and not self.__skipped__:
+ for test, traceback in pairs:
+ if test is self:
+ print(traceback, file=self.session)
+
+ # put footer (timestamp/rerun instructions) into session
+ testMethod = getattr(self, self._testMethodName)
+ if getattr(testMethod, "__benchmarks_test__", False):
+ benchmarks = True
+ else:
+ benchmarks = False
+
+ import datetime
+ print("Session info generated @", datetime.datetime.now().ctime(), file=self.session)
+ print("To rerun this test, issue the following command from the 'test' directory:\n", file=self.session)
+ print("./dotest.py %s -v %s %s" % (self.getRunOptions(),
+ ('+b' if benchmarks else '-t'),
+ self.getRerunArgs()), file=self.session)
+ self.session.close()
+ del self.session
+
+ # process the log files
+ log_files_for_this_test = glob.glob(self.log_basename + "*")
+
+ if prefix != 'Success' or lldbtest_config.log_success:
+ # keep all log files, rename them to include prefix
+ dst_log_basename = self.getLogBasenameForCurrentTest(prefix)
+ for src in log_files_for_this_test:
+ if os.path.isfile(src):
+ dst = src.replace(self.log_basename, dst_log_basename)
+ if os.name == "nt" and os.path.isfile(dst):
+ # On Windows, renaming a -> b will throw an exception if b exists. On non-Windows platforms
+ # it silently replaces the destination. Ultimately this means that atomic renames are not
+ # guaranteed to be possible on Windows, but we need this to work anyway, so just remove the
+ # destination first if it already exists.
+ os.remove(dst)
+
+ os.rename(src, dst)
+ else:
+ # success! (and we don't want log files) delete log files
+ for log_file in log_files_for_this_test:
+ try:
+ os.unlink(log_file)
+ except:
+ # We've seen consistent unlink failures on Windows, perhaps because the
+ # just-created log file is being scanned by anti-virus. Empirically, this
+ # sleep-and-retry approach allows tests to succeed much more reliably.
+ # Attempts to figure out exactly what process was still holding a file handle
+ # have failed because running instrumentation like Process Monitor seems to
+ # slow things down enough that the problem becomes much less consistent.
+ time.sleep(0.5)
+ os.unlink(log_file)
+
+ # ====================================================
+ # Config. methods supported through a plugin interface
+ # (enables reading of the current test configuration)
+ # ====================================================
+
+ def getArchitecture(self):
+ """Returns the architecture in effect the test suite is running with."""
+ module = builder_module()
+ arch = module.getArchitecture()
+ if arch == 'amd64':
+ arch = 'x86_64'
+ return arch
+
+ def getLldbArchitecture(self):
+ """Returns the architecture of the lldb binary."""
+ if not hasattr(self, 'lldbArchitecture'):
+
+ # spawn local process
+ command = [
+ lldbtest_config.lldbExec,
+ "-o",
+ "file " + lldbtest_config.lldbExec,
+ "-o",
+ "quit"
+ ]
+
+ output = check_output(command)
+ str = output.decode("utf-8");
+
+ for line in str.splitlines():
+ m = re.search("Current executable set to '.*' \\((.*)\\)\\.", line)
+ if m:
+ self.lldbArchitecture = m.group(1)
+ break
+
+ return self.lldbArchitecture
+
+ def getCompiler(self):
+ """Returns the compiler in effect the test suite is running with."""
+ module = builder_module()
+ return module.getCompiler()
+
+ def getCompilerBinary(self):
+ """Returns the compiler binary the test suite is running with."""
+ return self.getCompiler().split()[0]
+
+ def getCompilerVersion(self):
+ """ Returns a string that represents the compiler version.
+ Supports: llvm, clang.
+ """
+ from .lldbutil import which
+ version = 'unknown'
+
+ compiler = self.getCompilerBinary()
+ version_output = system([[which(compiler), "-v"]])[1]
+ for line in version_output.split(os.linesep):
+ m = re.search('version ([0-9\.]+)', line)
+ if m:
+ version = m.group(1)
+ return version
+
+ def getGoCompilerVersion(self):
+ """ Returns a string that represents the go compiler version, or None if go is not found.
+ """
+ compiler = which("go")
+ if compiler:
+ version_output = system([[compiler, "version"]])[0]
+ for line in version_output.split(os.linesep):
+ m = re.search('go version (devel|go\\S+)', line)
+ if m:
+ return m.group(1)
+ return None
+
+ def platformIsDarwin(self):
+ """Returns true if the OS triple for the selected platform is any valid apple OS"""
+ return platformIsDarwin()
+
+ def getPlatform(self):
+ """Returns the target platform the test suite is running on."""
+ return getPlatform()
+
+ def isIntelCompiler(self):
+ """ Returns true if using an Intel (ICC) compiler, false otherwise. """
+ return any([x in self.getCompiler() for x in ["icc", "icpc", "icl"]])
+
+ def expectedCompilerVersion(self, compiler_version):
+ """Returns True iff compiler_version[1] matches the current compiler version.
+ Use compiler_version[0] to specify the operator used to determine if a match has occurred.
+ Any operator other than the following defaults to an equality test:
+ '>', '>=', "=>", '<', '<=', '=<', '!=', "!" or 'not'
+ """
+ if (compiler_version == None):
+ return True
+ operator = str(compiler_version[0])
+ version = compiler_version[1]
+
+ if (version == None):
+ return True
+ if (operator == '>'):
+ return self.getCompilerVersion() > version
+ if (operator == '>=' or operator == '=>'):
+ return self.getCompilerVersion() >= version
+ if (operator == '<'):
+ return self.getCompilerVersion() < version
+ if (operator == '<=' or operator == '=<'):
+ return self.getCompilerVersion() <= version
+ if (operator == '!=' or operator == '!' or operator == 'not'):
+ return str(version) not in str(self.getCompilerVersion())
+ return str(version) in str(self.getCompilerVersion())
+
+ def expectedCompiler(self, compilers):
+ """Returns True iff any element of compilers is a sub-string of the current compiler."""
+ if (compilers == None):
+ return True
+
+ for compiler in compilers:
+ if compiler in self.getCompiler():
+ return True
+
+ return False
+
+ def expectedArch(self, archs):
+ """Returns True iff any element of archs is a sub-string of the current architecture."""
+ if (archs == None):
+ return True
+
+ for arch in archs:
+ if arch in self.getArchitecture():
+ return True
+
+ return False
+
+ def getRunOptions(self):
+ """Command line option for -A and -C to run this test again, called from
+ self.dumpSessionInfo()."""
+ arch = self.getArchitecture()
+ comp = self.getCompiler()
+ if arch:
+ option_str = "-A " + arch
+ else:
+ option_str = ""
+ if comp:
+ option_str += " -C " + comp
+ return option_str
+
+ # ==================================================
+ # Build methods supported through a plugin interface
+ # ==================================================
+
+ def getstdlibFlag(self):
+ """ Returns the proper -stdlib flag, or empty if not required."""
+ if self.platformIsDarwin() or self.getPlatform() == "freebsd":
+ stdlibflag = "-stdlib=libc++"
+ else: # this includes NetBSD
+ stdlibflag = ""
+ return stdlibflag
+
+ def getstdFlag(self):
+ """ Returns the proper stdflag. """
+ if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
+ stdflag = "-std=c++0x"
+ else:
+ stdflag = "-std=c++11"
+ return stdflag
+
+ def buildDriver(self, sources, exe_name):
+ """ Platform-specific way to build a program that links with LLDB (via the liblldb.so
+ or LLDB.framework).
+ """
+
+ stdflag = self.getstdFlag()
+ stdlibflag = self.getstdlibFlag()
+
+ lib_dir = os.environ["LLDB_LIB_DIR"]
+ if sys.platform.startswith("darwin"):
+ dsym = os.path.join(lib_dir, 'LLDB.framework', 'LLDB')
+ d = {'CXX_SOURCES' : sources,
+ 'EXE' : exe_name,
+ 'CFLAGS_EXTRAS' : "%s %s" % (stdflag, stdlibflag),
+ 'FRAMEWORK_INCLUDES' : "-F%s" % lib_dir,
+ 'LD_EXTRAS' : "%s -Wl,-rpath,%s" % (dsym, lib_dir),
+ }
+ elif sys.platform.rstrip('0123456789') in ('freebsd', 'linux', 'netbsd') or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
+ d = {'CXX_SOURCES' : sources,
+ 'EXE' : exe_name,
+ 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
+ 'LD_EXTRAS' : "-L%s -llldb" % lib_dir}
+ elif sys.platform.startswith('win'):
+ d = {'CXX_SOURCES' : sources,
+ 'EXE' : exe_name,
+ 'CFLAGS_EXTRAS' : "%s %s -I%s" % (stdflag, stdlibflag, os.path.join(os.environ["LLDB_SRC"], "include")),
+ 'LD_EXTRAS' : "-L%s -lliblldb" % os.environ["LLDB_IMPLIB_DIR"]}
+ if self.TraceOn():
+ print("Building LLDB Driver (%s) from sources %s" % (exe_name, sources))
+
+ self.buildDefault(dictionary=d)
+
+ def buildLibrary(self, sources, lib_name):
+ """Platform specific way to build a default library. """
+
+ stdflag = self.getstdFlag()
+
+ lib_dir = os.environ["LLDB_LIB_DIR"]
+ if self.platformIsDarwin():
+ dsym = os.path.join(lib_dir, 'LLDB.framework', 'LLDB')
+ d = {'DYLIB_CXX_SOURCES' : sources,
+ 'DYLIB_NAME' : lib_name,
+ 'CFLAGS_EXTRAS' : "%s -stdlib=libc++" % stdflag,
+ 'FRAMEWORK_INCLUDES' : "-F%s" % lib_dir,
+ 'LD_EXTRAS' : "%s -Wl,-rpath,%s -dynamiclib" % (dsym, lib_dir),
+ }
+ elif self.getPlatform() in ('freebsd', 'linux', 'netbsd') or os.environ.get('LLDB_BUILD_TYPE') == 'Makefile':
+ d = {'DYLIB_CXX_SOURCES' : sources,
+ 'DYLIB_NAME' : lib_name,
+ 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
+ 'LD_EXTRAS' : "-shared -L%s -llldb" % lib_dir}
+ elif self.getPlatform() == 'windows':
+ d = {'DYLIB_CXX_SOURCES' : sources,
+ 'DYLIB_NAME' : lib_name,
+ 'CFLAGS_EXTRAS' : "%s -I%s -fPIC" % (stdflag, os.path.join(os.environ["LLDB_SRC"], "include")),
+ 'LD_EXTRAS' : "-shared -l%s\liblldb.lib" % self.os.environ["LLDB_IMPLIB_DIR"]}
+ if self.TraceOn():
+ print("Building LLDB Library (%s) from sources %s" % (lib_name, sources))
+
+ self.buildDefault(dictionary=d)
+
+ def buildProgram(self, sources, exe_name):
+ """ Platform specific way to build an executable from C/C++ sources. """
+ d = {'CXX_SOURCES' : sources,
+ 'EXE' : exe_name}
+ self.buildDefault(dictionary=d)
+
+ def buildDefault(self, architecture=None, compiler=None, dictionary=None, clean=True):
+ """Platform specific way to build the default binaries."""
+ module = builder_module()
+ if target_is_android():
+ dictionary = append_android_envs(dictionary)
+ if not module.buildDefault(self, architecture, compiler, dictionary, clean):
+ raise Exception("Don't know how to build default binary")
+
+ def buildDsym(self, architecture=None, compiler=None, dictionary=None, clean=True):
+ """Platform specific way to build binaries with dsym info."""
+ module = builder_module()
+ if not module.buildDsym(self, architecture, compiler, dictionary, clean):
+ raise Exception("Don't know how to build binary with dsym")
+
+ def buildDwarf(self, architecture=None, compiler=None, dictionary=None, clean=True):
+ """Platform specific way to build binaries with dwarf maps."""
+ module = builder_module()
+ if target_is_android():
+ dictionary = append_android_envs(dictionary)
+ if not module.buildDwarf(self, architecture, compiler, dictionary, clean):
+ raise Exception("Don't know how to build binary with dwarf")
+
+ def buildDwo(self, architecture=None, compiler=None, dictionary=None, clean=True):
+ """Platform specific way to build binaries with dwarf maps."""
+ module = builder_module()
+ if target_is_android():
+ dictionary = append_android_envs(dictionary)
+ if not module.buildDwo(self, architecture, compiler, dictionary, clean):
+ raise Exception("Don't know how to build binary with dwo")
+
+ def buildGo(self):
+ """Build the default go binary.
+ """
+ system([[which('go'), 'build -gcflags "-N -l" -o a.out main.go']])
+
+ def signBinary(self, binary_path):
+ if sys.platform.startswith("darwin"):
+ codesign_cmd = "codesign --force --sign lldb_codesign %s" % (binary_path)
+ call(codesign_cmd, shell=True)
+
+ def findBuiltClang(self):
+ """Tries to find and use Clang from the build directory as the compiler (instead of the system compiler)."""
+ paths_to_try = [
+ "llvm-build/Release+Asserts/x86_64/Release+Asserts/bin/clang",
+ "llvm-build/Debug+Asserts/x86_64/Debug+Asserts/bin/clang",
+ "llvm-build/Release/x86_64/Release/bin/clang",
+ "llvm-build/Debug/x86_64/Debug/bin/clang",
+ ]
+ lldb_root_path = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..")
+ for p in paths_to_try:
+ path = os.path.join(lldb_root_path, p)
+ if os.path.exists(path):
+ return path
+
+ # Tries to find clang at the same folder as the lldb
+ path = os.path.join(os.path.dirname(lldbtest_config.lldbExec), "clang")
+ if os.path.exists(path):
+ return path
+
+ return os.environ["CC"]
+
+ def getBuildFlags(self, use_cpp11=True, use_libcxx=False, use_libstdcxx=False):
+ """ Returns a dictionary (which can be provided to build* functions above) which
+ contains OS-specific build flags.
+ """
+ cflags = ""
+ ldflags = ""
+
+ # On Mac OS X, unless specifically requested to use libstdc++, use libc++
+ if not use_libstdcxx and self.platformIsDarwin():
+ use_libcxx = True
+
+ if use_libcxx and self.libcxxPath:
+ cflags += "-stdlib=libc++ "
+ if self.libcxxPath:
+ libcxxInclude = os.path.join(self.libcxxPath, "include")
+ libcxxLib = os.path.join(self.libcxxPath, "lib")
+ if os.path.isdir(libcxxInclude) and os.path.isdir(libcxxLib):
+ cflags += "-nostdinc++ -I%s -L%s -Wl,-rpath,%s " % (libcxxInclude, libcxxLib, libcxxLib)
+
+ if use_cpp11:
+ cflags += "-std="
+ if "gcc" in self.getCompiler() and "4.6" in self.getCompilerVersion():
+ cflags += "c++0x"
+ else:
+ cflags += "c++11"
+ if self.platformIsDarwin() or self.getPlatform() == "freebsd":
+ cflags += " -stdlib=libc++"
+ elif self.getPlatform() == "netbsd":
+ cflags += " -stdlib=libstdc++"
+ elif "clang" in self.getCompiler():
+ cflags += " -stdlib=libstdc++"
+
+ return {'CFLAGS_EXTRAS' : cflags,
+ 'LD_EXTRAS' : ldflags,
+ }
+
+ def cleanup(self, dictionary=None):
+ """Platform specific way to do cleanup after build."""
+ module = builder_module()
+ if not module.cleanup(self, dictionary):
+ raise Exception("Don't know how to do cleanup with dictionary: "+dictionary)
+
+ def getLLDBLibraryEnvVal(self):
+ """ Returns the path that the OS-specific library search environment variable
+ (self.dylibPath) should be set to in order for a program to find the LLDB
+ library. If an environment variable named self.dylibPath is already set,
+ the new path is appended to it and returned.
+ """
+ existing_library_path = os.environ[self.dylibPath] if self.dylibPath in os.environ else None
+ lib_dir = os.environ["LLDB_LIB_DIR"]
+ if existing_library_path:
+ return "%s:%s" % (existing_library_path, lib_dir)
+ elif sys.platform.startswith("darwin"):
+ return os.path.join(lib_dir, 'LLDB.framework')
+ else:
+ return lib_dir
+
+ def getLibcPlusPlusLibs(self):
+ if self.getPlatform() in ('freebsd', 'linux', 'netbsd'):
+ return ['libc++.so.1']
+ else:
+ return ['libc++.1.dylib','libc++abi.dylib']
+
+# Metaclass for TestBase to change the list of test metods when a new TestCase is loaded.
+# We change the test methods to create a new test method for each test for each debug info we are
+# testing. The name of the new test method will be '<original-name>_<debug-info>' and with adding
+# the new test method we remove the old method at the same time.
+class LLDBTestCaseFactory(type):
+ def __new__(cls, name, bases, attrs):
+ newattrs = {}
+ for attrname, attrvalue in attrs.items():
+ if attrname.startswith("test") and not getattr(attrvalue, "__no_debug_info_test__", False):
+ target_platform = lldb.DBG.GetSelectedPlatform().GetTriple().split('-')[2]
+
+ # If any debug info categories were explicitly tagged, assume that list to be
+ # authoritative. If none were specified, try with all debug info formats.
+ all_dbginfo_categories = set(test_categories.debug_info_categories)
+ categories = set(getattr(attrvalue, "categories", [])) & all_dbginfo_categories
+ if not categories:
+ categories = all_dbginfo_categories
+
+ supported_categories = [x for x in categories
+ if test_categories.is_supported_on_platform(x, target_platform)]
+ if "dsym" in supported_categories:
+ @add_test_categories(["dsym"])
+ @wraps(attrvalue)
+ def dsym_test_method(self, attrvalue=attrvalue):
+ self.debug_info = "dsym"
+ return attrvalue(self)
+ dsym_method_name = attrname + "_dsym"
+ dsym_test_method.__name__ = dsym_method_name
+ newattrs[dsym_method_name] = dsym_test_method
+
+ if "dwarf" in supported_categories:
+ @add_test_categories(["dwarf"])
+ @wraps(attrvalue)
+ def dwarf_test_method(self, attrvalue=attrvalue):
+ self.debug_info = "dwarf"
+ return attrvalue(self)
+ dwarf_method_name = attrname + "_dwarf"
+ dwarf_test_method.__name__ = dwarf_method_name
+ newattrs[dwarf_method_name] = dwarf_test_method
+
+ if "dwo" in supported_categories:
+ @add_test_categories(["dwo"])
+ @wraps(attrvalue)
+ def dwo_test_method(self, attrvalue=attrvalue):
+ self.debug_info = "dwo"
+ return attrvalue(self)
+ dwo_method_name = attrname + "_dwo"
+ dwo_test_method.__name__ = dwo_method_name
+ newattrs[dwo_method_name] = dwo_test_method
+ else:
+ newattrs[attrname] = attrvalue
+ return super(LLDBTestCaseFactory, cls).__new__(cls, name, bases, newattrs)
+
+# Setup the metaclass for this class to change the list of the test methods when a new class is loaded
+@add_metaclass(LLDBTestCaseFactory)
+class TestBase(Base):
+ """
+ This abstract base class is meant to be subclassed. It provides default
+ implementations for setUpClass(), tearDownClass(), setUp(), and tearDown(),
+ among other things.
+
+ Important things for test class writers:
+
+ - Overwrite the mydir class attribute, otherwise your test class won't
+ run. It specifies the relative directory to the top level 'test' so
+ the test harness can change to the correct working directory before
+ running your test.
+
+ - The setUp method sets up things to facilitate subsequent interactions
+ with the debugger as part of the test. These include:
+ - populate the test method name
+ - create/get a debugger set with synchronous mode (self.dbg)
+ - get the command interpreter from with the debugger (self.ci)
+ - create a result object for use with the command interpreter
+ (self.res)
+ - plus other stuffs
+
+ - The tearDown method tries to perform some necessary cleanup on behalf
+ of the test to return the debugger to a good state for the next test.
+ These include:
+ - execute any tearDown hooks registered by the test method with
+ TestBase.addTearDownHook(); examples can be found in
+ settings/TestSettings.py
+ - kill the inferior process associated with each target, if any,
+ and, then delete the target from the debugger's target list
+ - perform build cleanup before running the next test method in the
+ same test class; examples of registering for this service can be
+ found in types/TestIntegerTypes.py with the call:
+ - self.setTearDownCleanup(dictionary=d)
+
+ - Similarly setUpClass and tearDownClass perform classwise setup and
+ teardown fixtures. The tearDownClass method invokes a default build
+ cleanup for the entire test class; also, subclasses can implement the
+ classmethod classCleanup(cls) to perform special class cleanup action.
+
+ - The instance methods runCmd and expect are used heavily by existing
+ test cases to send a command to the command interpreter and to perform
+ string/pattern matching on the output of such command execution. The
+ expect method also provides a mode to peform string/pattern matching
+ without running a command.
+
+ - The build methods buildDefault, buildDsym, and buildDwarf are used to
+ build the binaries used during a particular test scenario. A plugin
+ should be provided for the sys.platform running the test suite. The
+ Mac OS X implementation is located in plugins/darwin.py.
+ """
+
+ # Maximum allowed attempts when launching the inferior process.
+ # Can be overridden by the LLDB_MAX_LAUNCH_COUNT environment variable.
+ maxLaunchCount = 3;
+
+ # 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;
+
+ # Returns the list of categories to which this test case belongs
+ # by default, look for a ".categories" file, and read its contents
+ # if no such file exists, traverse the hierarchy - we guarantee
+ # a .categories to exist at the top level directory so we do not end up
+ # looping endlessly - subclasses are free to define their own categories
+ # in whatever way makes sense to them
+ def getCategories(self):
+ import inspect
+ import os.path
+ folder = inspect.getfile(self.__class__)
+ folder = os.path.dirname(folder)
+ while folder != '/':
+ categories_file_name = os.path.join(folder,".categories")
+ if os.path.exists(categories_file_name):
+ categories_file = open(categories_file_name,'r')
+ categories = categories_file.readline()
+ categories_file.close()
+ categories = str.replace(categories,'\n','')
+ categories = str.replace(categories,'\r','')
+ return categories.split(',')
+ else:
+ folder = os.path.dirname(folder)
+ continue
+
+ def setUp(self):
+ #import traceback
+ #traceback.print_stack()
+
+ # Works with the test driver to conditionally skip tests via decorators.
+ Base.setUp(self)
+
+ 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"])
+
+ # We want our debugger to be synchronous.
+ self.dbg.SetAsync(False)
+
+ # 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()
+
+ if lldb.remote_platform and configuration.lldb_platform_working_dir:
+ remote_test_dir = lldbutil.join_remote_paths(
+ configuration.lldb_platform_working_dir,
+ self.getArchitecture(),
+ str(self.test_number),
+ self.mydir)
+ error = lldb.remote_platform.MakeDirectory(remote_test_dir, 448) # 448 = 0o700
+ if error.Success():
+ lldb.remote_platform.SetWorkingDirectory(remote_test_dir)
+
+ # This function removes all files from the current working directory while leaving
+ # the directories in place. The cleaup is required to reduce the disk space required
+ # by the test suit while leaving the directories untached 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)
+ else:
+ print("error: making remote directory '%s': %s" % (remote_test_dir, error))
+
+ def registerSharedLibrariesWithTarget(self, target, shlibs):
+ '''If we are remotely running the test suite, register the shared libraries with the target so they get uploaded, otherwise do nothing
+
+ Any modules in the target that have their remote install file specification set will
+ get uploaded to the remote host. This function registers the local copies of the
+ shared libraries with the target and sets their remote install locations so they will
+ be uploaded when the target is run.
+ '''
+ if not shlibs or not self.platformContext:
+ return None
+
+ shlib_environment_var = self.platformContext.shlib_environment_var
+ shlib_prefix = self.platformContext.shlib_prefix
+ shlib_extension = '.' + self.platformContext.shlib_extension
+
+ working_dir = self.get_process_working_directory()
+ environment = ['%s=%s' % (shlib_environment_var, working_dir)]
+ # Add any shared libraries to our target if remote so they get
+ # uploaded into the working directory on the remote side
+ for name in shlibs:
+ # The path can be a full path to a shared library, or a make file name like "Foo" for
+ # "libFoo.dylib" or "libFoo.so", or "Foo.so" for "Foo.so" or "libFoo.so", or just a
+ # basename like "libFoo.so". So figure out which one it is and resolve the local copy
+ # of the shared library accordingly
+ if os.path.exists(name):
+ local_shlib_path = name # name is the full path to the local shared library
+ else:
+ # Check relative names
+ local_shlib_path = os.path.join(os.getcwd(), shlib_prefix + name + shlib_extension)
+ if not os.path.exists(local_shlib_path):
+ local_shlib_path = os.path.join(os.getcwd(), name + shlib_extension)
+ if not os.path.exists(local_shlib_path):
+ local_shlib_path = os.path.join(os.getcwd(), name)
+
+ # Make sure we found the local shared library in the above code
+ self.assertTrue(os.path.exists(local_shlib_path))
+
+ # Add the shared library to our target
+ shlib_module = target.AddModule(local_shlib_path, None, None, None)
+ if lldb.remote_platform:
+ # We must set the remote install location if we want the shared library
+ # to get uploaded to the remote target
+ remote_shlib_path = lldbutil.append_to_process_working_directory(os.path.basename(local_shlib_path))
+ shlib_module.SetRemoteInstallFileSpec(lldb.SBFileSpec(remote_shlib_path, False))
+
+ return environment
+
+ # utility methods that tests can use to access the current objects
+ def target(self):
+ if not self.dbg:
+ raise Exception('Invalid debugger instance')
+ return self.dbg.GetSelectedTarget()
+
+ def process(self):
+ if not self.dbg:
+ raise Exception('Invalid debugger instance')
+ return self.dbg.GetSelectedTarget().GetProcess()
+
+ def thread(self):
+ if not self.dbg:
+ raise Exception('Invalid debugger instance')
+ return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread()
+
+ def frame(self):
+ if not self.dbg:
+ raise Exception('Invalid debugger instance')
+ return self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame()
+
+ def get_process_working_directory(self):
+ '''Get the working directory that should be used when launching processes for local or remote processes.'''
+ if lldb.remote_platform:
+ # Remote tests set the platform working directory up in TestBase.setUp()
+ return lldb.remote_platform.GetWorkingDirectory()
+ else:
+ # local tests change directory into each test subdirectory
+ return os.getcwd()
+
+ def tearDown(self):
+ #import traceback
+ #traceback.print_stack()
+
+ # Ensure all the references to SB objects have gone away so that we can
+ # be sure that all test-specific resources have been freed before we
+ # attempt to delete the targets.
+ gc.collect()
+
+ # Delete the target(s) from the debugger as a general cleanup step.
+ # This includes terminating the process for each target, if any.
+ # We'd like to reuse the debugger for our next test without incurring
+ # the initialization overhead.
+ targets = []
+ for target in self.dbg:
+ if target:
+ targets.append(target)
+ process = target.GetProcess()
+ if process:
+ rc = self.invoke(process, "Kill")
+ self.assertTrue(rc.Success(), PROCESS_KILLED)
+ for target in targets:
+ self.dbg.DeleteTarget(target)
+
+ # Do this last, to make sure it's in reverse order from how we setup.
+ Base.tearDown(self)
+
+ # This must be the last statement, otherwise teardown hooks or other
+ # lines might depend on this still being active.
+ del self.dbg
+
+ def switch_to_thread_with_stop_reason(self, stop_reason):
+ """
+ Run the 'thread list' command, and select the thread with stop reason as
+ 'stop_reason'. If no such thread exists, no select action is done.
+ """
+ from .lldbutil import stop_reason_to_str
+ self.runCmd('thread list')
+ output = self.res.GetOutput()
+ thread_line_pattern = re.compile("^[ *] thread #([0-9]+):.*stop reason = %s" %
+ stop_reason_to_str(stop_reason))
+ for line in output.splitlines():
+ matched = thread_line_pattern.match(line)
+ if matched:
+ self.runCmd('thread select %s' % matched.group(1))
+
+ 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 not cmd or len(cmd) == 0:
+ 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):
+ self.ci.HandleCommand(cmd, self.res, inHistory)
+
+ with recording(self, trace) as sbuf:
+ print("runCmd:", cmd, file=sbuf)
+ if not check:
+ print("check of return status not required", file=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:
+ self.assertTrue(self.res.Succeeded(),
+ msg if msg else CMD_MSG(cmd))
+
+ def match (self, str, patterns, msg=None, trace=False, error=False, matching=True, exe=True):
+ """run command in str, and match the result against regexp in patterns returning the match object for the first matching pattern
+
+ Otherwise, all the arguments have the same meanings as for the expect function"""
+
+ trace = (True if traceAlways else trace)
+
+ if exe:
+ # First run the command. If we are expecting error, set check=False.
+ # Pass the assert message along since it provides more semantic info.
+ self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error)
+
+ # Then compare the output against expected strings.
+ output = self.res.GetError() if error else self.res.GetOutput()
+
+ # If error is True, the API client expects the command to fail!
+ if error:
+ self.assertFalse(self.res.Succeeded(),
+ "Command '" + str + "' is expected to fail!")
+ else:
+ # No execution required, just compare str against the golden input.
+ output = str
+ with recording(self, trace) as sbuf:
+ print("looking at:", output, file=sbuf)
+
+ # The heading says either "Expecting" or "Not expecting".
+ heading = "Expecting" if matching else "Not expecting"
+
+ for pattern in patterns:
+ # Match Objects always have a boolean value of True.
+ match_object = re.search(pattern, output)
+ matched = bool(match_object)
+ with recording(self, trace) as sbuf:
+ print("%s pattern: %s" % (heading, pattern), file=sbuf)
+ print("Matched" if matched else "Not matched", file=sbuf)
+ if matched:
+ break
+
+ self.assertTrue(matched if matching else not matched,
+ msg if msg else EXP_MSG(str, exe))
+
+ return match_object
+
+ def expect(self, str, msg=None, patterns=None, startstr=None, endstr=None, substrs=None, trace=False, error=False, matching=True, exe=True, inHistory=False):
+ """
+ Similar to runCmd; with additional expect style output matching ability.
+
+ Ask the command interpreter to handle the command and then check its
+ return status. The 'msg' parameter specifies an informational assert
+ message. We expect the output from running the command to start with
+ 'startstr', matches the substrings contained in 'substrs', and regexp
+ matches the patterns contained in 'patterns'.
+
+ If the keyword argument error is set to True, it signifies that the API
+ client is expecting the command to fail. In this case, the error stream
+ from running the command is retrieved and compared against the golden
+ input, instead.
+
+ If the keyword argument matching is set to False, it signifies that the API
+ client is expecting the output of the command not to match the golden
+ input.
+
+ Finally, the required argument 'str' represents the lldb command to be
+ sent to the command interpreter. In case the keyword argument 'exe' is
+ set to False, the 'str' is treated as a string to be matched/not-matched
+ against the golden input.
+ """
+ trace = (True if traceAlways else trace)
+
+ if exe:
+ # First run the command. If we are expecting error, set check=False.
+ # Pass the assert message along since it provides more semantic info.
+ self.runCmd(str, msg=msg, trace = (True if trace else False), check = not error, inHistory=inHistory)
+
+ # Then compare the output against expected strings.
+ output = self.res.GetError() if error else self.res.GetOutput()
+
+ # If error is True, the API client expects the command to fail!
+ if error:
+ self.assertFalse(self.res.Succeeded(),
+ "Command '" + str + "' is expected to fail!")
+ else:
+ # No execution required, just compare str against the golden input.
+ if isinstance(str,lldb.SBCommandReturnObject):
+ output = str.GetOutput()
+ else:
+ output = str
+ with recording(self, trace) as sbuf:
+ print("looking at:", output, file=sbuf)
+
+ # The heading says either "Expecting" or "Not expecting".
+ heading = "Expecting" if matching else "Not expecting"
+
+ # Start from the startstr, if specified.
+ # If there's no startstr, set the initial state appropriately.
+ matched = output.startswith(startstr) if startstr else (True if matching else False)
+
+ if startstr:
+ with recording(self, trace) as sbuf:
+ print("%s start string: %s" % (heading, startstr), file=sbuf)
+ print("Matched" if matched else "Not matched", file=sbuf)
+
+ # Look for endstr, if specified.
+ keepgoing = matched if matching else not matched
+ if endstr:
+ matched = output.endswith(endstr)
+ with recording(self, trace) as sbuf:
+ print("%s end string: %s" % (heading, endstr), file=sbuf)
+ print("Matched" if matched else "Not matched", file=sbuf)
+
+ # Look for sub strings, if specified.
+ keepgoing = matched if matching else not matched
+ if substrs and keepgoing:
+ for str in substrs:
+ matched = output.find(str) != -1
+ with recording(self, trace) as sbuf:
+ print("%s sub string: %s" % (heading, str), file=sbuf)
+ print("Matched" if matched else "Not matched", file=sbuf)
+ keepgoing = matched if matching else not matched
+ if not keepgoing:
+ break
+
+ # Search for regular expression patterns, if specified.
+ keepgoing = matched if matching else not matched
+ if patterns and keepgoing:
+ for pattern in patterns:
+ # Match Objects always have a boolean value of True.
+ matched = bool(re.search(pattern, output))
+ with recording(self, trace) as sbuf:
+ print("%s pattern: %s" % (heading, pattern), file=sbuf)
+ print("Matched" if matched else "Not matched", file=sbuf)
+ keepgoing = matched if matching else not matched
+ if not keepgoing:
+ break
+
+ self.assertTrue(matched if matching else not matched,
+ msg if msg else EXP_MSG(str, exe))
+
+ def invoke(self, obj, name, trace=False):
+ """Use reflection to call a method dynamically with no argument."""
+ trace = (True if traceAlways else trace)
+
+ method = getattr(obj, name)
+ import inspect
+ self.assertTrue(inspect.ismethod(method),
+ name + "is a method name of object: " + str(obj))
+ result = method()
+ with recording(self, trace) as sbuf:
+ print(str(method) + ":", result, file=sbuf)
+ return result
+
+ def build(self, architecture=None, compiler=None, dictionary=None, clean=True):
+ """Platform specific way to build the default binaries."""
+ module = builder_module()
+ if target_is_android():
+ dictionary = append_android_envs(dictionary)
+ if self.debug_info is None:
+ return self.buildDefault(architecture, compiler, dictionary, clean)
+ elif self.debug_info == "dsym":
+ return self.buildDsym(architecture, compiler, dictionary, clean)
+ elif self.debug_info == "dwarf":
+ return self.buildDwarf(architecture, compiler, dictionary, clean)
+ elif self.debug_info == "dwo":
+ return self.buildDwo(architecture, compiler, dictionary, clean)
+ else:
+ self.fail("Can't build for debug info: %s" % self.debug_info)
+
+ # =================================================
+ # Misc. helper methods for debugging test execution
+ # =================================================
+
+ def DebugSBValue(self, val):
+ """Debug print a SBValue object, if traceAlways is True."""
+ from .lldbutil import value_type_to_str
+
+ if not traceAlways:
+ return
+
+ err = sys.stderr
+ err.write(val.GetName() + ":\n")
+ err.write('\t' + "TypeName -> " + val.GetTypeName() + '\n')
+ err.write('\t' + "ByteSize -> " + str(val.GetByteSize()) + '\n')
+ err.write('\t' + "NumChildren -> " + str(val.GetNumChildren()) + '\n')
+ err.write('\t' + "Value -> " + str(val.GetValue()) + '\n')
+ err.write('\t' + "ValueAsUnsigned -> " + str(val.GetValueAsUnsigned())+ '\n')
+ err.write('\t' + "ValueType -> " + value_type_to_str(val.GetValueType()) + '\n')
+ err.write('\t' + "Summary -> " + str(val.GetSummary()) + '\n')
+ err.write('\t' + "IsPointerType -> " + str(val.TypeIsPointerType()) + '\n')
+ err.write('\t' + "Location -> " + val.GetLocation() + '\n')
+
+ def DebugSBType(self, type):
+ """Debug print a SBType object, if traceAlways is True."""
+ if not traceAlways:
+ return
+
+ err = sys.stderr
+ err.write(type.GetName() + ":\n")
+ err.write('\t' + "ByteSize -> " + str(type.GetByteSize()) + '\n')
+ err.write('\t' + "IsPointerType -> " + str(type.IsPointerType()) + '\n')
+ err.write('\t' + "IsReferenceType -> " + str(type.IsReferenceType()) + '\n')
+
+ def DebugPExpect(self, child):
+ """Debug the spwaned pexpect object."""
+ if not traceAlways:
+ return
+
+ print(child)
+
+ @classmethod
+ def RemoveTempFile(cls, file):
+ if os.path.exists(file):
+ os.remove(file)
diff --git a/packages/Python/lldbsuite/test/lldbtest_config.py b/packages/Python/lldbsuite/test/lldbtest_config.py
new file mode 100644
index 000000000000..c2d4549437b9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lldbtest_config.py
@@ -0,0 +1,21 @@
+"""
+ The LLVM Compiler Infrastructure
+
+ This file is distributed under the University of Illinois Open Source
+ License. See LICENSE.TXT for details.
+
+Configuration options for lldbtest.py set by dotest.py during initialization
+"""
+
+# array of strings
+# each string has the name of an lldb channel followed by
+# zero or more categories in that channel
+# ex. "gdb-remote packets"
+channels = []
+
+# leave logs/traces even for successful test runs
+log_success = False
+
+# path to the lldb command line executable tool
+lldbExec = None
+
diff --git a/packages/Python/lldbsuite/test/lldbutil.py b/packages/Python/lldbsuite/test/lldbutil.py
new file mode 100644
index 000000000000..339619dc4f74
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lldbutil.py
@@ -0,0 +1,1016 @@
+"""
+This LLDB module contains miscellaneous utilities.
+Some of the test suite takes advantage of the utility functions defined here.
+They can also be useful for general purpose lldb scripting.
+"""
+
+from __future__ import print_function
+from __future__ import absolute_import
+
+# System modules
+import collections
+import os
+import re
+import sys
+
+# Third-party modules
+from six import StringIO as SixStringIO
+import six
+
+# LLDB modules
+import lldb
+
+
+# ===================================================
+# Utilities for locating/checking executable programs
+# ===================================================
+
+def is_exe(fpath):
+ """Returns True if fpath is an executable."""
+ 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
+
+# ===================================================
+# Disassembly for an SBFunction or an SBSymbol object
+# ===================================================
+
+def disassemble(target, function_or_symbol):
+ """Disassemble the function or symbol given a target.
+
+ It returns the disassembly content in a string object.
+ """
+ buf = SixStringIO()
+ insts = function_or_symbol.GetInstructions(target)
+ for i in insts:
+ print(i, file=buf)
+ return buf.getvalue()
+
+# ==========================================================
+# Integer (byte size 1, 2, 4, and 8) to bytearray conversion
+# ==========================================================
+
+def int_to_bytearray(val, bytesize):
+ """Utility function to convert an integer into a bytearray.
+
+ It returns the bytearray in the little endian format. It is easy to get the
+ big endian format, just do ba.reverse() on the returned object.
+ """
+ import struct
+
+ if bytesize == 1:
+ return bytearray([val])
+
+ # Little endian followed by a format character.
+ template = "<%c"
+ if bytesize == 2:
+ fmt = template % 'h'
+ elif bytesize == 4:
+ fmt = template % 'i'
+ elif bytesize == 4:
+ fmt = template % 'q'
+ else:
+ return None
+
+ packed = struct.pack(fmt, val)
+ return bytearray(list(map(ord, packed)))
+
+def bytearray_to_int(bytes, bytesize):
+ """Utility function to convert a bytearray into an integer.
+
+ It interprets the bytearray in the little endian format. For a big endian
+ bytearray, just do ba.reverse() on the object before passing it in.
+ """
+ import struct
+
+ if bytesize == 1:
+ return bytes[0]
+
+ # Little endian followed by a format character.
+ template = "<%c"
+ if bytesize == 2:
+ fmt = template % 'h'
+ elif bytesize == 4:
+ fmt = template % 'i'
+ elif bytesize == 4:
+ fmt = template % 'q'
+ else:
+ return None
+
+ unpacked = struct.unpack(fmt, str(bytes))
+ return unpacked[0]
+
+
+# ==============================================================
+# Get the description of an lldb object or None if not available
+# ==============================================================
+def get_description(obj, option=None):
+ """Calls lldb_obj.GetDescription() and returns a string, or None.
+
+ For SBTarget, SBBreakpointLocation, and SBWatchpoint lldb objects, an extra
+ option can be passed in to describe the detailed level of description
+ desired:
+ o lldb.eDescriptionLevelBrief
+ o lldb.eDescriptionLevelFull
+ o lldb.eDescriptionLevelVerbose
+ """
+ method = getattr(obj, 'GetDescription')
+ if not method:
+ return None
+ tuple = (lldb.SBTarget, lldb.SBBreakpointLocation, lldb.SBWatchpoint)
+ if isinstance(obj, tuple):
+ if option is None:
+ option = lldb.eDescriptionLevelBrief
+
+ stream = lldb.SBStream()
+ if option is None:
+ success = method(stream)
+ else:
+ success = method(stream, option)
+ if not success:
+ return None
+ return stream.GetData()
+
+
+# =================================================
+# Convert some enum value to its string counterpart
+# =================================================
+
+def state_type_to_str(enum):
+ """Returns the stateType string given an enum."""
+ if enum == lldb.eStateInvalid:
+ return "invalid"
+ elif enum == lldb.eStateUnloaded:
+ return "unloaded"
+ elif enum == lldb.eStateConnected:
+ return "connected"
+ elif enum == lldb.eStateAttaching:
+ return "attaching"
+ elif enum == lldb.eStateLaunching:
+ return "launching"
+ elif enum == lldb.eStateStopped:
+ return "stopped"
+ elif enum == lldb.eStateRunning:
+ return "running"
+ elif enum == lldb.eStateStepping:
+ return "stepping"
+ elif enum == lldb.eStateCrashed:
+ return "crashed"
+ elif enum == lldb.eStateDetached:
+ return "detached"
+ elif enum == lldb.eStateExited:
+ return "exited"
+ elif enum == lldb.eStateSuspended:
+ return "suspended"
+ else:
+ raise Exception("Unknown StateType enum")
+
+def stop_reason_to_str(enum):
+ """Returns the stopReason string given an enum."""
+ if enum == lldb.eStopReasonInvalid:
+ return "invalid"
+ elif enum == lldb.eStopReasonNone:
+ return "none"
+ elif enum == lldb.eStopReasonTrace:
+ return "trace"
+ elif enum == lldb.eStopReasonBreakpoint:
+ return "breakpoint"
+ elif enum == lldb.eStopReasonWatchpoint:
+ return "watchpoint"
+ elif enum == lldb.eStopReasonExec:
+ return "exec"
+ elif enum == lldb.eStopReasonSignal:
+ return "signal"
+ elif enum == lldb.eStopReasonException:
+ return "exception"
+ elif enum == lldb.eStopReasonPlanComplete:
+ return "plancomplete"
+ elif enum == lldb.eStopReasonThreadExiting:
+ return "threadexiting"
+ else:
+ raise Exception("Unknown StopReason enum")
+
+def symbol_type_to_str(enum):
+ """Returns the symbolType string given an enum."""
+ if enum == lldb.eSymbolTypeInvalid:
+ return "invalid"
+ elif enum == lldb.eSymbolTypeAbsolute:
+ return "absolute"
+ elif enum == lldb.eSymbolTypeCode:
+ return "code"
+ elif enum == lldb.eSymbolTypeData:
+ return "data"
+ elif enum == lldb.eSymbolTypeTrampoline:
+ return "trampoline"
+ elif enum == lldb.eSymbolTypeRuntime:
+ return "runtime"
+ elif enum == lldb.eSymbolTypeException:
+ return "exception"
+ elif enum == lldb.eSymbolTypeSourceFile:
+ return "sourcefile"
+ elif enum == lldb.eSymbolTypeHeaderFile:
+ return "headerfile"
+ elif enum == lldb.eSymbolTypeObjectFile:
+ return "objectfile"
+ elif enum == lldb.eSymbolTypeCommonBlock:
+ return "commonblock"
+ elif enum == lldb.eSymbolTypeBlock:
+ return "block"
+ elif enum == lldb.eSymbolTypeLocal:
+ return "local"
+ elif enum == lldb.eSymbolTypeParam:
+ return "param"
+ elif enum == lldb.eSymbolTypeVariable:
+ return "variable"
+ elif enum == lldb.eSymbolTypeVariableType:
+ return "variabletype"
+ elif enum == lldb.eSymbolTypeLineEntry:
+ return "lineentry"
+ elif enum == lldb.eSymbolTypeLineHeader:
+ return "lineheader"
+ elif enum == lldb.eSymbolTypeScopeBegin:
+ return "scopebegin"
+ elif enum == lldb.eSymbolTypeScopeEnd:
+ return "scopeend"
+ elif enum == lldb.eSymbolTypeAdditional:
+ return "additional"
+ elif enum == lldb.eSymbolTypeCompiler:
+ return "compiler"
+ elif enum == lldb.eSymbolTypeInstrumentation:
+ return "instrumentation"
+ elif enum == lldb.eSymbolTypeUndefined:
+ return "undefined"
+
+def value_type_to_str(enum):
+ """Returns the valueType string given an enum."""
+ if enum == lldb.eValueTypeInvalid:
+ return "invalid"
+ elif enum == lldb.eValueTypeVariableGlobal:
+ return "global_variable"
+ elif enum == lldb.eValueTypeVariableStatic:
+ return "static_variable"
+ elif enum == lldb.eValueTypeVariableArgument:
+ return "argument_variable"
+ elif enum == lldb.eValueTypeVariableLocal:
+ return "local_variable"
+ elif enum == lldb.eValueTypeRegister:
+ return "register"
+ elif enum == lldb.eValueTypeRegisterSet:
+ return "register_set"
+ elif enum == lldb.eValueTypeConstResult:
+ return "constant_result"
+ else:
+ raise Exception("Unknown ValueType enum")
+
+
+# ==================================================
+# Get stopped threads due to each stop reason.
+# ==================================================
+
+def sort_stopped_threads(process,
+ breakpoint_threads = None,
+ crashed_threads = None,
+ watchpoint_threads = None,
+ signal_threads = None,
+ exiting_threads = None,
+ other_threads = None):
+ """ Fills array *_threads with threads stopped for the corresponding stop
+ reason.
+ """
+ for lst in [breakpoint_threads,
+ watchpoint_threads,
+ signal_threads,
+ exiting_threads,
+ other_threads]:
+ if lst is not None:
+ lst[:] = []
+
+ for thread in process:
+ dispatched = False
+ for (reason, list) in [(lldb.eStopReasonBreakpoint, breakpoint_threads),
+ (lldb.eStopReasonException, crashed_threads),
+ (lldb.eStopReasonWatchpoint, watchpoint_threads),
+ (lldb.eStopReasonSignal, signal_threads),
+ (lldb.eStopReasonThreadExiting, exiting_threads),
+ (None, other_threads)]:
+ if not dispatched and list is not None:
+ if thread.GetStopReason() == reason or reason is None:
+ list.append(thread)
+ dispatched = True
+
+# ==================================================
+# Utility functions for setting breakpoints
+# ==================================================
+
+def run_break_set_by_file_and_line (test, file_name, line_number, extra_options = None, num_expected_locations = 1, loc_exact=False, module_name=None):
+ """Set a breakpoint by file and line, returning the breakpoint number.
+
+ If extra_options is not None, then we append it to the breakpoint set command.
+
+ If num_expected_locations is -1 we check that we got AT LEAST one location, otherwise we check that num_expected_locations equals the number of locations.
+
+ If loc_exact is true, we check that there is one location, and that location must be at the input file and line number."""
+
+ if file_name == None:
+ command = 'breakpoint set -l %d'%(line_number)
+ else:
+ command = 'breakpoint set -f "%s" -l %d'%(file_name, line_number)
+
+ if module_name:
+ command += " --shlib '%s'" % (module_name)
+
+ if extra_options:
+ command += " " + extra_options
+
+ break_results = run_break_set_command (test, command)
+
+ if num_expected_locations == 1 and loc_exact:
+ check_breakpoint_result (test, break_results, num_locations=num_expected_locations, file_name = file_name, line_number = line_number, module_name=module_name)
+ else:
+ check_breakpoint_result (test, break_results, num_locations = num_expected_locations)
+
+ return get_bpno_from_match (break_results)
+
+def run_break_set_by_symbol (test, symbol, extra_options = None, num_expected_locations = -1, sym_exact = False, module_name=None):
+ """Set a breakpoint by symbol name. Common options are the same as run_break_set_by_file_and_line.
+
+ If sym_exact is true, then the output symbol must match the input exactly, otherwise we do a substring match."""
+ command = 'breakpoint set -n "%s"'%(symbol)
+
+ if module_name:
+ command += " --shlib '%s'" % (module_name)
+
+ if extra_options:
+ command += " " + extra_options
+
+ break_results = run_break_set_command (test, command)
+
+ if num_expected_locations == 1 and sym_exact:
+ check_breakpoint_result (test, break_results, num_locations = num_expected_locations, symbol_name = symbol, module_name=module_name)
+ else:
+ check_breakpoint_result (test, break_results, num_locations = num_expected_locations)
+
+ return get_bpno_from_match (break_results)
+
+def run_break_set_by_selector (test, selector, extra_options = None, num_expected_locations = -1, module_name=None):
+ """Set a breakpoint by selector. Common options are the same as run_break_set_by_file_and_line."""
+
+ command = 'breakpoint set -S "%s"' % (selector)
+
+ if module_name:
+ command += ' --shlib "%s"' % (module_name)
+
+ if extra_options:
+ command += " " + extra_options
+
+ break_results = run_break_set_command (test, command)
+
+ if num_expected_locations == 1:
+ check_breakpoint_result (test, break_results, num_locations = num_expected_locations, symbol_name = selector, symbol_match_exact=False, module_name=module_name)
+ else:
+ check_breakpoint_result (test, break_results, num_locations = num_expected_locations)
+
+ return get_bpno_from_match (break_results)
+
+def run_break_set_by_regexp (test, regexp, extra_options=None, num_expected_locations=-1):
+ """Set a breakpoint by regular expression match on symbol name. Common options are the same as run_break_set_by_file_and_line."""
+
+ command = 'breakpoint set -r "%s"'%(regexp)
+ if extra_options:
+ command += " " + extra_options
+
+ break_results = run_break_set_command (test, command)
+
+ check_breakpoint_result (test, break_results, num_locations=num_expected_locations)
+
+ return get_bpno_from_match (break_results)
+
+def run_break_set_by_source_regexp (test, regexp, extra_options=None, num_expected_locations=-1):
+ """Set a breakpoint by source regular expression. Common options are the same as run_break_set_by_file_and_line."""
+ command = 'breakpoint set -p "%s"'%(regexp)
+ if extra_options:
+ command += " " + extra_options
+
+ break_results = run_break_set_command (test, command)
+
+ check_breakpoint_result (test, break_results, num_locations=num_expected_locations)
+
+ return get_bpno_from_match (break_results)
+
+def run_break_set_command (test, command):
+ """Run the command passed in - it must be some break set variant - and analyze the result.
+ Returns a dictionary of information gleaned from the command-line results.
+ Will assert if the breakpoint setting fails altogether.
+
+ Dictionary will contain:
+ bpno - breakpoint of the newly created breakpoint, -1 on error.
+ num_locations - number of locations set for the breakpoint.
+
+ If there is only one location, the dictionary MAY contain:
+ file - source file name
+ line_no - source line number
+ symbol - symbol name
+ inline_symbol - inlined symbol name
+ offset - offset from the original symbol
+ module - module
+ address - address at which the breakpoint was set."""
+
+ patterns = [r"^Breakpoint (?P<bpno>[0-9]+): (?P<num_locations>[0-9]+) locations\.$",
+ r"^Breakpoint (?P<bpno>[0-9]+): (?P<num_locations>no) locations \(pending\)\.",
+ r"^Breakpoint (?P<bpno>[0-9]+): where = (?P<module>.*)`(?P<symbol>[+\-]{0,1}[^+]+)( \+ (?P<offset>[0-9]+)){0,1}( \[inlined\] (?P<inline_symbol>.*)){0,1} at (?P<file>[^:]+):(?P<line_no>[0-9]+), address = (?P<address>0x[0-9a-fA-F]+)$",
+ r"^Breakpoint (?P<bpno>[0-9]+): where = (?P<module>.*)`(?P<symbol>.*)( \+ (?P<offset>[0-9]+)){0,1}, address = (?P<address>0x[0-9a-fA-F]+)$"]
+ match_object = test.match (command, patterns)
+ break_results = match_object.groupdict()
+
+ # We always insert the breakpoint number, setting it to -1 if we couldn't find it
+ # Also, make sure it gets stored as an integer.
+ if not 'bpno' in break_results:
+ break_results['bpno'] = -1
+ else:
+ break_results['bpno'] = int(break_results['bpno'])
+
+ # We always insert the number of locations
+ # If ONE location is set for the breakpoint, then the output doesn't mention locations, but it has to be 1...
+ # We also make sure it is an integer.
+
+ if not 'num_locations' in break_results:
+ num_locations = 1
+ else:
+ num_locations = break_results['num_locations']
+ if num_locations == 'no':
+ num_locations = 0
+ else:
+ num_locations = int(break_results['num_locations'])
+
+ break_results['num_locations'] = num_locations
+
+ if 'line_no' in break_results:
+ break_results['line_no'] = int(break_results['line_no'])
+
+ return break_results
+
+def get_bpno_from_match (break_results):
+ return int (break_results['bpno'])
+
+def check_breakpoint_result (test, break_results, file_name=None, line_number=-1, symbol_name=None, symbol_match_exact=True, module_name=None, offset=-1, num_locations=-1):
+
+ out_num_locations = break_results['num_locations']
+
+ if num_locations == -1:
+ test.assertTrue (out_num_locations > 0, "Expecting one or more locations, got none.")
+ else:
+ test.assertTrue (num_locations == out_num_locations, "Expecting %d locations, got %d."%(num_locations, out_num_locations))
+
+ if file_name:
+ out_file_name = ""
+ if 'file' in break_results:
+ out_file_name = break_results['file']
+ test.assertTrue (file_name == out_file_name, "Breakpoint file name '%s' doesn't match resultant name '%s'."%(file_name, out_file_name))
+
+ if line_number != -1:
+ out_line_number = -1
+ if 'line_no' in break_results:
+ out_line_number = break_results['line_no']
+
+ test.assertTrue (line_number == out_line_number, "Breakpoint line number %s doesn't match resultant line %s."%(line_number, out_line_number))
+
+ if symbol_name:
+ out_symbol_name = ""
+ # Look first for the inlined symbol name, otherwise use the symbol name:
+ if 'inline_symbol' in break_results and break_results['inline_symbol']:
+ out_symbol_name = break_results['inline_symbol']
+ elif 'symbol' in break_results:
+ out_symbol_name = break_results['symbol']
+
+ if symbol_match_exact:
+ test.assertTrue(symbol_name == out_symbol_name, "Symbol name '%s' doesn't match resultant symbol '%s'."%(symbol_name, out_symbol_name))
+ else:
+ test.assertTrue(out_symbol_name.find(symbol_name) != -1, "Symbol name '%s' isn't in resultant symbol '%s'."%(symbol_name, out_symbol_name))
+
+ if module_name:
+ out_module_name = None
+ if 'module' in break_results:
+ out_module_name = break_results['module']
+
+ test.assertTrue (module_name.find(out_module_name) != -1, "Symbol module name '%s' isn't in expected module name '%s'."%(out_module_name, module_name))
+
+# ==================================================
+# Utility functions related to Threads and Processes
+# ==================================================
+
+def get_stopped_threads(process, reason):
+ """Returns the thread(s) with the specified stop reason in a list.
+
+ The list can be empty if no such thread exists.
+ """
+ threads = []
+ for t in process:
+ if t.GetStopReason() == reason:
+ threads.append(t)
+ return threads
+
+def get_stopped_thread(process, reason):
+ """A convenience function which returns the first thread with the given stop
+ reason or None.
+
+ Example usages:
+
+ 1. Get the stopped thread due to a breakpoint condition
+
+ ...
+ from lldbutil import get_stopped_thread
+ thread = get_stopped_thread(process, lldb.eStopReasonPlanComplete)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
+ ...
+
+ 2. Get the thread stopped due to a breakpoint
+
+ ...
+ from lldbutil import get_stopped_thread
+ thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint")
+ ...
+
+ """
+ threads = get_stopped_threads(process, reason)
+ if len(threads) == 0:
+ return None
+ return threads[0]
+
+def get_threads_stopped_at_breakpoint (process, bkpt):
+ """ For a stopped process returns the thread stopped at the breakpoint passed in bkpt"""
+ stopped_threads = []
+ threads = []
+
+ stopped_threads = get_stopped_threads (process, lldb.eStopReasonBreakpoint)
+
+ if len(stopped_threads) == 0:
+ return threads
+
+ for thread in stopped_threads:
+ # Make sure we've hit our breakpoint...
+ break_id = thread.GetStopReasonDataAtIndex (0)
+ if break_id == bkpt.GetID():
+ threads.append(thread)
+
+ return threads
+
+def is_thread_crashed (test, thread):
+ """In the test suite we dereference a null pointer to simulate a crash. The way this is
+ reported depends on the platform."""
+ if test.platformIsDarwin():
+ return thread.GetStopReason() == lldb.eStopReasonException and "EXC_BAD_ACCESS" in thread.GetStopDescription(100)
+ elif test.getPlatform() == "linux":
+ return thread.GetStopReason() == lldb.eStopReasonSignal and thread.GetStopReasonDataAtIndex(0) == thread.GetProcess().GetUnixSignals().GetSignalNumberFromName("SIGSEGV")
+ else:
+ return "invalid address" in thread.GetStopDescription(100)
+
+def get_crashed_threads (test, process):
+ threads = []
+ if process.GetState() != lldb.eStateStopped:
+ return threads
+ for thread in process:
+ if is_thread_crashed(test, thread):
+ threads.append(thread)
+ return threads
+
+def continue_to_breakpoint (process, bkpt):
+ """ Continues the process, if it stops, returns the threads stopped at bkpt; otherwise, returns None"""
+ process.Continue()
+ if process.GetState() != lldb.eStateStopped:
+ return None
+ else:
+ return get_threads_stopped_at_breakpoint (process, bkpt)
+
+def get_caller_symbol(thread):
+ """
+ Returns the symbol name for the call site of the leaf function.
+ """
+ depth = thread.GetNumFrames()
+ if depth <= 1:
+ return None
+ caller = thread.GetFrameAtIndex(1).GetSymbol()
+ if caller:
+ return caller.GetName()
+ else:
+ return None
+
+
+def get_function_names(thread):
+ """
+ Returns a sequence of function names from the stack frames of this thread.
+ """
+ def GetFuncName(i):
+ return thread.GetFrameAtIndex(i).GetFunctionName()
+
+ return list(map(GetFuncName, list(range(thread.GetNumFrames()))))
+
+
+def get_symbol_names(thread):
+ """
+ Returns a sequence of symbols for this thread.
+ """
+ def GetSymbol(i):
+ return thread.GetFrameAtIndex(i).GetSymbol().GetName()
+
+ return list(map(GetSymbol, list(range(thread.GetNumFrames()))))
+
+
+def get_pc_addresses(thread):
+ """
+ Returns a sequence of pc addresses for this thread.
+ """
+ def GetPCAddress(i):
+ return thread.GetFrameAtIndex(i).GetPCAddress()
+
+ return list(map(GetPCAddress, list(range(thread.GetNumFrames()))))
+
+
+def get_filenames(thread):
+ """
+ Returns a sequence of file names from the stack frames of this thread.
+ """
+ def GetFilename(i):
+ return thread.GetFrameAtIndex(i).GetLineEntry().GetFileSpec().GetFilename()
+
+ return list(map(GetFilename, list(range(thread.GetNumFrames()))))
+
+
+def get_line_numbers(thread):
+ """
+ Returns a sequence of line numbers from the stack frames of this thread.
+ """
+ def GetLineNumber(i):
+ return thread.GetFrameAtIndex(i).GetLineEntry().GetLine()
+
+ return list(map(GetLineNumber, list(range(thread.GetNumFrames()))))
+
+
+def get_module_names(thread):
+ """
+ Returns a sequence of module names from the stack frames of this thread.
+ """
+ def GetModuleName(i):
+ return thread.GetFrameAtIndex(i).GetModule().GetFileSpec().GetFilename()
+
+ return list(map(GetModuleName, list(range(thread.GetNumFrames()))))
+
+
+def get_stack_frames(thread):
+ """
+ Returns a sequence of stack frames for this thread.
+ """
+ def GetStackFrame(i):
+ return thread.GetFrameAtIndex(i)
+
+ return list(map(GetStackFrame, list(range(thread.GetNumFrames()))))
+
+
+def print_stacktrace(thread, string_buffer = False):
+ """Prints a simple stack trace of this thread."""
+
+ output = SixStringIO() if string_buffer else sys.stdout
+ target = thread.GetProcess().GetTarget()
+
+ depth = thread.GetNumFrames()
+
+ mods = get_module_names(thread)
+ funcs = get_function_names(thread)
+ symbols = get_symbol_names(thread)
+ files = get_filenames(thread)
+ lines = get_line_numbers(thread)
+ addrs = get_pc_addresses(thread)
+
+ if thread.GetStopReason() != lldb.eStopReasonInvalid:
+ desc = "stop reason=" + stop_reason_to_str(thread.GetStopReason())
+ else:
+ desc = ""
+ print("Stack trace for thread id={0:#x} name={1} queue={2} ".format(
+ thread.GetThreadID(), thread.GetName(), thread.GetQueueName()) + desc, file=output)
+
+ for i in range(depth):
+ frame = thread.GetFrameAtIndex(i)
+ function = frame.GetFunction()
+
+ load_addr = addrs[i].GetLoadAddress(target)
+ if not function:
+ file_addr = addrs[i].GetFileAddress()
+ start_addr = frame.GetSymbol().GetStartAddress().GetFileAddress()
+ symbol_offset = file_addr - start_addr
+ print(" frame #{num}: {addr:#016x} {mod}`{symbol} + {offset}".format(
+ num=i, addr=load_addr, mod=mods[i], symbol=symbols[i], offset=symbol_offset), file=output)
+ else:
+ print(" frame #{num}: {addr:#016x} {mod}`{func} at {file}:{line} {args}".format(
+ num=i, addr=load_addr, mod=mods[i],
+ func='%s [inlined]' % funcs[i] if frame.IsInlined() else funcs[i],
+ file=files[i], line=lines[i],
+ args=get_args_as_string(frame, showFuncName=False) if not frame.IsInlined() else '()'), file=output)
+
+ if string_buffer:
+ return output.getvalue()
+
+
+def print_stacktraces(process, string_buffer = False):
+ """Prints the stack traces of all the threads."""
+
+ output = SixStringIO() if string_buffer else sys.stdout
+
+ print("Stack traces for " + str(process), file=output)
+
+ for thread in process:
+ print(print_stacktrace(thread, string_buffer=True), file=output)
+
+ if string_buffer:
+ return output.getvalue()
+
+def expect_state_changes(test, listener, states, timeout = 5):
+ """Listens for state changed events on the listener and makes sure they match what we
+ expect. Stop-and-restart events (where GetRestartedFromEvent() returns true) are ignored."""
+
+ for expected_state in states:
+ def get_next_event():
+ event = lldb.SBEvent()
+ if not listener.WaitForEvent(timeout, event):
+ test.fail("Timed out while waiting for a transition to state %s" %
+ lldb.SBDebugger.StateAsCString(expected_state))
+ return event
+
+ event = get_next_event()
+ while (lldb.SBProcess.GetStateFromEvent(event) == lldb.eStateStopped and
+ lldb.SBProcess.GetRestartedFromEvent(event)):
+ # Ignore restarted event and the subsequent running event.
+ event = get_next_event()
+ test.assertEqual(lldb.SBProcess.GetStateFromEvent(event), lldb.eStateRunning,
+ "Restarted event followed by a running event")
+ event = get_next_event()
+
+ test.assertEqual(lldb.SBProcess.GetStateFromEvent(event), expected_state)
+
+# ===================================
+# Utility functions related to Frames
+# ===================================
+
+def get_parent_frame(frame):
+ """
+ Returns the parent frame of the input frame object; None if not available.
+ """
+ thread = frame.GetThread()
+ parent_found = False
+ for f in thread:
+ if parent_found:
+ return f
+ if f.GetFrameID() == frame.GetFrameID():
+ parent_found = True
+
+ # If we reach here, no parent has been found, return None.
+ return None
+
+def get_args_as_string(frame, showFuncName=True):
+ """
+ Returns the args of the input frame object as a string.
+ """
+ # arguments => True
+ # locals => False
+ # statics => False
+ # in_scope_only => True
+ vars = frame.GetVariables(True, False, False, True) # type of SBValueList
+ args = [] # list of strings
+ for var in vars:
+ args.append("(%s)%s=%s" % (var.GetTypeName(),
+ var.GetName(),
+ var.GetValue()))
+ if frame.GetFunction():
+ name = frame.GetFunction().GetName()
+ elif frame.GetSymbol():
+ name = frame.GetSymbol().GetName()
+ else:
+ name = ""
+ if showFuncName:
+ return "%s(%s)" % (name, ", ".join(args))
+ else:
+ return "(%s)" % (", ".join(args))
+
+def print_registers(frame, string_buffer = False):
+ """Prints all the register sets of the frame."""
+
+ output = SixStringIO() if string_buffer else sys.stdout
+
+ print("Register sets for " + str(frame), file=output)
+
+ registerSet = frame.GetRegisters() # Return type of SBValueList.
+ print("Frame registers (size of register set = %d):" % registerSet.GetSize(), file=output)
+ for value in registerSet:
+ #print(value, file=output)
+ print("%s (number of children = %d):" % (value.GetName(), value.GetNumChildren()), file=output)
+ for child in value:
+ print("Name: %s, Value: %s" % (child.GetName(), child.GetValue()), file=output)
+
+ if string_buffer:
+ return output.getvalue()
+
+def get_registers(frame, kind):
+ """Returns the registers given the frame and the kind of registers desired.
+
+ Returns None if there's no such kind.
+ """
+ registerSet = frame.GetRegisters() # Return type of SBValueList.
+ for value in registerSet:
+ if kind.lower() in value.GetName().lower():
+ return value
+
+ return None
+
+def get_GPRs(frame):
+ """Returns the general purpose registers of the frame as an SBValue.
+
+ The returned SBValue object is iterable. An example:
+ ...
+ from lldbutil import get_GPRs
+ regs = get_GPRs(frame)
+ for reg in regs:
+ print("%s => %s" % (reg.GetName(), reg.GetValue()))
+ ...
+ """
+ return get_registers(frame, "general purpose")
+
+def get_FPRs(frame):
+ """Returns the floating point registers of the frame as an SBValue.
+
+ The returned SBValue object is iterable. An example:
+ ...
+ from lldbutil import get_FPRs
+ regs = get_FPRs(frame)
+ for reg in regs:
+ print("%s => %s" % (reg.GetName(), reg.GetValue()))
+ ...
+ """
+ return get_registers(frame, "floating point")
+
+def get_ESRs(frame):
+ """Returns the exception state registers of the frame as an SBValue.
+
+ The returned SBValue object is iterable. An example:
+ ...
+ from lldbutil import get_ESRs
+ regs = get_ESRs(frame)
+ for reg in regs:
+ print("%s => %s" % (reg.GetName(), reg.GetValue()))
+ ...
+ """
+ return get_registers(frame, "exception state")
+
+# ======================================
+# Utility classes/functions for SBValues
+# ======================================
+
+class BasicFormatter(object):
+ """The basic formatter inspects the value object and prints the value."""
+ def format(self, value, buffer=None, indent=0):
+ if not buffer:
+ output = SixStringIO()
+ else:
+ output = buffer
+ # If there is a summary, it suffices.
+ val = value.GetSummary()
+ # Otherwise, get the value.
+ if val == None:
+ val = value.GetValue()
+ if val == None and value.GetNumChildren() > 0:
+ val = "%s (location)" % value.GetLocation()
+ print("{indentation}({type}) {name} = {value}".format(
+ indentation = ' ' * indent,
+ type = value.GetTypeName(),
+ name = value.GetName(),
+ value = val), file=output)
+ return output.getvalue()
+
+class ChildVisitingFormatter(BasicFormatter):
+ """The child visiting formatter prints the value and its immediate children.
+
+ The constructor takes a keyword arg: indent_child, which defaults to 2.
+ """
+ def __init__(self, indent_child=2):
+ """Default indentation of 2 SPC's for the children."""
+ self.cindent = indent_child
+ def format(self, value, buffer=None):
+ if not buffer:
+ output = SixStringIO()
+ else:
+ output = buffer
+
+ BasicFormatter.format(self, value, buffer=output)
+ for child in value:
+ BasicFormatter.format(self, child, buffer=output, indent=self.cindent)
+
+ return output.getvalue()
+
+class RecursiveDecentFormatter(BasicFormatter):
+ """The recursive decent formatter prints the value and the decendents.
+
+ The constructor takes two keyword args: indent_level, which defaults to 0,
+ and indent_child, which defaults to 2. The current indentation level is
+ determined by indent_level, while the immediate children has an additional
+ indentation by inden_child.
+ """
+ def __init__(self, indent_level=0, indent_child=2):
+ self.lindent = indent_level
+ self.cindent = indent_child
+ def format(self, value, buffer=None):
+ if not buffer:
+ output = SixStringIO()
+ else:
+ output = buffer
+
+ BasicFormatter.format(self, value, buffer=output, indent=self.lindent)
+ new_indent = self.lindent + self.cindent
+ for child in value:
+ if child.GetSummary() != None:
+ BasicFormatter.format(self, child, buffer=output, indent=new_indent)
+ else:
+ if child.GetNumChildren() > 0:
+ rdf = RecursiveDecentFormatter(indent_level=new_indent)
+ rdf.format(child, buffer=output)
+ else:
+ BasicFormatter.format(self, child, buffer=output, indent=new_indent)
+
+ return output.getvalue()
+
+# ===========================================================
+# Utility functions for path manipulation on remote platforms
+# ===========================================================
+
+def join_remote_paths(*paths):
+ # TODO: update with actual platform name for remote windows once it exists
+ if lldb.remote_platform.GetName() == 'remote-windows':
+ return os.path.join(*paths).replace(os.path.sep, '\\')
+ return os.path.join(*paths).replace(os.path.sep, '/')
+
+def append_to_process_working_directory(*paths):
+ remote = lldb.remote_platform
+ if remote:
+ return join_remote_paths(remote.GetWorkingDirectory(), *paths)
+ return os.path.join(os.getcwd(), *paths)
+
+# ==================================================
+# Utility functions to get the correct signal number
+# ==================================================
+
+import signal
+
+def get_signal_number(signal_name):
+ platform = lldb.remote_platform
+ if platform and platform.IsValid():
+ signals = platform.GetUnixSignals()
+ if signals.IsValid():
+ signal_number = signals.GetSignalNumberFromName(signal_name)
+ if signal_number > 0:
+ return signal_number
+ # No remote platform; fall back to using local python signals.
+ return getattr(signal, signal_name)
+
+class PrintableRegex(object):
+ def __init__(self, text):
+ self.regex = re.compile(text)
+ self.text = text
+
+ def match(self, str):
+ return self.regex.match(str)
+
+ def __str__(self):
+ return "%s" % (self.text)
+
+ def __repr__(self):
+ return "re.compile(%s) -> %s" % (self.text, self.regex)
+
+def skip_if_callable(test, mycallable, reason):
+ if six.callable(mycallable):
+ if mycallable(test):
+ test.skipTest(reason)
+ return True
+ return False
+
+def skip_if_library_missing(test, target, library):
+ def find_library(target, library):
+ for module in target.modules:
+ filename = module.file.GetFilename()
+ if isinstance(library, str):
+ if library == filename:
+ return False
+ elif hasattr(library, 'match'):
+ if library.match(filename):
+ return False
+ return True
+ def find_library_callable(test):
+ return find_library(target, library)
+ return skip_if_callable(test, find_library_callable, "could not find library matching '%s' in target %s" % (library, target))
diff --git a/packages/Python/lldbsuite/test/lock.py b/packages/Python/lldbsuite/test/lock.py
new file mode 100644
index 000000000000..89823b88abc5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/lock.py
@@ -0,0 +1,27 @@
+"""
+Interprocess mutex based on file locks
+"""
+
+import fcntl
+import os
+
+class Lock:
+
+ def __init__(self, filename):
+ self.filename = filename
+ # This will create it if it does not exist already
+ unbuffered = 0
+ self.handle = open(filename, 'a+', unbuffered)
+
+ def acquire(self):
+ fcntl.flock(self.handle, fcntl.LOCK_EX)
+
+ # will throw IOError if unavailable
+ def try_acquire(self):
+ fcntl.flock(self.handle, fcntl.LOCK_NB | fcntl.LOCK_EX)
+
+ def release(self):
+ fcntl.flock(self.handle, fcntl.LOCK_UN)
+
+ def __del__(self):
+ self.handle.close()
diff --git a/packages/Python/lldbsuite/test/logging/Makefile b/packages/Python/lldbsuite/test/logging/Makefile
new file mode 100644
index 000000000000..d4bc9c689043
--- /dev/null
+++ b/packages/Python/lldbsuite/test/logging/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/logging/TestLogging.py b/packages/Python/lldbsuite/test/logging/TestLogging.py
new file mode 100644
index 000000000000..f8558a758ee9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/logging/TestLogging.py
@@ -0,0 +1,107 @@
+"""
+Test lldb logging. This test just makes sure logging doesn't crash, and produces some output.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time, string
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class LogTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+ append_log_file = "lldb-commands-log-append.txt"
+ truncate_log_file = "lldb-commands-log-truncate.txt"
+
+ @classmethod
+ def classCleanup(cls):
+ """Cleanup the test byproducts."""
+ cls.RemoveTempFile(cls.truncate_log_file)
+ cls.RemoveTempFile(cls.append_log_file)
+
+ def test (self):
+ self.build()
+ if self.debug_info == "dsym":
+ self.command_log_tests ("dsym")
+ else:
+ self.command_log_tests ("dwarf")
+
+ def command_log_tests (self, type):
+ exe = os.path.join (os.getcwd(), "a.out")
+ self.expect("file " + exe,
+ patterns = [ "Current executable set to .*a.out" ])
+
+ log_file = os.path.join (os.getcwd(), "lldb-commands-log-%s-%s-%s.txt" % (type,
+ os.path.basename(self.getCompiler()),
+ self.getArchitecture()))
+
+ if (os.path.exists (log_file)):
+ os.remove (log_file)
+
+ # By default, Debugger::EnableLog() will set log options to
+ # PREPEND_THREAD_NAME + OPTION_THREADSAFE. We don't want the
+ # threadnames here, so we enable just threadsafe (-t).
+ self.runCmd ("log enable -t -f '%s' lldb commands" % (log_file))
+
+ self.runCmd ("command alias bp breakpoint")
+
+ self.runCmd ("bp set -n main")
+
+ self.runCmd ("bp l")
+
+ self.runCmd("log disable lldb")
+
+ self.assertTrue (os.path.isfile (log_file))
+
+ f = open (log_file)
+ log_lines = f.readlines()
+ f.close ()
+ os.remove (log_file)
+
+ self.assertTrue(log_lines > 0, "Something was written to the log file.")
+
+ # Check that lldb truncates its log files
+ @no_debug_info_test
+ def test_log_truncate (self):
+ if (os.path.exists (self.truncate_log_file)):
+ os.remove (self.truncate_log_file)
+
+ # put something in our log file
+ with open(self.truncate_log_file, "w") as f:
+ for i in range(1, 1000):
+ f.write("bacon\n")
+
+ self.runCmd ("log enable -t -f '%s' lldb commands" % (self.truncate_log_file))
+ self.runCmd ("help log")
+ self.runCmd ("log disable lldb")
+
+ self.assertTrue (os.path.isfile (self.truncate_log_file))
+ with open(self.truncate_log_file, "r") as f:
+ contents = f.read ()
+
+ # check that it got removed
+ self.assertTrue(string.find(contents, "bacon") == -1)
+
+ # Check that lldb can append to a log file
+ @no_debug_info_test
+ def test_log_append (self):
+ if (os.path.exists (self.append_log_file)):
+ os.remove (self.append_log_file)
+
+ # put something in our log file
+ with open(self.append_log_file, "w") as f:
+ f.write("bacon\n")
+
+ self.runCmd ("log enable -t -a -f '%s' lldb commands" % (self.append_log_file))
+ self.runCmd ("help log")
+ self.runCmd ("log disable lldb")
+
+ self.assertTrue (os.path.isfile (self.append_log_file))
+ with open(self.append_log_file, "r") as f:
+ contents = f.read ()
+
+ # check that it is still there
+ self.assertTrue(string.find(contents, "bacon") == 0)
diff --git a/packages/Python/lldbsuite/test/logging/main.cpp b/packages/Python/lldbsuite/test/logging/main.cpp
new file mode 100644
index 000000000000..7af4e3de2d0b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/logging/main.cpp
@@ -0,0 +1,62 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <cstdlib>
+#include <string>
+#include <fstream>
+#include <iostream>
+
+int
+product (int x, int y)
+{
+ int result = x * y;
+ return result;
+}
+
+int
+sum (int a, int b)
+{
+ int result = a + b;
+ return result;
+}
+
+int
+strange_max (int m, int n)
+{
+ if (m > n)
+ return m;
+ else if (n > m)
+ return n;
+ else
+ return 0;
+}
+
+int
+foo (int i, int j)
+{
+ if (strange_max (i, j) == i)
+ return product (i, j);
+ else if (strange_max (i, j) == j)
+ return sum (i, j);
+ else
+ return product (sum (i, i), sum (j, j));
+}
+
+int
+main(int argc, char const *argv[])
+{
+
+ int array[3];
+
+ array[0] = foo (1238, 78392);
+ array[1] = foo (379265, 23674);
+ array[2] = foo (872934, 234);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/macosx/add-dsym/Makefile b/packages/Python/lldbsuite/test/macosx/add-dsym/Makefile
new file mode 100644
index 000000000000..4e4aa71de2a2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/add-dsym/Makefile
@@ -0,0 +1,11 @@
+CC ?= clang
+
+all: clean
+ mkdir hide.app
+ mkdir hide.app/Contents
+ $(CC) -g main.c
+ mv a.out.dSYM hide.app/Contents
+ strip -x a.out
+
+clean:
+ rm -rf a.out a.out.dSYM hide.app
diff --git a/packages/Python/lldbsuite/test/macosx/add-dsym/TestAddDsymMidExecutionCommand.py b/packages/Python/lldbsuite/test/macosx/add-dsym/TestAddDsymMidExecutionCommand.py
new file mode 100644
index 000000000000..497f695d7cc7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/add-dsym/TestAddDsymMidExecutionCommand.py
@@ -0,0 +1,45 @@
+"""Test that the 'add-dsym', aka 'target symbols add', succeeds in the middle of debug session."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import sys
+from lldbsuite.test.lldbtest import *
+
+@skipUnlessDarwin
+class AddDsymMidExecutionCommandCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ self.source = 'main.c'
+
+ @no_debug_info_test # Prevent the genaration of the dwarf version of this test
+ def test_add_dsym_mid_execution(self):
+ """Test that add-dsym mid-execution loads the symbols at the right place for a slid binary."""
+ self.buildDsym(clean=True)
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ self.target = self.dbg.CreateTarget(exe)
+ self.assertTrue(self.target, VALID_TARGET)
+
+ main_bp = self.target.BreakpointCreateByName ("main", "a.out")
+ self.assertTrue(main_bp, VALID_BREAKPOINT)
+
+ self.runCmd("settings set target.disable-aslr false")
+ self.process = self.target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(self.process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ self.assertTrue(self.process.GetState() == lldb.eStateStopped,
+ STOPPED_DUE_TO_BREAKPOINT)
+
+ self.runCmd("add-dsym hide.app/Contents/a.out.dSYM")
+
+ self.expect("frame select",
+ substrs = ['a.out`main at main.c'])
diff --git a/packages/Python/lldbsuite/test/macosx/add-dsym/main.c b/packages/Python/lldbsuite/test/macosx/add-dsym/main.c
new file mode 100644
index 000000000000..da9e09f07389
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/add-dsym/main.c
@@ -0,0 +1,7 @@
+#include <stdio.h>
+static int var = 5;
+int main ()
+{
+ printf ("%p is %d\n", &var, var); // break on this line
+ return ++var;
+}
diff --git a/packages/Python/lldbsuite/test/macosx/debug-info/apple_types/Makefile b/packages/Python/lldbsuite/test/macosx/debug-info/apple_types/Makefile
new file mode 100644
index 000000000000..aa3a0fcdcea4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/debug-info/apple_types/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+MAKE_DSYM := NO
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/macosx/debug-info/apple_types/TestAppleTypesIsProduced.py b/packages/Python/lldbsuite/test/macosx/debug-info/apple_types/TestAppleTypesIsProduced.py
new file mode 100644
index 000000000000..fad14db41003
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/debug-info/apple_types/TestAppleTypesIsProduced.py
@@ -0,0 +1,67 @@
+"""
+Test that clang produces the __apple accelerator tables, for example, __apple_types, correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+from lldbsuite.test.lldbutil import symbol_type_to_str
+
+class AppleTypesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ #rdar://problem/11166975
+ @skipUnlessDarwin
+ def test_debug_info_for_apple_types(self):
+ """Test that __apple_types section does get produced by clang."""
+
+ if not self.getCompiler().endswith('clang'):
+ self.skipTest("clang compiler only test")
+
+ self.build()
+ if self.debug_info == "dsym":
+ exe = os.path.join(os.getcwd(), "a.out.dSYM/Contents/Resources/DWARF/a.out")
+ else:
+ exe = os.path.join(os.getcwd(), "main.o")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+ self.assertTrue(target.GetNumModules() > 0)
+
+ # Hide stdout if not running with '-t' option.
+ if not self.TraceOn():
+ self.HideStdout()
+
+ print("Number of modules for the target: %d" % target.GetNumModules())
+ for module in target.module_iter():
+ print(module)
+
+ # Get the executable module at index 0.
+ exe_module = target.GetModuleAtIndex(0)
+
+ dwarf_section = exe_module.FindSection("__DWARF")
+ self.assertTrue(dwarf_section)
+ print("__DWARF section:", dwarf_section)
+ print("Number of sub-sections: %d" % dwarf_section.GetNumSubSections())
+ INDENT = ' ' * 4
+ for subsec in dwarf_section:
+ print(INDENT + str(subsec))
+
+ debug_str_sub_section = dwarf_section.FindSubSection("__debug_str")
+ self.assertTrue(debug_str_sub_section)
+ print("__debug_str sub-section:", debug_str_sub_section)
+
+ # Find our __apple_types section by name.
+ apple_types_sub_section = dwarf_section.FindSubSection("__apple_types")
+ self.assertTrue(apple_types_sub_section)
+ print("__apple_types sub-section:", apple_types_sub_section)
+
+ # These other three all important subsections should also be present.
+ self.assertTrue(dwarf_section.FindSubSection("__apple_names") and
+ dwarf_section.FindSubSection("__apple_namespac") and
+ dwarf_section.FindSubSection("__apple_objc"))
diff --git a/packages/Python/lldbsuite/test/macosx/debug-info/apple_types/main.c b/packages/Python/lldbsuite/test/macosx/debug-info/apple_types/main.c
new file mode 100644
index 000000000000..cb4bdb9c16b4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/debug-info/apple_types/main.c
@@ -0,0 +1,27 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+int main (int argc, char const *argv[])
+{
+ struct point_tag {
+ int x;
+ int y;
+ }; // Set break point at this line.
+
+ struct rect_tag {
+ struct point_tag bottom_left;
+ struct point_tag top_right;
+ };
+ struct point_tag pt = { 2, 3 }; // This is the first executable statement.
+ struct rect_tag rect = {{1,2}, {3,4}};
+ pt.x = argc;
+ pt.y = argc * argc;
+ rect.top_right.x = rect.top_right.x + argc;
+ rect.top_right.y = rect.top_right.y + argc;
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/macosx/indirect_symbol/Makefile b/packages/Python/lldbsuite/test/macosx/indirect_symbol/Makefile
new file mode 100644
index 000000000000..07aa39eac3be
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/indirect_symbol/Makefile
@@ -0,0 +1,48 @@
+CC ?= clang
+ifeq "$(ARCH)" ""
+ ARCH = x86_64
+endif
+
+ifeq "$(OS)" ""
+ OS = $(shell uname -s)
+endif
+
+CFLAGS ?= -g -O0
+CWD := $(shell pwd)
+
+LIB_PREFIX := lib
+
+ifeq "$(OS)" "Darwin"
+ CFLAGS += -arch $(ARCH)
+ DS := dsymutil
+ LD_FLAGS := -dynamiclib
+ LIB_INDIRECT := $(LIB_PREFIX)indirect.dylib
+ LIB_REEXPORT := $(LIB_PREFIX)reexport.dylib
+ EXEC_PATH := "@executable_path"
+ EXEC_PATH_INDIRECT := -install_name $(EXEC_PATH)/$(LIB_INDIRECT)
+ EXEC_PATH_REEXPORT := -install_name $(EXEC_PATH)/$(LIB_REEXPORT)
+endif
+
+all: a.out $(LIB_INDIRECT) $(LIB_REEXPORT)
+
+a.out: main.o $(LIB_INDIRECT) $(LIB_REEXPORT)
+ $(CC) $(CFLAGS) -o a.out main.o -L. $(LIB_INDIRECT) $(LIB_REEXPORT)
+
+main.o: main.c
+ $(CC) $(CFLAGS) -c main.c
+
+$(LIB_INDIRECT): indirect.o
+ $(CC) $(CFLAGS) $(LD_FLAGS) $(EXEC_PATH_INDIRECT) -o $(LIB_INDIRECT) indirect.o
+ if [ "$(OS)" = "Darwin" ]; then dsymutil $(LIB_INDIRECT); fi
+
+indirect.o: indirect.c
+ $(CC) $(CFLAGS) -c indirect.c
+
+$(LIB_REEXPORT): reexport.o $(LIB_INDIRECT)
+ $(CC) $(CFLAGS) $(LD_FLAGS) $(EXEC_PATH_REEXPORT) -o $(LIB_REEXPORT) reexport.o -L. -lindirect -Wl,-alias_list,$(CWD)/alias.list
+ if [ "$(OS)" = "Darwin" ]; then dsymutil $(LIB_REEXPORT); fi
+
+reexport.o: reexport.c
+ $(CC) $(CFLAGS) -c reexport.c
+clean:
+ rm -rf $(wildcard *.o *~ *.dylib *.so a.out *.dSYM)
diff --git a/packages/Python/lldbsuite/test/macosx/indirect_symbol/TestIndirectSymbols.py b/packages/Python/lldbsuite/test/macosx/indirect_symbol/TestIndirectSymbols.py
new file mode 100644
index 000000000000..4f98865ca5a2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/indirect_symbol/TestIndirectSymbols.py
@@ -0,0 +1,88 @@
+"""Test stepping and setting breakpoints in indirect and re-exported symbols."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TestIndirectFunctions(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers that we will step to in main:
+ self.main_source = "main.c"
+
+ @skipUnlessDarwin
+ @add_test_categories(['pyapi'])
+ def test_with_python_api(self):
+ """Test stepping and setting breakpoints in indirect and re-exported symbols."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ self.main_source_spec = lldb.SBFileSpec (self.main_source)
+
+ break1 = target.BreakpointCreateBySourceRegex ("Set breakpoint here to step in indirect.", self.main_source_spec)
+ self.assertTrue(break1, VALID_BREAKPOINT)
+
+ break2 = target.BreakpointCreateBySourceRegex ("Set breakpoint here to step in reexported.", self.main_source_spec)
+ self.assertTrue(break2, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, break1)
+ if len(threads) != 1:
+ self.fail ("Failed to stop at breakpoint 1.")
+
+ thread = threads[0]
+
+ # Now do a step-into, and we should end up in the hidden target of this indirect function.
+ thread.StepInto()
+ curr_function = thread.GetFrameAtIndex(0).GetFunctionName()
+ self.assertTrue (curr_function == "call_through_indirect_hidden", "Stepped into indirect symbols.")
+
+ # Now set a breakpoint using the indirect symbol name, and make sure we get to that:
+ break_indirect = target.BreakpointCreateByName ("call_through_indirect");
+ self.assertTrue (break_indirect, VALID_BREAKPOINT)
+
+ # Now continue should take us to the second call through the indirect symbol:
+
+ threads = lldbutil.continue_to_breakpoint (process, break_indirect)
+ self.assertTrue (len(threads) == 1, "Stopped at breakpoint in indirect function.")
+ curr_function = thread.GetFrameAtIndex(0).GetFunctionName()
+ self.assertTrue (curr_function == "call_through_indirect_hidden", "Stepped into indirect symbols.")
+
+ # Delete this breakpoint so it won't get in the way:
+ target.BreakpointDelete (break_indirect.GetID())
+
+ # Now continue to the site of the first re-exported function call in main:
+ threads = lldbutil.continue_to_breakpoint (process, break2)
+
+ # This is stepping Into through a re-exported symbol to an indirect symbol:
+ thread.StepInto()
+ curr_function = thread.GetFrameAtIndex(0).GetFunctionName()
+ self.assertTrue (curr_function == "call_through_indirect_hidden", "Stepped into indirect symbols.")
+
+ # And the last bit is to set a breakpoint on the re-exported symbol and make sure we are again in out target function.
+ break_reexported = target.BreakpointCreateByName ("reexport_to_indirect");
+ self.assertTrue (break_reexported, VALID_BREAKPOINT)
+
+ # Now continue should take us to the second call through the indirect symbol:
+
+ threads = lldbutil.continue_to_breakpoint (process, break_reexported)
+ self.assertTrue (len(threads) == 1, "Stopped at breakpoint in reexported function target.")
+ curr_function = thread.GetFrameAtIndex(0).GetFunctionName()
+ self.assertTrue (curr_function == "call_through_indirect_hidden", "Stepped into indirect symbols.")
diff --git a/packages/Python/lldbsuite/test/macosx/indirect_symbol/alias.list b/packages/Python/lldbsuite/test/macosx/indirect_symbol/alias.list
new file mode 100644
index 000000000000..3232c5888379
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/indirect_symbol/alias.list
@@ -0,0 +1 @@
+_call_through_indirect _reexport_to_indirect \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/macosx/indirect_symbol/indirect.c b/packages/Python/lldbsuite/test/macosx/indirect_symbol/indirect.c
new file mode 100644
index 000000000000..48e1459bb59b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/indirect_symbol/indirect.c
@@ -0,0 +1,14 @@
+#define MakeResolver(name) \
+ void * name ## Resolver(void) __asm__("_" #name); \
+ void * name ## Resolver(void) { \
+ __asm__(".symbol_resolver _" #name); \
+ return name ## _hidden; \
+ }
+
+int
+call_through_indirect_hidden(int arg)
+{
+ return arg + 5;
+}
+
+MakeResolver(call_through_indirect)
diff --git a/packages/Python/lldbsuite/test/macosx/indirect_symbol/main.c b/packages/Python/lldbsuite/test/macosx/indirect_symbol/main.c
new file mode 100644
index 000000000000..b5af058d00b1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/indirect_symbol/main.c
@@ -0,0 +1,14 @@
+extern int call_through_indirect(int);
+extern int reexport_to_indirect(int);
+
+int
+main ()
+{
+ int indirect_result = call_through_indirect(20); // Set breakpoint here to step in indirect.
+ indirect_result = call_through_indirect(30);
+
+ int reexport_result = reexport_to_indirect (20); // Set breakpoint here to step in reexported.
+ reexport_result = reexport_to_indirect (30);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/macosx/indirect_symbol/reexport.c b/packages/Python/lldbsuite/test/macosx/indirect_symbol/reexport.c
new file mode 100644
index 000000000000..096a463b3a47
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/indirect_symbol/reexport.c
@@ -0,0 +1,7 @@
+extern int call_through_indirect(int);
+
+int
+fake_call_through_reexport(int value)
+{
+ return value + 10;
+}
diff --git a/packages/Python/lldbsuite/test/macosx/order/Makefile b/packages/Python/lldbsuite/test/macosx/order/Makefile
new file mode 100644
index 000000000000..52fae2d2ca34
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/order/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+LDFLAGS = $(CFLAGS) -Xlinker -order_file -Xlinker ./order-file
+MAKE_DSYM := NO
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/macosx/order/TestOrderFile.py b/packages/Python/lldbsuite/test/macosx/order/TestOrderFile.py
new file mode 100644
index 000000000000..6541169798ae
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/order/TestOrderFile.py
@@ -0,0 +1,36 @@
+"""
+Test that debug symbols have the correct order as specified by the order file.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class OrderFileTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipUnlessDarwin
+ def test(self):
+ """Test debug symbols follow the correct order by the order file."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Test that the debug symbols have Function f3 before Function f1.
+ # Use "-s address" option to sort by address.
+ self.runCmd("image dump symtab -s address a.out")
+ output = self.res.GetOutput()
+ mo_f3 = re.search("Code +.+f3", output)
+ mo_f1 = re.search("Code +.+f1", output)
+
+ # Match objects for f3 and f1 must exist and f3 must come before f1.
+ self.assertTrue(mo_f3 and mo_f1 and mo_f3.start() < mo_f1.start(),
+ "Symbols have correct order by the order file")
+
+ self.runCmd("run", RUN_COMPLETED)
diff --git a/packages/Python/lldbsuite/test/macosx/order/cmds.txt b/packages/Python/lldbsuite/test/macosx/order/cmds.txt
new file mode 100644
index 000000000000..8c51dd763bf4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/order/cmds.txt
@@ -0,0 +1,3 @@
+b main.c:41
+c
+lines -shlib a.out main.c
diff --git a/packages/Python/lldbsuite/test/macosx/order/main.c b/packages/Python/lldbsuite/test/macosx/order/main.c
new file mode 100644
index 000000000000..cd1ea581876f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/order/main.c
@@ -0,0 +1,54 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+
+int f1 (char *s);
+int f2 (char *s);
+int f3 (char *s);
+
+
+// We want f1 to start on line 20
+int f1 (char *s)
+{
+ return printf("f1: %s\n", s);
+}
+
+
+
+
+
+// We want f2 to start on line 30
+int f2 (char *s)
+{
+ return printf("f2: %s\n", s);
+}
+
+
+
+
+
+// We want f3 to start on line 40
+int f3 (char *s)
+{
+ return printf("f3: %s\n", s);
+}
+
+
+
+
+
+// We want main to start on line 50
+int main (int argc, const char * argv[])
+{
+ f1("carp");
+ f2("ding");
+ f3("dong");
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/macosx/order/order-file b/packages/Python/lldbsuite/test/macosx/order/order-file
new file mode 100644
index 000000000000..0cf8ecd2a639
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/order/order-file
@@ -0,0 +1,4 @@
+main.o:_f3
+main.o:_main
+main.o:_f2
+main.o:_f1
diff --git a/packages/Python/lldbsuite/test/macosx/queues/Makefile b/packages/Python/lldbsuite/test/macosx/queues/Makefile
new file mode 100644
index 000000000000..93f2f7b2f340
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/queues/Makefile
@@ -0,0 +1,28 @@
+CC ?= clang
+ifeq "$(ARCH)" ""
+ ARCH = x86_64
+endif
+
+ifeq "$(OS)" ""
+ OS = $(shell uname -s)
+endif
+
+CFLAGS ?= -g -O0
+CWD := $(shell pwd)
+
+LIB_PREFIX := lib
+
+ifeq "$(OS)" "Darwin"
+ CFLAGS += -arch $(ARCH)
+endif
+
+all: a.out
+
+a.out: main.o
+ $(CC) $(CFLAGS) -o a.out main.o
+
+main.o: main.c
+ $(CC) $(CFLAGS) -c main.c
+
+clean:
+ rm -rf $(wildcard *.o *~ *.dylib *.so a.out *.dSYM)
diff --git a/packages/Python/lldbsuite/test/macosx/queues/TestQueues.py b/packages/Python/lldbsuite/test/macosx/queues/TestQueues.py
new file mode 100644
index 000000000000..492d1d3bda3a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/queues/TestQueues.py
@@ -0,0 +1,243 @@
+"""Test queues inspection SB APIs."""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TestQueues(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipUnlessDarwin
+ @add_test_categories(['pyapi'])
+ @unittest2.expectedFailure("rdar://22531180")
+ def test_with_python_api(self):
+ """Test queues inspection SB APIs."""
+ self.build()
+ self.queues()
+ self.queues_with_libBacktraceRecording()
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers that we will step to in main:
+ self.main_source = "main.c"
+
+ def check_queue_for_valid_queue_id(self, queue):
+ self.assertTrue(queue.GetQueueID() != 0, "Check queue %s for valid QueueID (got 0x%x)" % (queue.GetName(), queue.GetQueueID()))
+
+ def check_running_and_pending_items_on_queue(self, queue, expected_running, expected_pending):
+ self.assertTrue(queue.GetNumPendingItems() == expected_pending, "queue %s should have %d pending items, instead has %d pending items" % (queue.GetName(), expected_pending, (queue.GetNumPendingItems())))
+ self.assertTrue(queue.GetNumRunningItems() == expected_running, "queue %s should have %d running items, instead has %d running items" % (queue.GetName(), expected_running, (queue.GetNumRunningItems())))
+
+ def check_number_of_threads_owned_by_queue(self, queue, number_threads):
+ self.assertTrue(queue.GetNumThreads() == number_threads, "queue %s should have %d thread executing, but has %d" % (queue.GetName(), number_threads, queue.GetNumThreads()))
+
+ def check_queue_kind (self, queue, kind):
+ expected_kind_string = "Unknown"
+ if kind == lldb.eQueueKindSerial:
+ expected_kind_string = "Serial queue"
+ if kind == lldb.eQueueKindConcurrent:
+ expected_kind_string = "Concurrent queue"
+ actual_kind_string = "Unknown"
+ if queue.GetKind() == lldb.eQueueKindSerial:
+ actual_kind_string = "Serial queue"
+ if queue.GetKind() == lldb.eQueueKindConcurrent:
+ actual_kind_string = "Concurrent queue"
+ self.assertTrue(queue.GetKind() == kind, "queue %s is expected to be a %s but it is actually a %s" % (queue.GetName(), expected_kind_string, actual_kind_string))
+
+ def check_queues_threads_match_queue(self, queue):
+ for idx in range(0, queue.GetNumThreads()):
+ t = queue.GetThreadAtIndex(idx)
+ self.assertTrue(t.IsValid(), "Queue %s's thread #%d must be valid" % (queue.GetName(), idx))
+ self.assertTrue(t.GetQueueID() == queue.GetQueueID(), "Queue %s has a QueueID of %d but its thread #%d has a QueueID of %d" % (queue.GetName(), queue.GetQueueID(), idx, t.GetQueueID()))
+ self.assertTrue(t.GetQueueName() == queue.GetName(), "Queue %s has a QueueName of %s but its thread #%d has a QueueName of %s" % (queue.GetName(), queue.GetName(), idx, t.GetQueueName()))
+ self.assertTrue(t.GetQueue().GetQueueID() == queue.GetQueueID(), "Thread #%d's Queue's QueueID of %d is not the same as the QueueID of its owning queue %d" % (idx, t.GetQueue().GetQueueID(), queue.GetQueueID()))
+
+ def queues(self):
+ """Test queues inspection SB APIs without libBacktraceRecording."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+ self.main_source_spec = lldb.SBFileSpec (self.main_source)
+ break1 = target.BreakpointCreateByName ("stopper", 'a.out')
+ self.assertTrue(break1, VALID_BREAKPOINT)
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, break1)
+ if len(threads) != 1:
+ self.fail ("Failed to stop at breakpoint 1.")
+
+ queue_submittor_1 = lldb.SBQueue()
+ queue_performer_1 = lldb.SBQueue()
+ queue_performer_2 = lldb.SBQueue()
+ queue_performer_3 = lldb.SBQueue()
+ for idx in range (0, process.GetNumQueues()):
+ q = process.GetQueueAtIndex(idx)
+ if q.GetName() == "com.apple.work_submittor_1":
+ queue_submittor_1 = q
+ if q.GetName() == "com.apple.work_performer_1":
+ queue_performer_1 = q
+ if q.GetName() == "com.apple.work_performer_2":
+ queue_performer_2 = q
+ if q.GetName() == "com.apple.work_performer_3":
+ queue_performer_3 = q
+
+ self.assertTrue(queue_submittor_1.IsValid() and queue_performer_1.IsValid() and queue_performer_2.IsValid() and queue_performer_3.IsValid(), "Got all four expected queues: %s %s %s %s" % (queue_submittor_1.IsValid(), queue_performer_1.IsValid(), queue_performer_2.IsValid(), queue_performer_3.IsValid()))
+
+ self.check_queue_for_valid_queue_id (queue_submittor_1)
+ self.check_queue_for_valid_queue_id (queue_performer_1)
+ self.check_queue_for_valid_queue_id (queue_performer_2)
+ self.check_queue_for_valid_queue_id (queue_performer_3)
+
+ self.check_number_of_threads_owned_by_queue (queue_submittor_1, 1)
+ self.check_number_of_threads_owned_by_queue (queue_performer_1, 1)
+ self.check_number_of_threads_owned_by_queue (queue_performer_2, 1)
+ self.check_number_of_threads_owned_by_queue (queue_performer_3, 4)
+
+ self.check_queue_kind (queue_submittor_1, lldb.eQueueKindSerial)
+ self.check_queue_kind (queue_performer_1, lldb.eQueueKindSerial)
+ self.check_queue_kind (queue_performer_2, lldb.eQueueKindSerial)
+ self.check_queue_kind (queue_performer_3, lldb.eQueueKindConcurrent)
+
+ self.check_queues_threads_match_queue (queue_submittor_1)
+ self.check_queues_threads_match_queue (queue_performer_1)
+ self.check_queues_threads_match_queue (queue_performer_2)
+ self.check_queues_threads_match_queue (queue_performer_3)
+
+
+
+ # We have threads running with all the different dispatch QoS service
+ # levels - find those threads and check that we can get the correct
+ # QoS name for each of them.
+
+ user_initiated_thread = lldb.SBThread()
+ user_interactive_thread = lldb.SBThread()
+ utility_thread = lldb.SBThread()
+ unspecified_thread = lldb.SBThread()
+ background_thread = lldb.SBThread()
+ for th in process.threads:
+ if th.GetName() == "user initiated QoS":
+ user_initiated_thread = th
+ if th.GetName() == "user interactive QoS":
+ user_interactive_thread = th
+ if th.GetName() == "utility QoS":
+ utility_thread = th
+ if th.GetName() == "unspecified QoS":
+ unspecified_thread = th
+ if th.GetName() == "background QoS":
+ background_thread = th
+
+ self.assertTrue(user_initiated_thread.IsValid(), "Found user initiated QoS thread")
+ self.assertTrue(user_interactive_thread.IsValid(), "Found user interactive QoS thread")
+ self.assertTrue(utility_thread.IsValid(), "Found utility QoS thread")
+ self.assertTrue(unspecified_thread.IsValid(), "Found unspecified QoS thread")
+ self.assertTrue(background_thread.IsValid(), "Found background QoS thread")
+
+ stream = lldb.SBStream()
+ self.assertTrue(user_initiated_thread.GetInfoItemByPathAsString("requested_qos.printable_name", stream), "Get QoS printable string for user initiated QoS thread")
+ self.assertTrue(stream.GetData() == "User Initiated", "user initiated QoS thread name is valid")
+ stream.Clear()
+ self.assertTrue(user_interactive_thread.GetInfoItemByPathAsString("requested_qos.printable_name", stream), "Get QoS printable string for user interactive QoS thread")
+ self.assertTrue(stream.GetData() == "User Interactive", "user interactive QoS thread name is valid")
+ stream.Clear()
+ self.assertTrue(utility_thread.GetInfoItemByPathAsString("requested_qos.printable_name", stream), "Get QoS printable string for utility QoS thread")
+ self.assertTrue(stream.GetData() == "Utility", "utility QoS thread name is valid")
+ stream.Clear()
+ self.assertTrue(unspecified_thread.GetInfoItemByPathAsString("requested_qos.printable_name", stream), "Get QoS printable string for unspecified QoS thread")
+ self.assertTrue(stream.GetData() == "User Initiated", "unspecified QoS thread name is valid")
+ stream.Clear()
+ self.assertTrue(background_thread.GetInfoItemByPathAsString("requested_qos.printable_name", stream), "Get QoS printable string for background QoS thread")
+ self.assertTrue(stream.GetData() == "Background", "background QoS thread name is valid")
+
+ def queues_with_libBacktraceRecording(self):
+ """Test queues inspection SB APIs with libBacktraceRecording present."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ if not os.path.isfile('/Applications/Xcode.app/Contents/Developer/usr/lib/libBacktraceRecording.dylib'):
+ self.skipTest ("Skipped because libBacktraceRecording.dylib was present on the system.")
+
+ if not os.path.isfile('/usr/lib/system/introspection/libdispatch.dylib'):
+ self.skipTest ("Skipped because introspection libdispatch dylib is not present.")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ self.main_source_spec = lldb.SBFileSpec (self.main_source)
+
+ break1 = target.BreakpointCreateByName ("stopper", 'a.out')
+ self.assertTrue(break1, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, ['DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/usr/lib/libBacktraceRecording.dylib', 'DYLD_LIBRARY_PATH=/usr/lib/system/introspection'], self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # The stop reason of the thread should be breakpoint.
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, break1)
+ if len(threads) != 1:
+ self.fail ("Failed to stop at breakpoint 1.")
+
+ libbtr_module_filespec = lldb.SBFileSpec("libBacktraceRecording.dylib")
+ libbtr_module = target.FindModule (libbtr_module_filespec)
+ if not libbtr_module.IsValid():
+ self.skipTest ("Skipped because libBacktraceRecording.dylib was not loaded into the process.")
+
+ self.assertTrue(process.GetNumQueues() >= 4, "Found the correct number of queues.")
+
+ queue_submittor_1 = lldb.SBQueue()
+ queue_performer_1 = lldb.SBQueue()
+ queue_performer_2 = lldb.SBQueue()
+ queue_performer_3 = lldb.SBQueue()
+ for idx in range (0, process.GetNumQueues()):
+ q = process.GetQueueAtIndex(idx)
+ if q.GetName() == "com.apple.work_submittor_1":
+ queue_submittor_1 = q
+ if q.GetName() == "com.apple.work_performer_1":
+ queue_performer_1 = q
+ if q.GetName() == "com.apple.work_performer_2":
+ queue_performer_2 = q
+ if q.GetName() == "com.apple.work_performer_3":
+ queue_performer_3 = q
+
+ self.assertTrue(queue_submittor_1.IsValid() and queue_performer_1.IsValid() and queue_performer_2.IsValid() and queue_performer_3.IsValid(), "Got all four expected queues: %s %s %s %s" % (queue_submittor_1.IsValid(), queue_performer_1.IsValid(), queue_performer_2.IsValid(), queue_performer_3.IsValid()))
+
+ self.check_queue_for_valid_queue_id (queue_submittor_1)
+ self.check_queue_for_valid_queue_id (queue_performer_1)
+ self.check_queue_for_valid_queue_id (queue_performer_2)
+ self.check_queue_for_valid_queue_id (queue_performer_3)
+
+ self.check_running_and_pending_items_on_queue (queue_submittor_1, 1, 0)
+ self.check_running_and_pending_items_on_queue (queue_performer_1, 1, 3)
+ self.check_running_and_pending_items_on_queue (queue_performer_2, 1, 9999)
+ self.check_running_and_pending_items_on_queue (queue_performer_3, 4, 0)
+
+ self.check_number_of_threads_owned_by_queue (queue_submittor_1, 1)
+ self.check_number_of_threads_owned_by_queue (queue_performer_1, 1)
+ self.check_number_of_threads_owned_by_queue (queue_performer_2, 1)
+ self.check_number_of_threads_owned_by_queue (queue_performer_3, 4)
+
+ self.check_queue_kind (queue_submittor_1, lldb.eQueueKindSerial)
+ self.check_queue_kind (queue_performer_1, lldb.eQueueKindSerial)
+ self.check_queue_kind (queue_performer_2, lldb.eQueueKindSerial)
+ self.check_queue_kind (queue_performer_3, lldb.eQueueKindConcurrent)
+
+
+ self.check_queues_threads_match_queue (queue_submittor_1)
+ self.check_queues_threads_match_queue (queue_performer_1)
+ self.check_queues_threads_match_queue (queue_performer_2)
+ self.check_queues_threads_match_queue (queue_performer_3)
+
+ self.assertTrue(queue_performer_2.GetPendingItemAtIndex(0).IsValid(), "queue 2's pending item #0 is valid")
+ self.assertTrue(queue_performer_2.GetPendingItemAtIndex(0).GetAddress().GetSymbol().GetName() == "doing_the_work_2", "queue 2's pending item #0 should be doing_the_work_2")
+ self.assertTrue(queue_performer_2.GetNumPendingItems() == 9999, "verify that queue 2 still has 9999 pending items")
+ self.assertTrue(queue_performer_2.GetPendingItemAtIndex(9998).IsValid(), "queue 2's pending item #9998 is valid")
+ self.assertTrue(queue_performer_2.GetPendingItemAtIndex(9998).GetAddress().GetSymbol().GetName() == "doing_the_work_2", "queue 2's pending item #0 should be doing_the_work_2")
+ self.assertTrue(queue_performer_2.GetPendingItemAtIndex(9999).IsValid() == False, "queue 2's pending item #9999 is invalid")
diff --git a/packages/Python/lldbsuite/test/macosx/queues/main.c b/packages/Python/lldbsuite/test/macosx/queues/main.c
new file mode 100644
index 000000000000..fa6a3e570ae3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/queues/main.c
@@ -0,0 +1,133 @@
+#include <stdio.h>
+#include <unistd.h>
+#include <dispatch/dispatch.h>
+#include <pthread.h>
+
+void
+doing_the_work_1(void *in)
+{
+ while (1)
+ sleep (1);
+}
+
+void
+submit_work_1a(void *in)
+{
+ dispatch_queue_t *work_performer_1 = (dispatch_queue_t*) in;
+ dispatch_async_f (*work_performer_1, NULL, doing_the_work_1);
+ dispatch_async_f (*work_performer_1, NULL, doing_the_work_1);
+}
+
+void
+submit_work_1b(void *in)
+{
+ dispatch_queue_t *work_performer_1 = (dispatch_queue_t*) in;
+ dispatch_async_f (*work_performer_1, NULL, doing_the_work_1);
+ dispatch_async_f (*work_performer_1, NULL, doing_the_work_1);
+ while (1)
+ sleep (1);
+}
+
+void
+doing_the_work_2(void *in)
+{
+ while (1)
+ sleep (1);
+}
+
+void
+submit_work_2(void *in)
+{
+ dispatch_queue_t *work_performer_2 = (dispatch_queue_t*) in;
+ int i = 0;
+ while (i++ < 5000)
+ {
+ dispatch_async_f (*work_performer_2, NULL, doing_the_work_2);
+ dispatch_async_f (*work_performer_2, NULL, doing_the_work_2);
+ }
+}
+
+
+void
+doing_the_work_3(void *in)
+{
+ while (1)
+ sleep(1);
+}
+
+void
+submit_work_3(void *in)
+{
+ dispatch_queue_t *work_performer_3 = (dispatch_queue_t*) in;
+ dispatch_async_f (*work_performer_3, NULL, doing_the_work_3);
+ dispatch_async_f (*work_performer_3, NULL, doing_the_work_3);
+ dispatch_async_f (*work_performer_3, NULL, doing_the_work_3);
+ dispatch_async_f (*work_performer_3, NULL, doing_the_work_3);
+}
+
+
+void
+stopper ()
+{
+ while (1)
+ sleep (1);
+}
+
+int main ()
+{
+ dispatch_queue_t work_submittor_1 = dispatch_queue_create ("com.apple.work_submittor_1", DISPATCH_QUEUE_SERIAL);
+ dispatch_queue_t work_submittor_2 = dispatch_queue_create ("com.apple.work_submittor_and_quit_2", DISPATCH_QUEUE_SERIAL);
+ dispatch_queue_t work_submittor_3 = dispatch_queue_create ("com.apple.work_submittor_3", DISPATCH_QUEUE_SERIAL);
+
+ dispatch_queue_t work_performer_1 = dispatch_queue_create ("com.apple.work_performer_1", DISPATCH_QUEUE_SERIAL);
+ dispatch_queue_t work_performer_2 = dispatch_queue_create ("com.apple.work_performer_2", DISPATCH_QUEUE_SERIAL);
+
+ dispatch_queue_t work_performer_3 = dispatch_queue_create ("com.apple.work_performer_3", DISPATCH_QUEUE_CONCURRENT);
+
+ dispatch_async_f (work_submittor_1, (void*) &work_performer_1, submit_work_1a);
+ dispatch_async_f (work_submittor_1, (void*) &work_performer_1, submit_work_1b);
+
+ dispatch_async_f (work_submittor_2, (void*) &work_performer_2, submit_work_2);
+
+ dispatch_async_f (work_submittor_3, (void*) &work_performer_3, submit_work_3);
+
+
+ // Spin up threads with each of the different libdispatch QoS values.
+
+ dispatch_async (dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
+ pthread_setname_np ("user initiated QoS");
+ while (1)
+ sleep (10);
+ });
+ dispatch_async (dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^{
+ pthread_setname_np ("user interactive QoS");
+ while (1)
+ sleep (10);
+ });
+ dispatch_async (dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), ^{
+ pthread_setname_np ("default QoS");
+ while (1)
+ sleep (10);
+ });
+ dispatch_async (dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
+ pthread_setname_np ("utility QoS");
+ while (1)
+ sleep (10);
+ });
+ dispatch_async (dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{
+ pthread_setname_np ("background QoS");
+ while (1)
+ sleep (10);
+ });
+ dispatch_async (dispatch_get_global_queue(QOS_CLASS_UNSPECIFIED, 0), ^{
+ pthread_setname_np ("unspecified QoS");
+ while (1)
+ sleep (10);
+ });
+
+
+ sleep (1);
+ stopper ();
+
+}
+
diff --git a/packages/Python/lldbsuite/test/macosx/safe-to-func-call/Makefile b/packages/Python/lldbsuite/test/macosx/safe-to-func-call/Makefile
new file mode 100644
index 000000000000..93f2f7b2f340
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/safe-to-func-call/Makefile
@@ -0,0 +1,28 @@
+CC ?= clang
+ifeq "$(ARCH)" ""
+ ARCH = x86_64
+endif
+
+ifeq "$(OS)" ""
+ OS = $(shell uname -s)
+endif
+
+CFLAGS ?= -g -O0
+CWD := $(shell pwd)
+
+LIB_PREFIX := lib
+
+ifeq "$(OS)" "Darwin"
+ CFLAGS += -arch $(ARCH)
+endif
+
+all: a.out
+
+a.out: main.o
+ $(CC) $(CFLAGS) -o a.out main.o
+
+main.o: main.c
+ $(CC) $(CFLAGS) -c main.c
+
+clean:
+ rm -rf $(wildcard *.o *~ *.dylib *.so a.out *.dSYM)
diff --git a/packages/Python/lldbsuite/test/macosx/safe-to-func-call/TestSafeFuncCalls.py b/packages/Python/lldbsuite/test/macosx/safe-to-func-call/TestSafeFuncCalls.py
new file mode 100644
index 000000000000..297223c3e84e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/safe-to-func-call/TestSafeFuncCalls.py
@@ -0,0 +1,63 @@
+"""Test function call thread safety."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TestSafeFuncCalls(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers that we will step to in main:
+ self.main_source = "main.c"
+
+ @skipUnlessDarwin
+ @add_test_categories(['pyapi'])
+ def test_with_python_api(self):
+ """Test function call thread safety."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+ self.main_source_spec = lldb.SBFileSpec (self.main_source)
+ break1 = target.BreakpointCreateByName ("stopper", 'a.out')
+ self.assertTrue(break1, VALID_BREAKPOINT)
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, break1)
+ if len(threads) != 1:
+ self.fail ("Failed to stop at breakpoint 1.")
+
+ self.check_number_of_threads(process)
+
+ main_thread = lldb.SBThread()
+ select_thread = lldb.SBThread()
+ for idx in range (0, process.GetNumThreads()):
+ t = process.GetThreadAtIndex (idx)
+ if t.GetName() == "main thread":
+ main_thread = t
+ if t.GetName() == "select thread":
+ select_thread = t
+
+ self.assertTrue(main_thread.IsValid() and select_thread.IsValid(), "Got both expected threads")
+
+ self.safe_to_call_func_on_main_thread (main_thread)
+ self.safe_to_call_func_on_select_thread (select_thread)
+
+ def check_number_of_threads(self, process):
+ self.assertTrue(process.GetNumThreads() == 2, "Check that the process has two threads when sitting at the stopper() breakpoint")
+
+ def safe_to_call_func_on_main_thread (self, main_thread):
+ self.assertTrue(main_thread.SafeToCallFunctions() == True, "It is safe to call functions on the main thread")
+
+ def safe_to_call_func_on_select_thread (self, select_thread):
+ self.assertTrue(select_thread.SafeToCallFunctions() == False, "It is not safe to call functions on the select thread")
diff --git a/packages/Python/lldbsuite/test/macosx/safe-to-func-call/main.c b/packages/Python/lldbsuite/test/macosx/safe-to-func-call/main.c
new file mode 100644
index 000000000000..613384ff73b3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/safe-to-func-call/main.c
@@ -0,0 +1,30 @@
+#include <sys/select.h>
+#include <stdio.h>
+#include <pthread.h>
+#include <unistd.h>
+
+void *
+select_thread (void *in)
+{
+ pthread_setname_np ("select thread");
+ fd_set fdset;
+ FD_SET (STDIN_FILENO, &fdset);
+ while (1)
+ select (2, &fdset, NULL, NULL, NULL);
+ return NULL;
+}
+
+void stopper ()
+{
+ while (1)
+ sleep(1); // break here
+}
+
+int main ()
+{
+ pthread_setname_np ("main thread");
+ pthread_t other_thread;
+ pthread_create (&other_thread, NULL, select_thread, NULL);
+ sleep (1);
+ stopper();
+}
diff --git a/packages/Python/lldbsuite/test/macosx/universal/Makefile b/packages/Python/lldbsuite/test/macosx/universal/Makefile
new file mode 100644
index 000000000000..854c78ed8c29
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/universal/Makefile
@@ -0,0 +1,19 @@
+CC ?= clang
+
+testit: testit.i386 testit.x86_64
+ lipo -create -o testit testit.i386 testit.x86_64
+
+testit.i386: testit.i386.o
+ $(CC) -arch i386 -o testit.i386 testit.i386.o
+
+testit.x86_64: testit.x86_64.o
+ $(CC) -arch x86_64 -o testit.x86_64 testit.x86_64.o
+
+testit.i386.o: main.c
+ $(CC) -g -O0 -arch i386 -c -o testit.i386.o main.c
+
+testit.x86_64.o: main.c
+ $(CC) -g -O0 -arch x86_64 -c -o testit.x86_64.o main.c
+
+clean:
+ rm -rf $(wildcard testit* *~)
diff --git a/packages/Python/lldbsuite/test/macosx/universal/TestUniversal.py b/packages/Python/lldbsuite/test/macosx/universal/TestUniversal.py
new file mode 100644
index 000000000000..4b722b0c1d8e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/universal/TestUniversal.py
@@ -0,0 +1,107 @@
+"""Test aspects of lldb commands on universal binaries."""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class UniversalTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.c', '// Set break point at this line.')
+
+ @add_test_categories(['pyapi'])
+ @skipUnlessDarwin
+ @unittest2.skipUnless(hasattr(os, "uname") and os.uname()[4] in ['i386', 'x86_64'],
+ "requires i386 or x86_64")
+ def test_sbdebugger_create_target_with_file_and_target_triple(self):
+ """Test the SBDebugger.CreateTargetWithFileAndTargetTriple() API."""
+ # Invoke the default build rule.
+ self.build()
+
+ # Note that "testit" is a universal binary.
+ exe = os.path.join(os.getcwd(), "testit")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTargetWithFileAndTargetTriple(exe, "i386-apple-macosx")
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ @skipUnlessDarwin
+ @unittest2.skipUnless(hasattr(os, "uname") and os.uname()[4] in ['i386', 'x86_64'],
+ "requires i386 or x86_64")
+ def test_process_launch_for_universal(self):
+ """Test process launch of a universal binary."""
+ from lldbsuite.test.lldbutil import print_registers
+
+ # Invoke the default build rule.
+ self.build()
+
+ # Note that "testit" is a universal binary.
+ exe = os.path.join(os.getcwd(), "testit")
+
+ # By default, x86_64 is assumed if no architecture is specified.
+ self.expect("file " + exe, CURRENT_EXECUTABLE_SET,
+ startstr = "Current executable set to ",
+ substrs = ["testit' (x86_64)."])
+
+ # Break inside the main.
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=True)
+
+ # We should be able to launch the x86_64 executable.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Check whether we have a 64-bit process launched.
+ target = self.dbg.GetSelectedTarget()
+ process = target.GetProcess()
+ self.assertTrue(target and process and
+ self.invoke(process, 'GetAddressByteSize') == 8,
+ "64-bit process launched")
+
+ frame = process.GetThreadAtIndex(0).GetFrameAtIndex(0)
+ registers = print_registers(frame, string_buffer=True)
+ self.expect(registers, exe=False,
+ substrs = ['Name: rax'])
+
+ self.runCmd("continue")
+
+ # Now specify i386 as the architecture for "testit".
+ self.expect("file -a i386 " + exe, CURRENT_EXECUTABLE_SET,
+ startstr = "Current executable set to ",
+ substrs = ["testit' (i386)."])
+
+ # Break inside the main.
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=True)
+
+ # We should be able to launch the i386 executable as well.
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Check whether we have a 32-bit process launched.
+ target = self.dbg.GetSelectedTarget()
+ process = target.GetProcess()
+ self.assertTrue(target and process,
+ "32-bit process launched")
+
+ pointerSize = self.invoke(process, 'GetAddressByteSize')
+ self.assertTrue(pointerSize == 4,
+ "AddressByteSize of 32-bit process should be 4, got %d instead." % pointerSize)
+
+ frame = process.GetThreadAtIndex(0).GetFrameAtIndex(0)
+ registers = print_registers(frame, string_buffer=True)
+ self.expect(registers, exe=False,
+ substrs = ['Name: eax'])
+
+ self.runCmd("continue")
diff --git a/packages/Python/lldbsuite/test/macosx/universal/main.c b/packages/Python/lldbsuite/test/macosx/universal/main.c
new file mode 100644
index 000000000000..9351c77f7146
--- /dev/null
+++ b/packages/Python/lldbsuite/test/macosx/universal/main.c
@@ -0,0 +1,7 @@
+#include <stdio.h>
+int
+main (int argc, char **argv)
+{
+ printf ("Hello there!\n"); // Set break point at this line.
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/make/Makefile.rules b/packages/Python/lldbsuite/test/make/Makefile.rules
new file mode 100644
index 000000000000..e753317e9398
--- /dev/null
+++ b/packages/Python/lldbsuite/test/make/Makefile.rules
@@ -0,0 +1,600 @@
+#----------------------------------------------------------------------
+# Clients fill in the source files to build
+#----------------------------------------------------------------------
+# C_SOURCES := main.c
+# CXX_SOURCES :=
+# OBJC_SOURCES :=
+# OBJCXX_SOURCES :=
+# DYLIB_C_SOURCES :=
+# DYLIB_CXX_SOURCES :=
+#
+# Specifying DYLIB_ONLY has the effect of building dylib only, skipping
+# the building of the a.out executable program. For example,
+# DYLIB_ONLY := YES
+#
+# Also might be of interest:
+# FRAMEWORK_INCLUDES (Darwin only) :=
+# CFLAGS_EXTRAS :=
+# LD_EXTRAS :=
+# SPLIT_DEBUG_SYMBOLS := YES
+# CROSS_COMPILE :=
+#
+# And test/functionalities/archives/Makefile:
+# MAKE_DSYM := NO
+# ARCHIVE_NAME := libfoo.a
+# ARCHIVE_C_SOURCES := a.c b.c
+
+# Uncomment line below for debugging shell commands
+# SHELL = /bin/sh -x
+
+THIS_FILE_DIR := $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))/
+LLDB_BASE_DIR := $(THIS_FILE_DIR)../../../../../
+
+
+#----------------------------------------------------------------------
+# If TRIPLE is not defined try to set the ARCH, CC, CFLAGS, and more
+# from the triple alone
+#----------------------------------------------------------------------
+TRIPLE_CFLAGS :=
+ifneq "$(TRIPLE)" ""
+ triple_space = $(subst -, ,$(TRIPLE))
+ ARCH =$(word 1, $(triple_space))
+ TRIPLE_VENDOR =$(word 2, $(triple_space))
+ triple_os_and_version =$(shell echo $(word 3, $(triple_space)) | sed 's/\([a-z]*\)\(.*\)/\1 \2/')
+ TRIPLE_OS =$(word 1, $(triple_os_and_version))
+ TRIPLE_VERSION =$(word 2, $(triple_os_and_version))
+ ifeq "$(TRIPLE_VENDOR)" "apple"
+ ifeq "$(TRIPLE_OS)" "ios"
+ ifeq "$(SDKROOT)" ""
+ # Set SDKROOT if it wasn't set
+ ifneq (,$(findstring arm,$(ARCH)))
+ SDKROOT = $(shell xcrun --sdk iphoneos --show-sdk-path)
+ ifeq "$(TRIPLE_VERSION)" ""
+ TRIPLE_VERSION =$(shell echo $(notdir $(SDKROOT)) | sed -e 's/.*\([0-9]\.[0-9]\).*/\1/')
+ endif
+ TRIPLE_CFLAGS :=-mios-version-min=$(TRIPLE_VERSION) -isysroot "$(SDKROOT)"
+ else
+ SDKROOT = $(shell xcrun --sdk iphonesimulator --show-sdk-path)
+ ifeq "$(TRIPLE_VERSION)" ""
+ TRIPLE_VERSION =$(shell echo $(notdir $(SDKROOT)) | sed -e 's/.*\([0-9]\.[0-9]\).*/\1/')
+ endif
+ TRIPLE_CFLAGS :=-mios-simulator-version-min=$(TRIPLE_VERSION) -isysroot "$(SDKROOT)"
+ endif
+ endif
+ endif
+ endif
+endif
+
+#----------------------------------------------------------------------
+# If OS is not defined, use 'uname -s' to determine the OS name.
+#
+# uname on Windows gives "windows32", but most environments standardize
+# on "Windows_NT", so we'll make it consistent here. When running
+# tests from Visual Studio, the environment variable isn't inherited
+# all the way down to the process spawned for make.
+#----------------------------------------------------------------------
+HOST_OS = $(shell uname -s)
+ifeq "$(HOST_OS)" "windows32"
+ HOST_OS = Windows_NT
+endif
+ifeq "$(OS)" ""
+ OS = $(HOST_OS)
+endif
+
+#----------------------------------------------------------------------
+# If ARCH is not defined, default to x86_64.
+#----------------------------------------------------------------------
+ifeq "$(ARCH)" ""
+ifeq "$(OS)" "Windows_NT"
+ ARCH = x86
+else
+ ARCH = x86_64
+endif
+endif
+
+#----------------------------------------------------------------------
+# CC defaults to clang.
+#
+# If you change the defaults of CC, be sure to also change it in the file
+# test/plugins/builder_base.py, which provides a Python way to return the
+# value of the make variable CC -- getCompiler().
+#
+# See also these functions:
+# o cxx_compiler
+# o cxx_linker
+#----------------------------------------------------------------------
+CC ?= clang
+ifeq "$(CC)" "cc"
+ ifneq "$(shell which clang)" ""
+ CC = clang
+ else ifneq "$(shell which clang-3.5)" ""
+ CC = clang-3.5
+ else ifneq "$(shell which gcc)" ""
+ CC = gcc
+ endif
+endif
+
+#----------------------------------------------------------------------
+# ARCHFLAG is the flag used to tell the compiler which architecture
+# to compile for. The default is the flag that clang accepts.
+#----------------------------------------------------------------------
+ARCHFLAG ?= -arch
+
+#----------------------------------------------------------------------
+# Change any build/tool options needed
+#----------------------------------------------------------------------
+ifeq "$(OS)" "Darwin"
+ DS := $(shell xcrun -find -toolchain default dsymutil)
+ DSFLAGS =
+ DSYM = $(EXE).dSYM
+ AR := $(CROSS_COMPILE)libtool
+ ARFLAGS := -static -o
+else
+ AR := $(CROSS_COMPILE)ar
+ # On non-Apple platforms, -arch becomes -m
+ ARCHFLAG := -m
+
+ # i386, i686, x86 -> 32
+ # amd64, x86_64, x64 -> 64
+ ifeq "$(ARCH)" "amd64"
+ override ARCH := $(subst amd64,64,$(ARCH))
+ endif
+ ifeq "$(ARCH)" "x86_64"
+ override ARCH := $(subst x86_64,64,$(ARCH))
+ endif
+ ifeq "$(ARCH)" "x64"
+ override ARCH := $(subst x64,64,$(ARCH))
+ endif
+ ifeq "$(ARCH)" "x86"
+ override ARCH := $(subst x86,32,$(ARCH))
+ endif
+ ifeq "$(ARCH)" "i386"
+ override ARCH := $(subst i386,32,$(ARCH))
+ endif
+ ifeq "$(ARCH)" "i686"
+ override ARCH := $(subst i686,32,$(ARCH))
+ endif
+ ifeq "$(ARCH)" "powerpc"
+ override ARCH := $(subst powerpc,32,$(ARCH))
+ endif
+ ifeq "$(ARCH)" "powerpc64"
+ override ARCH := $(subst powerpc64,64,$(ARCH))
+ endif
+ ifeq "$(ARCH)" "aarch64"
+ override ARCH :=
+ override ARCHFLAG :=
+ endif
+ ifeq "$(ARCH)" "arm"
+ override ARCH :=
+ override ARCHFLAG :=
+ endif
+ ifeq "$(findstring mips,$(ARCH))" "mips"
+ override ARCHFLAG := -
+ endif
+
+ ifeq "$(SPLIT_DEBUG_SYMBOLS)" "YES"
+ DSYM = $(EXE).debug
+ endif
+endif
+
+LIMIT_DEBUG_INFO_FLAGS =
+NO_LIMIT_DEBUG_INFO_FLAGS =
+ifneq (,$(findstring clang,$(CC)))
+ LIMIT_DEBUG_INFO_FLAGS += -flimit-debug-info
+ NO_LIMIT_DEBUG_INFO_FLAGS += -fno-limit-debug-info
+endif
+
+DEBUG_INFO_FLAG ?= -g
+
+CFLAGS ?= $(DEBUG_INFO_FLAG) -O0 -fno-builtin
+ifeq "$(OS)" "Darwin"
+ CFLAGS += $(ARCHFLAG) $(ARCH) $(FRAMEWORK_INCLUDES) $(CFLAGS_EXTRAS) -I$(LLDB_BASE_DIR)include
+else
+ CFLAGS += $(ARCHFLAG)$(ARCH) $(FRAMEWORK_INCLUDES) $(CFLAGS_EXTRAS) -I$(LLDB_BASE_DIR)include
+endif
+
+CFLAGS += -include $(THIS_FILE_DIR)test_common.h $(TRIPLE_CFLAGS)
+
+# Use this one if you want to build one part of the result without debug information:
+ifeq "$(OS)" "Darwin"
+ CFLAGS_NO_DEBUG = -O0 $(ARCHFLAG) $(ARCH) $(FRAMEWORK_INCLUDES) $(CFLAGS_EXTRAS) $(TRIPLE_CFLAGS)
+else
+ CFLAGS_NO_DEBUG = -O0 $(ARCHFLAG)$(ARCH) $(FRAMEWORK_INCLUDES) $(CFLAGS_EXTRAS) $(TRIPLE_CFLAGS)
+endif
+
+ifeq "$(MAKE_DWO)" "YES"
+ CFLAGS += -gsplit-dwarf
+endif
+
+CXXFLAGS += -std=c++11
+CXXFLAGS += $(CFLAGS)
+LD = $(CC)
+LDFLAGS ?= $(CFLAGS)
+LDFLAGS += $(LD_EXTRAS)
+ifeq (,$(filter $(OS), Windows_NT Android))
+ ifneq (,$(filter YES,$(ENABLE_THREADS)))
+ LDFLAGS += -pthread
+ endif
+endif
+OBJECTS =
+EXE ?= a.out
+
+ifneq "$(DYLIB_NAME)" ""
+ ifeq "$(OS)" "Darwin"
+ DYLIB_FILENAME = lib$(DYLIB_NAME).dylib
+ DYLIB_EXECUTABLE_PATH ?= @executable_path
+ else ifeq "$(OS)" "Windows_NT"
+ DYLIB_FILENAME = $(DYLIB_NAME).dll
+ else
+ DYLIB_FILENAME = lib$(DYLIB_NAME).so
+ endif
+endif
+
+# Function that returns the counterpart C++ compiler, given $(CC) as arg.
+cxx_compiler_notdir = $(if $(findstring clang,$(1)), \
+ $(subst clang,clang++,$(1)), \
+ $(if $(findstring icc,$(1)), \
+ $(subst icc,icpc,$(1)), \
+ $(if $(findstring llvm-gcc,$(1)), \
+ $(subst llvm-gcc,llvm-g++,$(1)), \
+ $(if $(findstring gcc,$(1)), \
+ $(subst gcc,g++,$(1)), \
+ $(subst cc,c++,$(1))))))
+cxx_compiler = $(if $(findstring /,$(1)),$(join $(dir $(1)), $(call cxx_compiler_notdir,$(notdir $(1)))),$(call cxx_compiler_notdir,$(1)))
+
+# Function that returns the C++ linker, given $(CC) as arg.
+cxx_linker_notdir = $(if $(findstring clang,$(1)), \
+ $(subst clang,clang++,$(1)), \
+ $(if $(findstring icc,$(1)), \
+ $(subst icc,icpc,$(1)), \
+ $(if $(findstring llvm-gcc,$(1)), \
+ $(subst llvm-gcc,llvm-g++,$(1)), \
+ $(if $(findstring gcc,$(1)), \
+ $(subst gcc,g++,$(1)), \
+ $(subst cc,c++,$(1))))))
+cxx_linker = $(if $(findstring /,$(1)),$(join $(dir $(1)), $(call cxx_linker_notdir,$(notdir $(1)))),$(call cxx_linker_notdir,$(1)))
+
+OBJCOPY := $(CROSS_COMPILE)objcopy
+
+#----------------------------------------------------------------------
+# Windows specific options
+#----------------------------------------------------------------------
+ifeq "$(OS)" "Windows_NT"
+ ifneq (,$(findstring clang,$(CC)))
+ # Clang for Windows doesn't support C++ Exceptions
+ CXXFLAGS += -fno-exceptions
+ CXXFLAGS += -D_HAS_EXCEPTIONS=0
+ ifeq "$(VisualStudioVersion)" "14.0"
+ CXXFLAGS += -fms-compatibility-version=19.0
+ endif
+ # The MSVC linker doesn't understand long section names
+ # generated by the clang compiler.
+ LDFLAGS += -fuse-ld=lld
+ endif
+endif
+
+#----------------------------------------------------------------------
+# Android specific options
+#----------------------------------------------------------------------
+ifeq "$(OS)" "Android"
+ ifdef PIE
+ LDFLAGS += -pie
+ endif
+ replace_with = $(if $(findstring clang,$(1)), \
+ $(subst clang,$(2),$(1)), \
+ $(if $(findstring gcc,$(1)), \
+ $(subst gcc,$(2),$(1)), \
+ $(subst cc,$(2),$(1))))
+ ifeq "$(notdir $(CC))" "$(CC)"
+ replace_cc_with = $(call replace_with,$(CC),$(1))
+ else
+ replace_cc_with = $(join $(dir $(CC)),$(call replace_with,$(notdir $(CC)),$(1)))
+ endif
+ OBJCOPY = $(call replace_cc_with,objcopy)
+ AR = $(call replace_cc_with,ar)
+endif
+
+#----------------------------------------------------------------------
+# C++ standard library options
+#----------------------------------------------------------------------
+ifeq (1,$(USE_LIBSTDCPP))
+ # Clang requires an extra flag: -stdlib=libstdc++
+ ifneq (,$(findstring clang,$(CC)))
+ CXXFLAGS += -stdlib=libstdc++
+ LDFLAGS += -stdlib=libstdc++
+ endif
+endif
+
+ifeq (1,$(USE_LIBCPP))
+ # Clang requires an extra flag: -stdlib=libstdc++
+ ifneq (,$(findstring clang,$(CC)))
+ ifeq "$(OS)" "Linux"
+ # This is the default install location on Ubuntu 14.04
+ ifneq ($(wildcard /usr/include/c++/v1/.),)
+ CXXFLAGS += -stdlib=libc++ -DLLDB_USING_LIBCPP
+ LDFLAGS += -stdlib=libc++
+ CXXFLAGS += -I/usr/include/c++/v1
+ endif
+ else
+ CXXFLAGS += -stdlib=libc++ -DLLDB_USING_LIBCPP
+ LDFLAGS += -stdlib=libc++
+ endif
+ endif
+endif
+
+#----------------------------------------------------------------------
+# dylib settings
+#----------------------------------------------------------------------
+ifneq "$(strip $(DYLIB_C_SOURCES))" ""
+ DYLIB_OBJECTS +=$(strip $(DYLIB_C_SOURCES:.c=.o))
+endif
+
+ifneq "$(strip $(DYLIB_OBJC_SOURCES))" ""
+ DYLIB_OBJECTS +=$(strip $(DYLIB_OBJC_SOURCES:.m=.o))
+endif
+
+ifneq "$(strip $(DYLIB_CXX_SOURCES))" ""
+ DYLIB_OBJECTS +=$(strip $(DYLIB_CXX_SOURCES:.cpp=.o))
+ CXX = $(call cxx_compiler,$(CC))
+ LD = $(call cxx_linker,$(CC))
+endif
+
+#----------------------------------------------------------------------
+# Check if we have any C source files
+#----------------------------------------------------------------------
+ifneq "$(strip $(C_SOURCES))" ""
+ OBJECTS +=$(strip $(C_SOURCES:.c=.o))
+endif
+
+#----------------------------------------------------------------------
+# Check if we have any C++ source files
+#----------------------------------------------------------------------
+ifneq "$(strip $(CXX_SOURCES))" ""
+ OBJECTS +=$(strip $(CXX_SOURCES:.cpp=.o))
+ CXX = $(call cxx_compiler,$(CC))
+ LD = $(call cxx_linker,$(CC))
+endif
+
+#----------------------------------------------------------------------
+# Check if we have any ObjC source files
+#----------------------------------------------------------------------
+ifneq "$(strip $(OBJC_SOURCES))" ""
+ OBJECTS +=$(strip $(OBJC_SOURCES:.m=.o))
+ LDFLAGS +=-lobjc
+endif
+
+#----------------------------------------------------------------------
+# Check if we have any ObjC++ source files
+#----------------------------------------------------------------------
+ifneq "$(strip $(OBJCXX_SOURCES))" ""
+ OBJECTS +=$(strip $(OBJCXX_SOURCES:.mm=.o))
+ CXX = $(call cxx_compiler,$(CC))
+ LD = $(call cxx_linker,$(CC))
+ ifeq "$(findstring lobjc,$(LDFLAGS))" ""
+ LDFLAGS +=-lobjc
+ endif
+endif
+
+#----------------------------------------------------------------------
+# Check if we have any C source files for archive
+#----------------------------------------------------------------------
+ifneq "$(strip $(ARCHIVE_C_SOURCES))" ""
+ ARCHIVE_OBJECTS +=$(strip $(ARCHIVE_C_SOURCES:.c=.o))
+endif
+
+#----------------------------------------------------------------------
+# Check if we have any C++ source files for archive
+#----------------------------------------------------------------------
+ifneq "$(strip $(ARCHIVE_CXX_SOURCES))" ""
+ ARCHIVE_OBJECTS +=$(strip $(ARCHIVE_CXX_SOURCES:.cpp=.o))
+ CXX = $(call cxx_compiler,$(CC))
+ LD = $(call cxx_linker,$(CC))
+endif
+
+#----------------------------------------------------------------------
+# Check if we have any ObjC source files for archive
+#----------------------------------------------------------------------
+ifneq "$(strip $(ARCHIVE_OBJC_SOURCES))" ""
+ ARCHIVE_OBJECTS +=$(strip $(ARCHIVE_OBJC_SOURCES:.m=.o))
+ LDFLAGS +=-lobjc
+endif
+
+#----------------------------------------------------------------------
+# Check if we have any ObjC++ source files for archive
+#----------------------------------------------------------------------
+ifneq "$(strip $(ARCHIVE_OBJCXX_SOURCES))" ""
+ ARCHIVE_OBJECTS +=$(strip $(ARCHIVE_OBJCXX_SOURCES:.mm=.o))
+ CXX = $(call cxx_compiler,$(CC))
+ LD = $(call cxx_linker,$(CC))
+ ifeq "$(findstring lobjc,$(LDFLAGS))" ""
+ LDFLAGS +=-lobjc
+ endif
+endif
+
+#----------------------------------------------------------------------
+# Check if we are compiling with gcc 4.6
+#----------------------------------------------------------------------
+ifneq "$(strip $(CXX_SOURCES) $(OBJCXX_SOURCES))" ""
+ifneq "$(filter g++,$(CXX))" ""
+ CXXVERSION = $(shell $(CXX) -dumpversion | cut -b 1-3)
+ ifeq "$(CXXVERSION)" "4.6"
+ # GCC 4.6 cannot handle -std=c++11, so replace it with -std=c++0x
+ # instead. FIXME: remove once GCC version is upgraded.
+ override CXXFLAGS := $(subst -std=c++11,-std=c++0x,$(CXXFLAGS))
+ endif
+endif
+endif
+
+#----------------------------------------------------------------------
+# DYLIB_ONLY variable can be used to skip the building of a.out.
+# See the sections below regarding dSYM file as well as the building of
+# EXE from all the objects.
+#----------------------------------------------------------------------
+
+#----------------------------------------------------------------------
+# Make the dSYM file from the executable if $(MAKE_DSYM) != "NO"
+#----------------------------------------------------------------------
+ifneq "$(DYLIB_ONLY)" "YES"
+$(DSYM) : $(EXE)
+ifeq "$(OS)" "Darwin"
+ifneq "$(MAKE_DSYM)" "NO"
+ "$(DS)" $(DSFLAGS) -o "$(DSYM)" "$(EXE)"
+endif
+else
+ifeq "$(SPLIT_DEBUG_SYMBOLS)" "YES"
+ $(OBJCOPY) --only-keep-debug "$(EXE)" "$(DSYM)"
+ $(OBJCOPY) --strip-debug --add-gnu-debuglink="$(DSYM)" "$(EXE)" "$(EXE)"
+endif
+endif
+endif
+
+#----------------------------------------------------------------------
+# Compile the executable from all the objects.
+#----------------------------------------------------------------------
+ifneq "$(DYLIB_NAME)" ""
+ifeq "$(DYLIB_ONLY)" ""
+$(EXE) : $(OBJECTS) $(ARCHIVE_NAME) $(DYLIB_FILENAME)
+ $(LD) $(OBJECTS) $(ARCHIVE_NAME) -L. -l$(DYLIB_NAME) $(LDFLAGS) -o "$(EXE)"
+else
+EXE = $(DYLIB_FILENAME)
+endif
+else
+$(EXE) : $(OBJECTS) $(ARCHIVE_NAME)
+ $(LD) $(OBJECTS) $(LDFLAGS) $(ARCHIVE_NAME) -o "$(EXE)"
+endif
+
+#----------------------------------------------------------------------
+# Make the archive
+#----------------------------------------------------------------------
+ifneq "$(ARCHIVE_NAME)" ""
+ifeq "$(OS)" "Darwin"
+$(ARCHIVE_NAME) : $(ARCHIVE_OBJECTS)
+ $(AR) $(ARFLAGS) $(ARCHIVE_NAME) $(ARCHIVE_OBJECTS)
+ $(RM) $(ARCHIVE_OBJECTS)
+else
+$(ARCHIVE_NAME) : $(foreach ar_obj,$(ARCHIVE_OBJECTS),$(ARCHIVE_NAME)($(ar_obj)))
+endif
+endif
+
+#----------------------------------------------------------------------
+# Make the dylib
+#----------------------------------------------------------------------
+$(DYLIB_OBJECTS) : CFLAGS += -DCOMPILING_LLDB_TEST_DLL
+
+$(DYLIB_FILENAME) : $(DYLIB_OBJECTS)
+ifeq "$(OS)" "Darwin"
+ $(LD) $(DYLIB_OBJECTS) $(LDFLAGS) -install_name "$(DYLIB_EXECUTABLE_PATH)/$(DYLIB_FILENAME)" -dynamiclib -o "$(DYLIB_FILENAME)"
+ifneq "$(MAKE_DSYM)" "NO"
+ifneq "$(DS)" ""
+ "$(DS)" $(DSFLAGS) "$(DYLIB_FILENAME)"
+endif
+endif
+else
+ $(LD) $(DYLIB_OBJECTS) $(LDFLAGS) -shared -o "$(DYLIB_FILENAME)"
+ifeq "$(SPLIT_DEBUG_SYMBOLS)" "YES"
+ $(OBJCOPY) --only-keep-debug "$(DYLIB_FILENAME)" "$(DYLIB_FILENAME).debug"
+ $(OBJCOPY) --strip-debug --add-gnu-debuglink="$(DYLIB_FILENAME).debug" "$(DYLIB_FILENAME)" "$(DYLIB_FILENAME)"
+endif
+endif
+
+#----------------------------------------------------------------------
+# Automatic variables based on items already entered. Below we create
+# an object's lists from the list of sources by replacing all entries
+# that end with .c with .o, and we also create a list of prerequisite
+# files by replacing all .c files with .d.
+#----------------------------------------------------------------------
+PREREQS := $(OBJECTS:.o=.d)
+DWOS := $(OBJECTS:.o=.dwo) $(ARCHIVE_OBJECTS:.o=.dwo)
+ifneq "$(DYLIB_NAME)" ""
+ DYLIB_PREREQS := $(DYLIB_OBJECTS:.o=.d)
+ DYLIB_DWOS := $(DYLIB_OBJECTS:.o=.dwo)
+endif
+
+#----------------------------------------------------------------------
+# Rule for Generating Prerequisites Automatically using .d files and
+# the compiler -MM option. The -M option will list all system headers,
+# and the -MM option will list all non-system dependencies.
+#----------------------------------------------------------------------
+ifeq "$(HOST_OS)" "Windows_NT"
+ JOIN_CMD = &
+ QUOTE = "
+else
+ JOIN_CMD = ;
+ QUOTE = '
+endif
+
+%.d: %.c
+ @rm -f $@ $(JOIN_CMD) \
+ $(CC) -M $(CFLAGS) $< > $@.tmp && \
+ sed $(QUOTE)s,\($*\)\.o[ :]*,\1.o $@ : ,g$(QUOTE) < $@.tmp > $@ $(JOIN_CMD) \
+ rm -f $@.tmp
+
+%.d: %.cpp
+ @rm -f $@ $(JOIN_CMD) \
+ $(CXX) -M $(CXXFLAGS) $< > $@.tmp && \
+ sed $(QUOTE)s,\($*\)\.o[ :]*,\1.o $@ : ,g$(QUOTE) < $@.tmp > $@ $(JOIN_CMD) \
+ rm -f $@.tmp
+
+%.d: %.m
+ @rm -f $@ $(JOIN_CMD) \
+ $(CC) -M $(CFLAGS) $< > $@.tmp && \
+ sed $(QUOTE)s,\($*\)\.o[ :]*,\1.o $@ : ,g$(QUOTE) < $@.tmp > $@ $(JOIN_CMD) \
+ rm -f $@.tmp
+
+%.d: %.mm
+ @rm -f $@ $(JOIN_CMD) \
+ $(CXX) -M $(CXXFLAGS) $< > $@.tmp && \
+ sed $(QUOTE)s,\($*\)\.o[ :]*,\1.o $@ : ,g$(QUOTE) < $@.tmp > $@ $(JOIN_CMD) \
+ rm -f $@.tmp
+
+#----------------------------------------------------------------------
+# Include all of the makefiles for each source file so we don't have
+# to manually track all of the prerequisites for each source file.
+#----------------------------------------------------------------------
+sinclude $(PREREQS)
+ifneq "$(DYLIB_NAME)" ""
+ sinclude $(DYLIB_PREREQS)
+endif
+
+# Define a suffix rule for .mm -> .o
+.SUFFIXES: .mm .o
+.mm.o:
+ $(CXX) $(CXXFLAGS) -c $<
+
+.PHONY: clean
+dsym: $(DSYM)
+all: $(EXE) $(DSYM)
+clean::
+ $(RM) $(OBJECTS) $(PREREQS) $(PREREQS:.d=.d.tmp) $(DWOS) $(ARCHIVE_NAME) $(ARCHIVE_OBJECTS)
+ifneq "$(DYLIB_NAME)" ""
+ $(RM) -r $(DYLIB_FILENAME).dSYM
+ $(RM) $(DYLIB_OBJECTS) $(DYLIB_PREREQS) $(DYLIB_PREREQS:.d=.d.tmp) $(DYLIB_DWOS) $(DYLIB_FILENAME) $(DYLIB_FILENAME).debug
+endif
+ifneq "$(DSYM)" ""
+ $(RM) -r "$(DSYM)"
+endif
+ifeq "$(OS)" "Windows_NT"
+# http://llvm.org/pr24589
+ IF EXIST "$(EXE)" del "$(EXE)"
+ $(RM) $(wildcard *.manifest *.pdb *.ilk)
+ifneq "$(DYLIB_NAME)" ""
+ $(RM) $(DYLIB_NAME).lib $(DYLIB_NAME).exp
+endif
+else
+ $(RM) "$(EXE)"
+endif
+
+#----------------------------------------------------------------------
+# From http://blog.melski.net/tag/debugging-makefiles/
+#
+# Usage: make print-CC print-CXX print-LD
+#----------------------------------------------------------------------
+print-%:
+ @echo '$*=$($*)'
+ @echo ' origin = $(origin $*)'
+ @echo ' flavor = $(flavor $*)'
+ @echo ' value = $(value $*)'
+
+### Local Variables: ###
+### mode:makefile ###
+### End: ###
diff --git a/packages/Python/lldbsuite/test/make/test_common.h b/packages/Python/lldbsuite/test/make/test_common.h
new file mode 100644
index 000000000000..6f819706366e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/make/test_common.h
@@ -0,0 +1,19 @@
+// This header is included in all the test programs (C and C++) and provides a
+// hook for dealing with platform-specifics.
+#if defined(_WIN32) || defined(_WIN64)
+#ifdef COMPILING_LLDB_TEST_DLL
+#define LLDB_TEST_API __declspec(dllexport)
+#else
+#define LLDB_TEST_API __declspec(dllimport)
+#endif
+#else
+#define LLDB_TEST_API
+#endif
+
+#if defined(__cplusplus) && defined(_MSC_VER) && (_HAS_EXCEPTIONS == 0)
+// Compiling MSVC libraries with _HAS_EXCEPTIONS=0, eliminates most but not all
+// calls to __uncaught_exception. Unfortunately, it does seem to eliminate
+// the delcaration of __uncaught_excpeiton. Including <eh.h> ensures that it is
+// declared. This may not be necessary after MSVC 12.
+#include <eh.h>
+#endif
diff --git a/packages/Python/lldbsuite/test/plugins/builder_base.py b/packages/Python/lldbsuite/test/plugins/builder_base.py
new file mode 100644
index 000000000000..c4e3dff5301c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/plugins/builder_base.py
@@ -0,0 +1,137 @@
+"""
+If the build* function is passed the compiler argument, for example, 'llvm-gcc',
+it is passed as a make variable to the make command. Otherwise, we check the
+LLDB_CC environment variable; if it is defined, it is passed as a make variable
+to the make command.
+
+If neither the compiler keyword argument nor the LLDB_CC environment variable is
+specified, no CC make variable is passed to the make command. The Makefile gets
+to define the default CC being used.
+
+Same idea holds for LLDB_ARCH environment variable, which maps to the ARCH make
+variable.
+"""
+
+import os, sys
+import platform
+import lldbsuite.test.lldbtest as lldbtest
+
+def getArchitecture():
+ """Returns the architecture in effect the test suite is running with."""
+ return os.environ["ARCH"] if "ARCH" in os.environ else ""
+
+def getCompiler():
+ """Returns the compiler in effect the test suite is running with."""
+ return os.environ["CC"] if "CC" in os.environ else "clang"
+
+def getArchFlag():
+ """Returns the flag required to specify the arch"""
+ compiler = getCompiler()
+ if compiler is None:
+ return ""
+ elif "gcc" in compiler:
+ archflag = "-m"
+ elif "clang" in compiler:
+ archflag = "-arch"
+ else:
+ archflag = None
+
+ return ("ARCHFLAG=" + archflag) if archflag else ""
+
+def getMake():
+ """Returns the name for GNU make"""
+ if platform.system() == "FreeBSD" or platform.system() == "NetBSD":
+ return "gmake"
+ else:
+ return "make"
+
+def getArchSpec(architecture):
+ """
+ Helper function to return the key-value string to specify the architecture
+ used for the make system.
+ """
+ arch = architecture if architecture else None
+ if not arch and "ARCH" in os.environ:
+ arch = os.environ["ARCH"]
+
+ return ("ARCH=" + arch) if arch else ""
+
+def getCCSpec(compiler):
+ """
+ Helper function to return the key-value string to specify the compiler
+ used for the make system.
+ """
+ cc = compiler if compiler else None
+ if not cc and "CC" in os.environ:
+ cc = os.environ["CC"]
+ if cc:
+ return "CC=\"%s\"" % cc
+ else:
+ return ""
+
+def getCmdLine(d):
+ """
+ Helper function to return a properly formatted command line argument(s)
+ string used for the make system.
+ """
+
+ # If d is None or an empty mapping, just return an empty string.
+ if not d:
+ return ""
+ pattern = '%s="%s"' if "win32" in sys.platform else "%s='%s'"
+
+ def setOrAppendVariable(k, v):
+ append_vars = ["CFLAGS_EXTRAS", "LD_EXTRAS"]
+ if k in append_vars and k in os.environ:
+ v = os.environ[k] + " " + v
+ return pattern % (k, v)
+ cmdline = " ".join([setOrAppendVariable(k, v) for k, v in list(d.items())])
+
+ return cmdline
+
+
+def buildDefault(sender=None, architecture=None, compiler=None, dictionary=None, clean=True):
+ """Build the binaries the default way."""
+ commands = []
+ if clean:
+ commands.append([getMake(), "clean", getCmdLine(dictionary)])
+ commands.append([getMake(), getArchSpec(architecture), getCCSpec(compiler), getCmdLine(dictionary)])
+
+ lldbtest.system(commands, sender=sender)
+
+ # True signifies that we can handle building default.
+ return True
+
+def buildDwarf(sender=None, architecture=None, compiler=None, dictionary=None, clean=True):
+ """Build the binaries with dwarf debug info."""
+ commands = []
+ if clean:
+ commands.append([getMake(), "clean", getCmdLine(dictionary)])
+ commands.append([getMake(), "MAKE_DSYM=NO", getArchSpec(architecture), getCCSpec(compiler), getCmdLine(dictionary)])
+
+ lldbtest.system(commands, sender=sender)
+ # True signifies that we can handle building dwarf.
+ return True
+
+def buildDwo(sender=None, architecture=None, compiler=None, dictionary=None, clean=True):
+ """Build the binaries with dwarf debug info."""
+ commands = []
+ if clean:
+ commands.append([getMake(), "clean", getCmdLine(dictionary)])
+ commands.append([getMake(), "MAKE_DSYM=NO", "MAKE_DWO=YES", getArchSpec(architecture), getCCSpec(compiler), getCmdLine(dictionary)])
+
+ lldbtest.system(commands, sender=sender)
+ # True signifies that we can handle building dwo.
+ return True
+
+def cleanup(sender=None, dictionary=None):
+ """Perform a platform-specific cleanup after the test."""
+ #import traceback
+ #traceback.print_stack()
+ commands = []
+ if os.path.isfile("Makefile"):
+ commands.append([getMake(), "clean", getCmdLine(dictionary)])
+
+ lldbtest.system(commands, sender=sender)
+ # True signifies that we can handle cleanup.
+ return True
diff --git a/packages/Python/lldbsuite/test/plugins/builder_darwin.py b/packages/Python/lldbsuite/test/plugins/builder_darwin.py
new file mode 100644
index 000000000000..dd07206e323b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/plugins/builder_darwin.py
@@ -0,0 +1,21 @@
+
+from __future__ import print_function
+import os
+import lldbsuite.test.lldbtest as lldbtest
+
+from builder_base import *
+
+#print("Hello, darwin plugin!")
+
+def buildDsym(sender=None, architecture=None, compiler=None, dictionary=None, clean=True):
+ """Build the binaries with dsym debug info."""
+ commands = []
+
+ if clean:
+ commands.append(["make", "clean", getCmdLine(dictionary)])
+ commands.append(["make", "MAKE_DSYM=YES", getArchSpec(architecture), getCCSpec(compiler), getCmdLine(dictionary)])
+
+ lldbtest.system(commands, sender=sender)
+
+ # True signifies that we can handle building dsym.
+ return True
diff --git a/packages/Python/lldbsuite/test/plugins/builder_freebsd.py b/packages/Python/lldbsuite/test/plugins/builder_freebsd.py
new file mode 100644
index 000000000000..e56be429823e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/plugins/builder_freebsd.py
@@ -0,0 +1,4 @@
+from builder_base import *
+
+def buildDsym(sender=None, architecture=None, compiler=None, dictionary=None, clean=True):
+ return False
diff --git a/packages/Python/lldbsuite/test/plugins/builder_linux2.py b/packages/Python/lldbsuite/test/plugins/builder_linux2.py
new file mode 100644
index 000000000000..e56be429823e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/plugins/builder_linux2.py
@@ -0,0 +1,4 @@
+from builder_base import *
+
+def buildDsym(sender=None, architecture=None, compiler=None, dictionary=None, clean=True):
+ return False
diff --git a/packages/Python/lldbsuite/test/plugins/builder_netbsd.py b/packages/Python/lldbsuite/test/plugins/builder_netbsd.py
new file mode 100644
index 000000000000..e56be429823e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/plugins/builder_netbsd.py
@@ -0,0 +1,4 @@
+from builder_base import *
+
+def buildDsym(sender=None, architecture=None, compiler=None, dictionary=None, clean=True):
+ return False
diff --git a/packages/Python/lldbsuite/test/plugins/builder_win32.py b/packages/Python/lldbsuite/test/plugins/builder_win32.py
new file mode 100644
index 000000000000..e56be429823e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/plugins/builder_win32.py
@@ -0,0 +1,4 @@
+from builder_base import *
+
+def buildDsym(sender=None, architecture=None, compiler=None, dictionary=None, clean=True):
+ return False
diff --git a/packages/Python/lldbsuite/test/python_api/.categories b/packages/Python/lldbsuite/test/python_api/.categories
new file mode 100644
index 000000000000..db8069c3b9ff
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/.categories
@@ -0,0 +1 @@
+pyapi
diff --git a/packages/Python/lldbsuite/test/python_api/breakpoint/Makefile b/packages/Python/lldbsuite/test/python_api/breakpoint/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/breakpoint/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/breakpoint/TestBreakpointAPI.py b/packages/Python/lldbsuite/test/python_api/breakpoint/TestBreakpointAPI.py
new file mode 100644
index 000000000000..1f4fa20b8304
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/breakpoint/TestBreakpointAPI.py
@@ -0,0 +1,45 @@
+"""
+Test SBBreakpoint APIs.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class BreakpointAPITestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @add_test_categories(['pyapi'])
+ def test_breakpoint_is_valid(self):
+ """Make sure that if an SBBreakpoint gets deleted its IsValid returns false."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create a breakpoint on main.c by name 'AFunction'.
+ breakpoint = target.BreakpointCreateByName('AFunction', 'a.out')
+ #print("breakpoint:", breakpoint)
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Now delete it:
+ did_delete = target.BreakpointDelete(breakpoint.GetID())
+ self.assertTrue (did_delete, "Did delete the breakpoint we just created.")
+
+ # Make sure we can't find it:
+ del_bkpt = target.FindBreakpointByID (breakpoint.GetID())
+ self.assertTrue (not del_bkpt, "We did delete the breakpoint.")
+
+ # Finally make sure the original breakpoint is no longer valid.
+ self.assertTrue (not breakpoint, "Breakpoint we deleted is no longer valid.")
diff --git a/packages/Python/lldbsuite/test/python_api/breakpoint/main.c b/packages/Python/lldbsuite/test/python_api/breakpoint/main.c
new file mode 100644
index 000000000000..2677594e622e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/breakpoint/main.c
@@ -0,0 +1,14 @@
+#include <stdio.h>
+
+void
+AFunction()
+{
+ printf ("I am a function.\n");
+}
+
+int
+main ()
+{
+ AFunction();
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/python_api/class_members/Makefile b/packages/Python/lldbsuite/test/python_api/class_members/Makefile
new file mode 100644
index 000000000000..0d7550f9f282
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/class_members/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+OBJCXX_SOURCES := main.mm
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/class_members/TestSBTypeClassMembers.py b/packages/Python/lldbsuite/test/python_api/class_members/TestSBTypeClassMembers.py
new file mode 100644
index 000000000000..e1d5520bcc3d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/class_members/TestSBTypeClassMembers.py
@@ -0,0 +1,77 @@
+"""
+Test SBType APIs to fetch member function types.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class SBTypeMemberFunctionsTest(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # We'll use the test method name as the exe_name.
+ self.exe_name = self.testMethodName
+ # Find the line number to break at.
+ self.source = 'main.mm'
+ self.line = line_number(self.source, '// set breakpoint here')
+
+ @skipUnlessDarwin
+ @add_test_categories(['pyapi'])
+ def test(self):
+ """Test SBType APIs to fetch member function types."""
+ d = {'EXE': self.exe_name}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ exe = os.path.join(os.getcwd(), self.exe_name)
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Create the breakpoint inside function 'main'.
+ breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Get Frame #0.
+ self.assertTrue(process.GetState() == lldb.eStateStopped)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
+ frame0 = thread.GetFrameAtIndex(0)
+
+ variable = frame0.FindVariable("d")
+ Derived = variable.GetType()
+ Base = Derived.GetDirectBaseClassAtIndex(0).GetType()
+
+ self.assertTrue(Derived.GetNumberOfMemberFunctions() == 2, "Derived declares two methods")
+ self.assertTrue(Derived.GetMemberFunctionAtIndex(0).GetType().GetFunctionReturnType().GetName() == "int", "Derived::dImpl returns int")
+
+ self.assertTrue(Base.GetNumberOfMemberFunctions() == 4, "Base declares three methods")
+ self.assertTrue(Base.GetMemberFunctionAtIndex(3).GetType().GetFunctionArgumentTypes().GetSize() == 3, "Base::sfunc takes three arguments")
+ self.assertTrue(Base.GetMemberFunctionAtIndex(3).GetName() == "sfunc", "Base::sfunc not found")
+ self.assertTrue(Base.GetMemberFunctionAtIndex(3).GetKind() == lldb.eMemberFunctionKindStaticMethod, "Base::sfunc is a static")
+ self.assertTrue(Base.GetMemberFunctionAtIndex(2).GetType().GetFunctionArgumentTypes().GetSize() == 0, "Base::dat takes no arguments")
+ self.assertTrue(Base.GetMemberFunctionAtIndex(1).GetType().GetFunctionArgumentTypes().GetTypeAtIndex(1).GetName() == "char", "Base::bar takes a second 'char' argument")
+ self.assertTrue(Base.GetMemberFunctionAtIndex(1).GetName() == "bar", "Base::bar not found")
+
+ variable = frame0.FindVariable("thingy")
+ Thingy = variable.GetType()
+
+ self.assertTrue(Thingy.GetNumberOfMemberFunctions() == 2, "Thingy declares two methods")
+
+ self.assertTrue(Thingy.GetMemberFunctionAtIndex(0).GetReturnType().GetName() == "id", "Thingy::init returns an id")
+ self.assertTrue(Thingy.GetMemberFunctionAtIndex(1).GetNumberOfArguments() == 2, "Thingy::foo takes two arguments")
+ self.assertTrue(Thingy.GetMemberFunctionAtIndex(1).GetArgumentTypeAtIndex(0).GetName() == "int", "Thingy::foo takes an int")
diff --git a/packages/Python/lldbsuite/test/python_api/class_members/main.mm b/packages/Python/lldbsuite/test/python_api/class_members/main.mm
new file mode 100644
index 000000000000..ff61b369ee1f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/class_members/main.mm
@@ -0,0 +1,47 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#import <Foundation/Foundation.h>
+
+class Base {
+public:
+ int foo(int x, int y) { return 1; }
+ char bar(int x, char y) { return 2; }
+ void dat() {}
+ static int sfunc(char, int, float) { return 3; }
+};
+
+class Derived: public Base {
+protected:
+ int dImpl() { return 1; }
+public:
+ float baz(float b) { return b + 1.0; }
+};
+
+@interface Thingy: NSObject {
+}
+- (id)init;
+- (id)fooWithBar: (int)bar andBaz:(id)baz;
+@end
+
+@implementation Thingy {
+}
+- (id)init {
+ return (self = [super init]);
+}
+- (id)fooWithBar: (int)bar andBaz:(id)baz {
+ return nil;
+}
+@end
+
+int main() {
+ Derived d;
+ Thingy *thingy = [[Thingy alloc] init];
+ return 0; // set breakpoint here
+}
diff --git a/packages/Python/lldbsuite/test/python_api/debugger/TestDebuggerAPI.py b/packages/Python/lldbsuite/test/python_api/debugger/TestDebuggerAPI.py
new file mode 100644
index 000000000000..98feda859ae9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/debugger/TestDebuggerAPI.py
@@ -0,0 +1,40 @@
+"""
+Test Debugger APIs.
+"""
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+
+
+class DebuggerAPITestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_debugger_api_boundary_condition(self):
+ """Exercise SBDebugger APIs with boundary conditions."""
+ self.dbg.HandleCommand(None)
+ self.dbg.SetDefaultArchitecture(None)
+ self.dbg.GetScriptingLanguage(None)
+ self.dbg.CreateTarget(None)
+ self.dbg.CreateTarget(None, None, None, True, lldb.SBError())
+ self.dbg.CreateTargetWithFileAndTargetTriple(None, None)
+ self.dbg.CreateTargetWithFileAndArch(None, None)
+ self.dbg.FindTargetWithFileAndArch(None, None)
+ self.dbg.SetInternalVariable(None, None, None)
+ self.dbg.GetInternalVariableValue(None, None)
+ # FIXME (filcab): We must first allow for the swig bindings to know if
+ # a Python callback is set. (Check python-typemaps.swig)
+ #self.dbg.SetLoggingCallback(None)
+ self.dbg.SetPrompt(None)
+ self.dbg.SetCurrentPlatform(None)
+ self.dbg.SetCurrentPlatformSDKRoot(None)
+
+ @add_test_categories(['pyapi'])
+ def test_debugger_delete_invalid_target(self):
+ """SBDebugger.DeleteTarget() should not crash LLDB given and invalid target."""
+ target = lldb.SBTarget()
+ self.assertFalse(target.IsValid())
+ self.dbg.DeleteTarget(target)
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/TestDefaultConstructorForAPIObjects.py b/packages/Python/lldbsuite/test/python_api/default-constructor/TestDefaultConstructorForAPIObjects.py
new file mode 100644
index 000000000000..aa3a6141326a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/TestDefaultConstructorForAPIObjects.py
@@ -0,0 +1,395 @@
+"""
+Test lldb Python API object's default constructor and make sure it is invalid
+after initial construction.
+
+There are also some cases of boundary condition testings sprinkled throughout
+the tests where None is passed to SB API which expects (const char *) in the
+C++ API counterpart. Passing None should not crash lldb!
+
+There are three exceptions to the above general rules, though; API objects
+SBCommadnReturnObject, SBStream, and SBSymbolContextList, are all valid objects
+after default construction.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class APIDefaultConstructorTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBAddress(self):
+ obj = lldb.SBAddress()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_address
+ sb_address.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBBlock(self):
+ obj = lldb.SBBlock()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_block
+ sb_block.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBBreakpoint(self):
+ obj = lldb.SBBreakpoint()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_breakpoint
+ sb_breakpoint.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBBreakpointLocation(self):
+ obj = lldb.SBBreakpointLocation()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_breakpointlocation
+ sb_breakpointlocation.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBBroadcaster(self):
+ obj = lldb.SBBroadcaster()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_broadcaster
+ sb_broadcaster.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBCommandReturnObject(self):
+ """SBCommandReturnObject object is valid after default construction."""
+ obj = lldb.SBCommandReturnObject()
+ if self.TraceOn():
+ print(obj)
+ self.assertTrue(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBCommunication(self):
+ obj = lldb.SBCommunication()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_communication
+ sb_communication.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBCompileUnit(self):
+ obj = lldb.SBCompileUnit()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_compileunit
+ sb_compileunit.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBDebugger(self):
+ obj = lldb.SBDebugger()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_debugger
+ sb_debugger.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ # darwin: This test passes with swig 3.0.2, fails w/3.0.5 other tests fail with 2.0.12 http://llvm.org/pr23488
+ def test_SBError(self):
+ obj = lldb.SBError()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_error
+ sb_error.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBEvent(self):
+ obj = lldb.SBEvent()
+ # This is just to test that typemap, as defined in lldb.swig, works.
+ obj2 = lldb.SBEvent(0, "abc")
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_event
+ sb_event.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ def test_SBFileSpec(self):
+ obj = lldb.SBFileSpec()
+ # This is just to test that FileSpec(None) does not crash.
+ obj2 = lldb.SBFileSpec(None, True)
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_filespec
+ sb_filespec.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBFrame(self):
+ obj = lldb.SBFrame()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_frame
+ sb_frame.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBFunction(self):
+ obj = lldb.SBFunction()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_function
+ sb_function.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBInstruction(self):
+ obj = lldb.SBInstruction()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_instruction
+ sb_instruction.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBInstructionList(self):
+ obj = lldb.SBInstructionList()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_instructionlist
+ sb_instructionlist.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBLineEntry(self):
+ obj = lldb.SBLineEntry()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_lineentry
+ sb_lineentry.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBListener(self):
+ obj = lldb.SBListener()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_listener
+ sb_listener.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ # Py3 asserts due to a bug in SWIG. Trying to upstream a patch to fix this in 3.0.8
+ @skipIf(py_version=['>=', (3,0)], swig_version=['<', (3,0,8)])
+ def test_SBModule(self):
+ obj = lldb.SBModule()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_module
+ sb_module.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBProcess(self):
+ obj = lldb.SBProcess()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_process
+ sb_process.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBSection(self):
+ obj = lldb.SBSection()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_section
+ sb_section.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBStream(self):
+ """SBStream object is valid after default construction."""
+ obj = lldb.SBStream()
+ if self.TraceOn():
+ print(obj)
+ self.assertTrue(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBStringList(self):
+ obj = lldb.SBStringList()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_stringlist
+ sb_stringlist.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBSymbol(self):
+ obj = lldb.SBSymbol()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_symbol
+ sb_symbol.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBSymbolContext(self):
+ obj = lldb.SBSymbolContext()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_symbolcontext
+ sb_symbolcontext.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBSymbolContextList(self):
+ """SBSymbolContextList object is valid after default construction."""
+ obj = lldb.SBSymbolContextList()
+ if self.TraceOn():
+ print(obj)
+ self.assertTrue(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBTarget(self):
+ obj = lldb.SBTarget()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_target
+ sb_target.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBThread(self):
+ obj = lldb.SBThread()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_thread
+ sb_thread.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBType(self):
+ try:
+ obj = lldb.SBType()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # If we reach here, the test fails.
+ self.fail("lldb.SBType() should fail, not succeed!")
+ except:
+ # Exception is expected.
+ return
+
+ # Unreachable code because lldb.SBType() should fail.
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_type
+ sb_type.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBTypeList(self):
+ """SBTypeList object is valid after default construction."""
+ obj = lldb.SBTypeList()
+ if self.TraceOn():
+ print(obj)
+ self.assertTrue(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBValue(self):
+ obj = lldb.SBValue()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_value
+ sb_value.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBValueList(self):
+ obj = lldb.SBValueList()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_valuelist
+ sb_valuelist.fuzz_obj(obj)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_SBWatchpoint(self):
+ obj = lldb.SBWatchpoint()
+ if self.TraceOn():
+ print(obj)
+ self.assertFalse(obj)
+ # Do fuzz testing on the invalid obj, it should not crash lldb.
+ import sb_watchpoint
+ sb_watchpoint.fuzz_obj(obj)
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_address.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_address.py
new file mode 100644
index 000000000000..f0e979543a4c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_address.py
@@ -0,0 +1,22 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.GetFileAddress()
+ obj.GetLoadAddress(lldb.SBTarget())
+ obj.SetLoadAddress(0xffff, lldb.SBTarget())
+ obj.OffsetAddress(sys.maxsize)
+ obj.GetDescription(lldb.SBStream())
+ obj.GetSection()
+ obj.GetSymbolContext(lldb.eSymbolContextEverything)
+ obj.GetModule()
+ obj.GetCompileUnit()
+ obj.GetFunction()
+ obj.GetBlock()
+ obj.GetSymbol()
+ obj.GetLineEntry()
+ obj.Clear()
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_block.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_block.py
new file mode 100644
index 000000000000..3eeb24b42734
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_block.py
@@ -0,0 +1,17 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.IsInlined()
+ obj.GetInlinedName()
+ obj.GetInlinedCallSiteFile()
+ obj.GetInlinedCallSiteLine()
+ obj.GetInlinedCallSiteColumn()
+ obj.GetParent()
+ obj.GetSibling()
+ obj.GetFirstChild()
+ obj.GetDescription(lldb.SBStream())
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpoint.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpoint.py
new file mode 100644
index 000000000000..2c05990edae0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpoint.py
@@ -0,0 +1,36 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.GetID()
+ obj.ClearAllBreakpointSites()
+ obj.FindLocationByAddress(sys.maxsize)
+ obj.FindLocationIDByAddress(sys.maxsize)
+ obj.FindLocationByID(0)
+ obj.GetLocationAtIndex(0)
+ obj.SetEnabled(True)
+ obj.IsEnabled()
+ obj.GetHitCount()
+ obj.SetIgnoreCount(1)
+ obj.GetIgnoreCount()
+ obj.SetCondition("i >= 10")
+ obj.GetCondition()
+ obj.SetThreadID(0)
+ obj.GetThreadID()
+ obj.SetThreadIndex(0)
+ obj.GetThreadIndex()
+ obj.SetThreadName("worker thread")
+ obj.GetThreadName()
+ obj.SetQueueName("my queue")
+ obj.GetQueueName()
+ obj.SetScriptCallbackFunction(None)
+ obj.SetScriptCallbackBody (None)
+ obj.GetNumResolvedLocations()
+ obj.GetNumLocations()
+ obj.GetDescription(lldb.SBStream())
+ for bp_loc in obj:
+ s = str(bp_loc)
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpointlocation.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpointlocation.py
new file mode 100644
index 000000000000..2251892643b3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_breakpointlocation.py
@@ -0,0 +1,28 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.GetAddress()
+ obj.GetLoadAddress()
+ obj.SetEnabled(True)
+ obj.IsEnabled()
+ obj.SetCondition("i >= 10")
+ obj.GetCondition()
+ obj.SetThreadID(0)
+ obj.GetThreadID()
+ obj.SetThreadIndex(0)
+ obj.GetThreadIndex()
+ obj.SetThreadName("worker thread")
+ obj.GetThreadName()
+ obj.SetQueueName("my queue")
+ obj.GetQueueName()
+ obj.IsResolved()
+ obj.GetDescription(lldb.SBStream(), lldb.eDescriptionLevelVerbose)
+ breakpoint = obj.GetBreakpoint()
+ # Do fuzz testing on the breakpoint obj, it should not crash lldb.
+ import sb_breakpoint
+ sb_breakpoint.fuzz_obj(breakpoint)
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_broadcaster.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_broadcaster.py
new file mode 100644
index 000000000000..27539e855cdd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_broadcaster.py
@@ -0,0 +1,20 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.BroadcastEventByType(lldb.eBreakpointEventTypeInvalidType, True)
+ obj.BroadcastEvent(lldb.SBEvent(), False)
+ listener = lldb.SBListener("fuzz_testing")
+ obj.AddInitialEventsToListener(listener, 0xffffffff)
+ obj.AddInitialEventsToListener(listener, 0)
+ obj.AddListener(listener, 0xffffffff)
+ obj.AddListener(listener, 0)
+ obj.GetName()
+ obj.EventTypeHasListeners(0)
+ obj.RemoveListener(listener, 0xffffffff)
+ obj.RemoveListener(listener, 0)
+ obj.Clear()
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_communication.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_communication.py
new file mode 100644
index 000000000000..d4b90840657b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_communication.py
@@ -0,0 +1,28 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ broadcaster = obj.GetBroadcaster()
+ # Do fuzz testing on the broadcaster obj, it should not crash lldb.
+ import sb_broadcaster
+ sb_broadcaster.fuzz_obj(broadcaster)
+ obj.AdoptFileDesriptor(0, False)
+ obj.AdoptFileDesriptor(1, False)
+ obj.AdoptFileDesriptor(2, False)
+ obj.Connect("file:/tmp/myfile")
+ obj.Connect(None)
+ obj.Disconnect()
+ obj.IsConnected()
+ obj.GetCloseOnEOF()
+ obj.SetCloseOnEOF(True)
+ obj.SetCloseOnEOF(False)
+ #obj.Write(None, sys.maxint, None)
+ #obj.Read(None, sys.maxint, 0xffffffff, None)
+ obj.ReadThreadStart()
+ obj.ReadThreadStop()
+ obj.ReadThreadIsRunning()
+ obj.SetReadThreadBytesReceivedCallback(None, None)
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_compileunit.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_compileunit.py
new file mode 100644
index 000000000000..92755ffa395d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_compileunit.py
@@ -0,0 +1,15 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.GetFileSpec()
+ obj.GetNumLineEntries()
+ obj.GetLineEntryAtIndex(0xffffffff)
+ obj.FindLineEntryIndex(0, 0xffffffff, None)
+ obj.GetDescription(lldb.SBStream())
+ for line_entry in obj:
+ s = str(line_entry)
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_debugger.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_debugger.py
new file mode 100644
index 000000000000..e7c188f09bad
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_debugger.py
@@ -0,0 +1,56 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.SetAsync(True)
+ obj.SetAsync(False)
+ obj.GetAsync()
+ obj.SkipLLDBInitFiles(True)
+ obj.SetInputFileHandle(None, True)
+ obj.SetOutputFileHandle(None, True)
+ obj.SetErrorFileHandle(None, True)
+ obj.GetInputFileHandle()
+ obj.GetOutputFileHandle()
+ obj.GetErrorFileHandle()
+ obj.GetCommandInterpreter()
+ obj.HandleCommand("nothing here")
+ listener = obj.GetListener()
+ obj.HandleProcessEvent(lldb.SBProcess(), lldb.SBEvent(), None, None)
+ obj.CreateTargetWithFileAndTargetTriple("a.out", "A-B-C")
+ obj.CreateTargetWithFileAndArch("b.out", "arm")
+ obj.CreateTarget("c.out")
+ obj.DeleteTarget(lldb.SBTarget())
+ obj.GetTargetAtIndex(0xffffffff)
+ obj.FindTargetWithProcessID(0)
+ obj.FindTargetWithFileAndArch("a.out", "arm")
+ obj.GetNumTargets()
+ obj.GetSelectedTarget()
+ obj.GetSourceManager()
+ obj.SetSelectedTarget(lldb.SBTarget())
+ obj.SetCurrentPlatformSDKRoot("tmp/sdk-root")
+ try:
+ obj.DispatchInput(None)
+ except Exception:
+ pass
+ obj.DispatchInputInterrupt()
+ obj.DispatchInputEndOfFile()
+ obj.GetInstanceName()
+ obj.GetDescription(lldb.SBStream())
+ obj.GetTerminalWidth()
+ obj.SetTerminalWidth(0xffffffff)
+ obj.GetID()
+ obj.GetPrompt()
+ obj.SetPrompt("Hi, Mom!")
+ obj.GetScriptLanguage()
+ obj.SetScriptLanguage(lldb.eScriptLanguageNone)
+ obj.SetScriptLanguage(lldb.eScriptLanguagePython)
+ obj.GetCloseInputOnEOF()
+ obj.SetCloseInputOnEOF(True)
+ obj.SetCloseInputOnEOF(False)
+ obj.Clear()
+ for target in obj:
+ s = str(target)
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_error.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_error.py
new file mode 100644
index 000000000000..7e069323bf3f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_error.py
@@ -0,0 +1,25 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.GetCString()
+ obj.Fail()
+ obj.Success()
+ obj.GetError()
+ obj.GetType()
+ obj.SetError(5, lldb.eErrorTypeGeneric)
+ obj.SetErrorToErrno()
+ obj.SetErrorToGenericError()
+ obj.SetErrorString("xyz")
+ obj.SetErrorString(None)
+ obj.SetErrorStringWithFormat("%s!", "error")
+ obj.SetErrorStringWithFormat(None)
+ obj.SetErrorStringWithFormat("error")
+ obj.SetErrorStringWithFormat("%s %s", "warning", "danger")
+ obj.SetErrorStringWithFormat("%s %s %s", "danger", "will", "robinson")
+ obj.GetDescription(lldb.SBStream())
+ obj.Clear()
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_event.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_event.py
new file mode 100644
index 000000000000..c64f9ba927c2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_event.py
@@ -0,0 +1,17 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.GetDataFlavor()
+ obj.GetType()
+ broadcaster = obj.GetBroadcaster()
+ # Do fuzz testing on the broadcaster obj, it should not crash lldb.
+ import sb_broadcaster
+ sb_broadcaster.fuzz_obj(broadcaster)
+ obj.BroadcasterMatchesRef(broadcaster)
+ obj.GetDescription(lldb.SBStream())
+ obj.Clear()
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_filespec.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_filespec.py
new file mode 100644
index 000000000000..3aa9235b8a16
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_filespec.py
@@ -0,0 +1,14 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.Exists()
+ obj.ResolveExecutableLocation()
+ obj.GetFilename()
+ obj.GetDirectory()
+ obj.GetPath(None, 0)
+ obj.GetDescription(lldb.SBStream())
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_frame.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_frame.py
new file mode 100644
index 000000000000..41edaff02ed7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_frame.py
@@ -0,0 +1,37 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.GetFrameID()
+ obj.GetPC()
+ obj.SetPC(0xffffffff)
+ obj.GetSP()
+ obj.GetFP()
+ obj.GetPCAddress()
+ obj.GetSymbolContext(0)
+ obj.GetModule()
+ obj.GetCompileUnit()
+ obj.GetFunction()
+ obj.GetSymbol()
+ obj.GetBlock()
+ obj.GetFunctionName()
+ obj.IsInlined()
+ obj.EvaluateExpression("x + y")
+ obj.EvaluateExpression("x + y", lldb.eDynamicCanRunTarget)
+ obj.GetFrameBlock()
+ obj.GetLineEntry()
+ obj.GetThread()
+ obj.Disassemble()
+ obj.GetVariables(True, True, True, True)
+ obj.GetVariables(True, True, True, False, lldb.eDynamicCanRunTarget)
+ obj.GetRegisters()
+ obj.FindVariable("my_var")
+ obj.FindVariable("my_var", lldb.eDynamicCanRunTarget)
+ obj.FindValue("your_var", lldb.eValueTypeVariableGlobal)
+ obj.FindValue("your_var", lldb.eValueTypeVariableStatic, lldb.eDynamicCanRunTarget)
+ obj.GetDescription(lldb.SBStream())
+ obj.Clear()
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_function.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_function.py
new file mode 100644
index 000000000000..fb88d37ac19c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_function.py
@@ -0,0 +1,19 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.GetName()
+ obj.GetMangledName()
+ obj.GetInstructions(lldb.SBTarget())
+ sa = obj.GetStartAddress()
+ ea = obj.GetEndAddress()
+ # Do fuzz testing on the address obj, it should not crash lldb.
+ import sb_address
+ sb_address.fuzz_obj(sa)
+ sb_address.fuzz_obj(ea)
+ obj.GetPrologueByteSize
+ obj.GetDescription(lldb.SBStream())
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_instruction.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_instruction.py
new file mode 100644
index 000000000000..b961bc389e31
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_instruction.py
@@ -0,0 +1,16 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.GetAddress()
+ obj.GetByteSize()
+ obj.DoesBranch()
+ obj.Print(None)
+ obj.GetDescription(lldb.SBStream())
+ obj.EmulateWithFrame(lldb.SBFrame(), 0)
+ obj.DumpEmulation("armv7")
+ obj.TestEmulation(lldb.SBStream(), "my-file")
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_instructionlist.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_instructionlist.py
new file mode 100644
index 000000000000..09d62f970480
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_instructionlist.py
@@ -0,0 +1,17 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.GetSize()
+ obj.GetInstructionAtIndex(0xffffffff)
+ obj.AppendInstruction(lldb.SBInstruction())
+ obj.Print(None)
+ obj.GetDescription(lldb.SBStream())
+ obj.DumpEmulationForAllInstructions("armv7")
+ obj.Clear()
+ for inst in obj:
+ s = str(inst)
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_lineentry.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_lineentry.py
new file mode 100644
index 000000000000..d97f2517f4bc
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_lineentry.py
@@ -0,0 +1,14 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.GetStartAddress()
+ obj.GetEndAddress()
+ obj.GetFileSpec()
+ obj.GetLine()
+ obj.GetColumn()
+ obj.GetDescription(lldb.SBStream())
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_listener.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_listener.py
new file mode 100644
index 000000000000..0747547b9cfd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_listener.py
@@ -0,0 +1,23 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.AddEvent(lldb.SBEvent())
+ obj.StartListeningForEvents(lldb.SBBroadcaster(), 0xffffffff)
+ obj.StopListeningForEvents(lldb.SBBroadcaster(), 0xffffffff)
+ event = lldb.SBEvent()
+ broadcaster = lldb.SBBroadcaster()
+ obj.WaitForEvent(5, event)
+ obj.WaitForEventForBroadcaster(5, broadcaster, event)
+ obj.WaitForEventForBroadcasterWithType(5, broadcaster, 0xffffffff, event)
+ obj.PeekAtNextEvent(event)
+ obj.PeekAtNextEventForBroadcaster(broadcaster, event)
+ obj.PeekAtNextEventForBroadcasterWithType(broadcaster, 0xffffffff, event)
+ obj.GetNextEvent(event)
+ obj.GetNextEventForBroadcaster(broadcaster, event)
+ obj.GetNextEventForBroadcasterWithType(broadcaster, 0xffffffff, event)
+ obj.HandleBroadcastEvent(event)
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_module.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_module.py
new file mode 100644
index 000000000000..0b9aa99167af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_module.py
@@ -0,0 +1,29 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.GetFileSpec()
+ obj.GetPlatformFileSpec()
+ obj.SetPlatformFileSpec(lldb.SBFileSpec())
+ obj.GetUUIDString()
+ obj.ResolveFileAddress(sys.maxsize)
+ obj.ResolveSymbolContextForAddress(lldb.SBAddress(), 0)
+ obj.GetDescription(lldb.SBStream())
+ obj.GetNumSymbols()
+ obj.GetSymbolAtIndex(sys.maxsize)
+ sc_list = obj.FindFunctions("my_func")
+ sc_list = obj.FindFunctions("my_func", lldb.eFunctionNameTypeAny)
+ obj.FindGlobalVariables(lldb.SBTarget(), "my_global_var", 1)
+ for section in obj.section_iter():
+ s = str(section)
+ for symbol in obj.symbol_in_section_iter(lldb.SBSection()):
+ s = str(symbol)
+ for symbol in obj:
+ s = str(symbol)
+ obj.GetAddressByteSize()
+ obj.GetByteOrder()
+ obj.GetTriple()
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_process.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_process.py
new file mode 100644
index 000000000000..40132b199580
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_process.py
@@ -0,0 +1,49 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.GetTarget()
+ obj.GetByteOrder()
+ obj.PutSTDIN("my data")
+ obj.GetSTDOUT(6)
+ obj.GetSTDERR(6)
+ event = lldb.SBEvent()
+ obj.ReportEventState(event, None)
+ obj.AppendEventStateReport(event, lldb.SBCommandReturnObject())
+ error = lldb.SBError()
+ obj.RemoteAttachToProcessWithID(123, error)
+ obj.RemoteLaunch(None, None, None, None, None, None, 0, False, error)
+ obj.GetNumThreads()
+ obj.GetThreadAtIndex(0)
+ obj.GetThreadByID(0)
+ obj.GetSelectedThread()
+ obj.SetSelectedThread(lldb.SBThread())
+ obj.SetSelectedThreadByID(0)
+ obj.GetState()
+ obj.GetExitStatus()
+ obj.GetExitDescription()
+ obj.GetProcessID()
+ obj.GetAddressByteSize()
+ obj.Destroy()
+ obj.Continue()
+ obj.Stop()
+ obj.Kill()
+ obj.Detach()
+ obj.Signal(7)
+ obj.ReadMemory(0x0000ffff, 10, error)
+ obj.WriteMemory(0x0000ffff, "hi data", error)
+ obj.ReadCStringFromMemory(0x0, 128, error)
+ obj.ReadUnsignedFromMemory(0xff, 4, error)
+ obj.ReadPointerFromMemory(0xff, error)
+ obj.GetBroadcaster()
+ obj.GetDescription(lldb.SBStream())
+ obj.LoadImage(lldb.SBFileSpec(), error)
+ obj.UnloadImage(0)
+ obj.Clear()
+ obj.GetNumSupportedHardwareWatchpoints(error)
+ for thread in obj:
+ s = str(thread)
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_section.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_section.py
new file mode 100644
index 000000000000..899130abe27d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_section.py
@@ -0,0 +1,22 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.IsValid()
+ obj.GetName()
+ obj.FindSubSection("hello_section_name")
+ obj.GetNumSubSections()
+ obj.GetSubSectionAtIndex(600)
+ obj.GetFileAddress()
+ obj.GetByteSize()
+ obj.GetFileOffset()
+ obj.GetFileByteSize()
+ obj.GetSectionData(1000, 100)
+ obj.GetSectionType()
+ obj.GetDescription(lldb.SBStream())
+ for subsec in obj:
+ s = str(subsec)
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_stringlist.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_stringlist.py
new file mode 100644
index 000000000000..9d8242c9b27d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_stringlist.py
@@ -0,0 +1,17 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.AppendString("another string")
+ obj.AppendString(None)
+ obj.AppendList(None, 0)
+ obj.AppendList(lldb.SBStringList())
+ obj.GetSize()
+ obj.GetStringAtIndex(0xffffffff)
+ obj.Clear()
+ for n in obj:
+ s = str(n)
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbol.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbol.py
new file mode 100644
index 000000000000..4a4c67a08804
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbol.py
@@ -0,0 +1,16 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.GetName()
+ obj.GetMangledName()
+ obj.GetInstructions(lldb.SBTarget())
+ obj.GetStartAddress()
+ obj.GetEndAddress()
+ obj.GetPrologueByteSize()
+ obj.GetType()
+ obj.GetDescription(lldb.SBStream())
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbolcontext.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbolcontext.py
new file mode 100644
index 000000000000..01b5b7b793ea
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_symbolcontext.py
@@ -0,0 +1,15 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.GetModule()
+ obj.GetCompileUnit()
+ obj.GetFunction()
+ obj.GetBlock()
+ obj.GetLineEntry()
+ obj.GetSymbol()
+ obj.GetDescription(lldb.SBStream())
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_target.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_target.py
new file mode 100644
index 000000000000..3b01be3e3440
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_target.py
@@ -0,0 +1,65 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.GetProcess()
+ listener = lldb.SBListener()
+ error = lldb.SBError()
+ obj.Launch(listener, None, None, None, None, None, None, 0, True, error)
+ obj.LaunchSimple(None, None, None)
+ obj.AttachToProcessWithID(listener, 123, error)
+ obj.AttachToProcessWithName(listener, 'lldb', False, error)
+ obj.ConnectRemote(listener, "connect://to/here", None, error)
+ obj.GetExecutable()
+ obj.GetNumModules()
+ obj.GetModuleAtIndex(0xffffffff)
+ obj.GetDebugger()
+ filespec = lldb.SBFileSpec()
+ obj.FindModule(filespec)
+ sc_list = obj.FindFunctions("the_func")
+ sc_list = obj.FindFunctions("the_func", lldb.eFunctionNameTypeAny)
+ obj.FindFirstType("dont_care")
+ obj.FindTypes("dont_care")
+ obj.FindFirstType(None)
+ obj.GetInstructions(lldb.SBAddress(), bytearray())
+ obj.GetSourceManager()
+ obj.FindGlobalVariables("my_global_var", 1)
+ address = obj.ResolveLoadAddress(0xffff)
+ obj.ResolveSymbolContextForAddress(address, 0)
+ obj.BreakpointCreateByLocation("filename", 20)
+ obj.BreakpointCreateByLocation(filespec, 20)
+ obj.BreakpointCreateByName("func", None)
+ obj.BreakpointCreateByRegex("func.", None)
+ obj.BreakpointCreateByAddress(0xf0f0)
+ obj.GetNumBreakpoints()
+ obj.GetBreakpointAtIndex(0)
+ obj.BreakpointDelete(0)
+ obj.FindBreakpointByID(0)
+ obj.EnableAllBreakpoints()
+ obj.DisableAllBreakpoints()
+ obj.DeleteAllBreakpoints()
+ obj.GetNumWatchpoints()
+ obj.GetWatchpointAtIndex(0)
+ obj.DeleteWatchpoint(0)
+ obj.FindWatchpointByID(0)
+ obj.EnableAllWatchpoints()
+ obj.DisableAllWatchpoints()
+ obj.DeleteAllWatchpoints()
+ obj.GetAddressByteSize()
+ obj.GetByteOrder()
+ obj.GetTriple()
+ error = lldb.SBError()
+ obj.WatchAddress(123, 8, True, True, error)
+ obj.GetBroadcaster()
+ obj.GetDescription(lldb.SBStream(), lldb.eDescriptionLevelBrief)
+ obj.Clear()
+ for module in obj.module_iter():
+ s = str(module)
+ for bp in obj.breakpoint_iter():
+ s = str(bp)
+ for wp in obj.watchpoint_iter():
+ s = str(wp)
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_thread.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_thread.py
new file mode 100644
index 000000000000..b69b22ea6a9f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_thread.py
@@ -0,0 +1,37 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.GetStopReason()
+ obj.GetStopReasonDataCount()
+ obj.GetStopReasonDataAtIndex(100)
+ obj.GetStopDescription(256)
+ obj.GetThreadID()
+ obj.GetIndexID()
+ obj.GetName()
+ obj.GetQueueName()
+ obj.StepOver(lldb.eOnlyDuringStepping)
+ obj.StepInto(lldb.eOnlyDuringStepping)
+ obj.StepOut()
+ frame = lldb.SBFrame()
+ obj.StepOutOfFrame(frame)
+ obj.StepInstruction(True)
+ filespec = lldb.SBFileSpec()
+ obj.StepOverUntil(frame, filespec, 1234)
+ obj.RunToAddress(0xabcd)
+ obj.Suspend()
+ obj.Resume()
+ obj.IsSuspended()
+ obj.GetNumFrames()
+ obj.GetFrameAtIndex(200)
+ obj.GetSelectedFrame()
+ obj.SetSelectedFrame(999)
+ obj.GetProcess()
+ obj.GetDescription(lldb.SBStream())
+ obj.Clear()
+ for frame in obj:
+ s = str(frame)
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_type.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_type.py
new file mode 100644
index 000000000000..5c801c1fbf2e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_type.py
@@ -0,0 +1,22 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.GetName()
+ obj.GetByteSize()
+ #obj.GetEncoding(5)
+ obj.GetNumberChildren(True)
+ member = lldb.SBTypeMember()
+ obj.GetChildAtIndex(True, 0, member)
+ obj.GetChildIndexForName(True, "_member_field")
+ obj.IsAPointerType()
+ obj.GetPointeeType()
+ obj.GetDescription(lldb.SBStream())
+ obj.IsPointerType(None)
+ lldb.SBType.IsPointerType(None)
+ for child_type in obj:
+ s = str(child_type)
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_value.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_value.py
new file mode 100644
index 000000000000..2bb8c58e2546
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_value.py
@@ -0,0 +1,67 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.GetError()
+ obj.GetID()
+ obj.GetName()
+ obj.GetTypeName()
+ obj.GetByteSize()
+ obj.IsInScope()
+ obj.GetFormat()
+ obj.SetFormat(lldb.eFormatBoolean)
+ obj.GetValue()
+ obj.GetValueType()
+ obj.GetValueDidChange()
+ obj.GetSummary()
+ obj.GetObjectDescription()
+ obj.GetLocation()
+ obj.SetValueFromCString("my_new_value")
+ obj.GetChildAtIndex(1)
+ obj.GetChildAtIndex(2, lldb.eNoDynamicValues, False)
+ obj.GetIndexOfChildWithName("my_first_child")
+ obj.GetChildMemberWithName("my_first_child")
+ obj.GetChildMemberWithName("my_first_child", lldb.eNoDynamicValues)
+ obj.GetNumChildren()
+ obj.GetOpaqueType()
+ obj.Dereference()
+ obj.TypeIsPointerType()
+ stream = lldb.SBStream()
+ obj.GetDescription(stream)
+ obj.GetExpressionPath(stream)
+ obj.GetExpressionPath(stream, True)
+ error = lldb.SBError()
+ obj.Watch(True, True, False, error)
+ obj.WatchPointee(True, False, True, error)
+ for child_val in obj:
+ s = str(child_val)
+ error = lldb.SBError()
+ obj.GetValueAsSigned (error, 0)
+ obj.GetValueAsUnsigned (error, 0)
+ obj.GetValueAsSigned(0)
+ obj.GetValueAsUnsigned(0)
+ obj.GetDynamicValue (lldb.eNoDynamicValues)
+ obj.GetStaticValue ()
+ obj.IsDynamic()
+ invalid_type = lldb.SBType()
+ obj.CreateChildAtOffset ("a", 12, invalid_type)
+ obj.Cast (invalid_type)
+ obj.CreateValueFromExpression ("pt->x", "pt->x")
+ obj.CreateValueFromAddress ("x", 0x123, invalid_type)
+ invalid_data = lldb.SBData()
+ obj.CreateValueFromData ("x", invalid_data, invalid_type)
+ obj.GetValueForExpressionPath("[0]")
+ obj.AddressOf()
+ obj.GetLoadAddress()
+ obj.GetAddress()
+ obj.GetPointeeData (0, 1)
+ obj.GetData ()
+ obj.GetTarget()
+ obj.GetProcess()
+ obj.GetThread()
+ obj.GetFrame()
+ obj.GetType()
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_valuelist.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_valuelist.py
new file mode 100644
index 000000000000..32f12f93dd81
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_valuelist.py
@@ -0,0 +1,14 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.Append(lldb.SBValue())
+ obj.GetSize()
+ obj.GetValueAtIndex(100)
+ obj.FindValueObjectByUID(200)
+ for val in obj:
+ s = str(val)
diff --git a/packages/Python/lldbsuite/test/python_api/default-constructor/sb_watchpoint.py b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_watchpoint.py
new file mode 100644
index 000000000000..f462e62ff164
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/default-constructor/sb_watchpoint.py
@@ -0,0 +1,21 @@
+"""
+Fuzz tests an object after the default construction to make sure it does not crash lldb.
+"""
+
+import sys
+import lldb
+
+def fuzz_obj(obj):
+ obj.GetID()
+ obj.IsValid()
+ obj.GetHardwareIndex()
+ obj.GetWatchAddress()
+ obj.GetWatchSize()
+ obj.SetEnabled(True)
+ obj.IsEnabled()
+ obj.GetHitCount()
+ obj.GetIgnoreCount()
+ obj.SetIgnoreCount(5)
+ obj.GetDescription(lldb.SBStream(), lldb.eDescriptionLevelVerbose)
+ obj.SetCondition("shouldWeStop()")
+ obj.GetCondition()
diff --git a/packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassembleRawData.py b/packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassembleRawData.py
new file mode 100644
index 000000000000..20333abc57af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassembleRawData.py
@@ -0,0 +1,39 @@
+"""
+Use lldb Python API to disassemble raw machine code bytes
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class DisassembleRawDataTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_disassemble_raw_data(self):
+ """Test disassembling raw bytes with the API."""
+ # Create a target from the debugger.
+ target = self.dbg.CreateTargetWithFileAndTargetTriple ("", "x86_64")
+ self.assertTrue(target, VALID_TARGET)
+
+ raw_bytes = bytearray([0x48, 0x89, 0xe5])
+
+ insts = target.GetInstructions(lldb.SBAddress(0, target), raw_bytes)
+
+ inst = insts.GetInstructionAtIndex(0)
+
+ if self.TraceOn():
+ print()
+ print("Raw bytes: ", [hex(x) for x in raw_bytes])
+ print("Disassembled%s" % str(inst))
+
+ self.assertTrue (inst.GetMnemonic(target) == "movq")
+ self.assertTrue (inst.GetOperands(target) == '%' + "rsp, " + '%' + "rbp")
diff --git a/packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassemble_VST1_64.py b/packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassemble_VST1_64.py
new file mode 100644
index 000000000000..e24b2ee5613a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/disassemble-raw-data/TestDisassemble_VST1_64.py
@@ -0,0 +1,58 @@
+"""
+Use lldb Python API to disassemble raw machine code bytes
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class Disassemble_VST1_64(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIf(True) # llvm.org/pr24575: all tests get ERRORs in dotest.py after this
+ @add_test_categories(['pyapi'])
+ @no_debug_info_test
+ def test_disassemble_invalid_vst_1_64_raw_data(self):
+ """Test disassembling invalid vst1.64 raw bytes with the API."""
+ # Create a target from the debugger.
+ target = self.dbg.CreateTargetWithFileAndTargetTriple ("", "thumbv7")
+ self.assertTrue(target, VALID_TARGET)
+
+ raw_bytes = bytearray([0xf0, 0xb5, 0x03, 0xaf,
+ 0x2d, 0xe9, 0x00, 0x0d,
+ 0xad, 0xf1, 0x40, 0x04,
+ 0x24, 0xf0, 0x0f, 0x04,
+ 0xa5, 0x46])
+
+ insts = target.GetInstructions(lldb.SBAddress(), raw_bytes)
+
+ if self.TraceOn():
+ print()
+ for i in insts:
+ print("Disassembled%s" % str(i))
+
+ # Remove the following return statement when the radar is fixed.
+ return
+
+ # rdar://problem/11034702
+ # VST1 (multiple single elements) encoding?
+ # The disassembler should not crash!
+ raw_bytes = bytearray([0x04, 0xf9, 0xed, 0x82])
+
+ insts = target.GetInstructions(lldb.SBAddress(), raw_bytes)
+
+ inst = insts.GetInstructionAtIndex(0)
+
+ if self.TraceOn():
+ print()
+ print("Raw bytes: ", [hex(x) for x in raw_bytes])
+ print("Disassembled%s" % str(inst))
+
+ self.assertTrue (inst.GetMnemonic(target) == "vst1.64")
diff --git a/packages/Python/lldbsuite/test/python_api/event/Makefile b/packages/Python/lldbsuite/test/python_api/event/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/event/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/event/TestEvents.py b/packages/Python/lldbsuite/test/python_api/event/TestEvents.py
new file mode 100644
index 000000000000..0a1a0dfda7d2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/event/TestEvents.py
@@ -0,0 +1,288 @@
+"""
+Test lldb Python event APIs.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+@skipIfDarwin # llvm.org/pr25924, sometimes generating SIGSEGV
+class EventAPITestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to of function 'c'.
+ self.line = line_number('main.c', '// Find the line number of function "c" here.')
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureLinux("llvm.org/pr23730") # Flaky, fails ~1/10 cases
+ @skipIfLinux # skip to avoid crashes
+ def test_listen_for_and_print_event(self):
+ """Exercise SBEvent API."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ self.dbg.SetAsync(True)
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create a breakpoint on main.c by name 'c'.
+ breakpoint = target.BreakpointCreateByName('c', 'a.out')
+
+ listener = lldb.SBListener("my listener")
+
+ # Now launch the process, and do not stop at the entry point.
+ error = lldb.SBError()
+ process = target.Launch (listener,
+ None, # argv
+ None, # envp
+ None, # stdin_path
+ None, # stdout_path
+ None, # stderr_path
+ None, # working directory
+ 0, # launch flags
+ False, # Stop at entry
+ error) # error
+
+ self.assertTrue(process.GetState() == lldb.eStateStopped, PROCESS_STOPPED)
+
+ # Create an empty event object.
+ event = lldb.SBEvent()
+
+ traceOn = self.TraceOn()
+ if traceOn:
+ lldbutil.print_stacktraces(process)
+
+ # Create MyListeningThread class to wait for any kind of event.
+ import threading
+ class MyListeningThread(threading.Thread):
+ def run(self):
+ count = 0
+ # Let's only try at most 4 times to retrieve any kind of event.
+ # After that, the thread exits.
+ while not count > 3:
+ if traceOn:
+ print("Try wait for event...")
+ if listener.WaitForEvent(5, event):
+ if traceOn:
+ desc = lldbutil.get_description(event)
+ print("Event description:", desc)
+ print("Event data flavor:", event.GetDataFlavor())
+ print("Process state:", lldbutil.state_type_to_str(process.GetState()))
+ print()
+ else:
+ if traceOn:
+ print("timeout occurred waiting for event...")
+ count = count + 1
+ return
+
+ # Let's start the listening thread to retrieve the events.
+ my_thread = MyListeningThread()
+ my_thread.start()
+
+ # Use Python API to continue the process. The listening thread should be
+ # able to receive the state changed events.
+ process.Continue()
+
+ # Use Python API to kill the process. The listening thread should be
+ # able to receive the state changed event, too.
+ process.Kill()
+
+ # Wait until the 'MyListeningThread' terminates.
+ my_thread.join()
+
+ @add_test_categories(['pyapi'])
+ @expectedFlakeyLinux("llvm.org/pr23730") # Flaky, fails ~1/100 cases
+ def test_wait_for_event(self):
+ """Exercise SBListener.WaitForEvent() API."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ self.dbg.SetAsync(True)
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create a breakpoint on main.c by name 'c'.
+ breakpoint = target.BreakpointCreateByName('c', 'a.out')
+ #print("breakpoint:", breakpoint)
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Get the debugger listener.
+ listener = self.dbg.GetListener()
+
+ # Now launch the process, and do not stop at entry point.
+ error = lldb.SBError()
+ process = target.Launch (listener,
+ None, # argv
+ None, # envp
+ None, # stdin_path
+ None, # stdout_path
+ None, # stderr_path
+ None, # working directory
+ 0, # launch flags
+ False, # Stop at entry
+ error) # error
+ self.assertTrue(error.Success() and process, PROCESS_IS_VALID)
+
+ # Create an empty event object.
+ event = lldb.SBEvent()
+ self.assertFalse(event, "Event should not be valid initially")
+
+ # Create MyListeningThread to wait for any kind of event.
+ import threading
+ class MyListeningThread(threading.Thread):
+ def run(self):
+ count = 0
+ # Let's only try at most 3 times to retrieve any kind of event.
+ while not count > 3:
+ if listener.WaitForEvent(5, event):
+ #print("Got a valid event:", event)
+ #print("Event data flavor:", event.GetDataFlavor())
+ #print("Event type:", lldbutil.state_type_to_str(event.GetType()))
+ return
+ count = count + 1
+ print("Timeout: listener.WaitForEvent")
+
+ return
+
+ # Use Python API to kill the process. The listening thread should be
+ # able to receive a state changed event.
+ process.Kill()
+
+ # Let's start the listening thread to retrieve the event.
+ my_thread = MyListeningThread()
+ my_thread.start()
+
+ # Wait until the 'MyListeningThread' terminates.
+ my_thread.join()
+
+ self.assertTrue(event,
+ "My listening thread successfully received an event")
+
+ @skipIfFreeBSD # llvm.org/pr21325
+ @add_test_categories(['pyapi'])
+ @expectedFlakeyLinux("llvm.org/pr23617") # Flaky, fails ~1/10 cases
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test_add_listener_to_broadcaster(self):
+ """Exercise some SBBroadcaster APIs."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ self.dbg.SetAsync(True)
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create a breakpoint on main.c by name 'c'.
+ breakpoint = target.BreakpointCreateByName('c', 'a.out')
+ #print("breakpoint:", breakpoint)
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ listener = lldb.SBListener("my listener")
+
+ # Now launch the process, and do not stop at the entry point.
+ error = lldb.SBError()
+ process = target.Launch (listener,
+ None, # argv
+ None, # envp
+ None, # stdin_path
+ None, # stdout_path
+ None, # stderr_path
+ None, # working directory
+ 0, # launch flags
+ False, # Stop at entry
+ error) # error
+
+ # Create an empty event object.
+ event = lldb.SBEvent()
+ self.assertFalse(event, "Event should not be valid initially")
+
+
+ # The finite state machine for our custom listening thread, with an
+ # initial state of None, which means no event has been received.
+ # It changes to 'connected' after 'connected' event is received (for remote platforms)
+ # It changes to 'running' after 'running' event is received (should happen only if the
+ # currentstate is either 'None' or 'connected')
+ # It changes to 'stopped' if a 'stopped' event is received (should happen only if the
+ # current state is 'running'.)
+ self.state = None
+
+ # Create MyListeningThread to wait for state changed events.
+ # By design, a "running" event is expected following by a "stopped" event.
+ import threading
+ class MyListeningThread(threading.Thread):
+ def run(self):
+ #print("Running MyListeningThread:", self)
+
+ # Regular expression pattern for the event description.
+ pattern = re.compile("data = {.*, state = (.*)}$")
+
+ # Let's only try at most 6 times to retrieve our events.
+ count = 0
+ while True:
+ if listener.WaitForEvent(5, event):
+ desc = lldbutil.get_description(event)
+ #print("Event description:", desc)
+ match = pattern.search(desc)
+ if not match:
+ break;
+ if match.group(1) == 'connected':
+ # When debugging remote targets with lldb-server, we
+ # first get the 'connected' event.
+ self.context.assertTrue(self.context.state == None)
+ self.context.state = 'connected'
+ continue
+ elif match.group(1) == 'running':
+ self.context.assertTrue(self.context.state == None or self.context.state == 'connected')
+ self.context.state = 'running'
+ continue
+ elif match.group(1) == 'stopped':
+ self.context.assertTrue(self.context.state == 'running')
+ # Whoopee, both events have been received!
+ self.context.state = 'stopped'
+ break
+ else:
+ break
+ print("Timeout: listener.WaitForEvent")
+ count = count + 1
+ if count > 6:
+ break
+
+ return
+
+ # Use Python API to continue the process. The listening thread should be
+ # able to receive the state changed events.
+ process.Continue()
+
+ # Start the listening thread to receive the "running" followed by the
+ # "stopped" events.
+ my_thread = MyListeningThread()
+ # Supply the enclosing context so that our listening thread can access
+ # the 'state' variable.
+ my_thread.context = self
+ my_thread.start()
+
+ # Wait until the 'MyListeningThread' terminates.
+ my_thread.join()
+
+ # The final judgement. :-)
+ self.assertTrue(self.state == 'stopped',
+ "Both expected state changed events received")
diff --git a/packages/Python/lldbsuite/test/python_api/event/main.c b/packages/Python/lldbsuite/test/python_api/event/main.c
new file mode 100644
index 000000000000..343526542d7e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/event/main.c
@@ -0,0 +1,49 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+// This simple program is to test the lldb Python API related to events.
+
+int a(int);
+int b(int);
+int c(int);
+
+int a(int val)
+{
+ if (val <= 1)
+ return b(val);
+ else if (val >= 3)
+ return c(val);
+
+ return val;
+}
+
+int b(int val)
+{
+ return c(val);
+}
+
+int c(int val)
+{
+ return val + 3; // Find the line number of function "c" here.
+}
+
+int main (int argc, char const *argv[])
+{
+ int A1 = a(1); // a(1) -> b(1) -> c(1)
+ printf("a(1) returns %d\n", A1);
+
+ int B2 = b(2); // b(2) -> c(2)
+ printf("b(2) returns %d\n", B2);
+
+ int A3 = a(3); // a(3) -> c(3)
+ printf("a(3) returns %d\n", A3);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/python_api/exprpath_synthetic/TestExprPathSynthetic.py b/packages/Python/lldbsuite/test/python_api/exprpath_synthetic/TestExprPathSynthetic.py
new file mode 100644
index 000000000000..80305e303d03
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/exprpath_synthetic/TestExprPathSynthetic.py
@@ -0,0 +1,4 @@
+import lldbsuite.test.lldbinline as lldbinline
+import lldbsuite.test.lldbtest as lldbtest
+
+lldbinline.MakeInlineTest(__file__, globals(), [lldbtest.skipIfFreeBSD,lldbtest.skipIfLinux,lldbtest.skipIfWindows])
diff --git a/packages/Python/lldbsuite/test/python_api/exprpath_synthetic/main.mm b/packages/Python/lldbsuite/test/python_api/exprpath_synthetic/main.mm
new file mode 100644
index 000000000000..f7383a5a14de
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/exprpath_synthetic/main.mm
@@ -0,0 +1,20 @@
+//===-- main.mm --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#import <Cocoa/Cocoa.h>
+#include <vector>
+
+int main (int argc, char const *argv[])
+{
+ std::vector<int> v{1,2,3,4,5};
+ NSArray *a = @[@"Hello",@"World",@"From Me"];
+ return 0; //% v = self.frame().FindVariable("v"); v0 = v.GetChildAtIndex(0); s = lldb.SBStream(); v0.GetExpressionPath(s);
+ //% self.runCmd("expr %s = 12" % s.GetData()); self.assertTrue(v0.GetValueAsUnsigned() == 12, "value change via expr failed")
+ //% a = self.frame().FindVariable("a"); a1 = a.GetChildAtIndex(1); s = lldb.SBStream(); a1.GetExpressionPath(s);
+ //% self.expect("po %s" % s.GetData(), substrs = ["World"])
+}
diff --git a/packages/Python/lldbsuite/test/python_api/findvalue_duplist/Makefile b/packages/Python/lldbsuite/test/python_api/findvalue_duplist/Makefile
new file mode 100644
index 000000000000..ddffdcfb62d6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/findvalue_duplist/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+# Clean renamed executable on 'make clean'
+clean: OBJECTS+=no_synth
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/findvalue_duplist/TestSBFrameFindValue.py b/packages/Python/lldbsuite/test/python_api/findvalue_duplist/TestSBFrameFindValue.py
new file mode 100644
index 000000000000..96d4f51fd097
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/findvalue_duplist/TestSBFrameFindValue.py
@@ -0,0 +1,50 @@
+"""Test that SBFrame::FindValue finds things but does not duplicate the entire variables list"""
+
+from __future__ import print_function
+
+
+
+import os, sys, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class SBFrameFindValueTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @add_test_categories(['pyapi'])
+ def test_formatters_api(self):
+ """Test that SBFrame::FindValue finds things but does not duplicate the entire variables list"""
+ self.build()
+ self.setTearDownCleanup()
+
+ exe_name = "a.out"
+ exe = os.path.join(os.getcwd(), exe_name)
+
+ # Create the target
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Set the breakpoints
+ breakpoint = target.BreakpointCreateBySourceRegex('Set breakpoint here', lldb.SBFileSpec("main.cpp"))
+ self.assertTrue(breakpoint.GetNumLocations() > 0, VALID_BREAKPOINT)
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple(None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Frame #0 should be at our breakpoint.
+ threads = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint)
+
+ self.assertTrue(len(threads) == 1)
+ self.thread = threads[0]
+ self.frame = self.thread.frames[0]
+ self.assertTrue(self.frame, "Frame 0 is valid.")
+
+ self.assertTrue(self.frame.GetVariables(True,True,False,True).GetSize() == 2, "variable count is off")
+ self.assertFalse(self.frame.FindValue("NoSuchThing",lldb.eValueTypeVariableArgument,lldb.eDynamicCanRunTarget).IsValid(), "found something that should not be here")
+ self.assertTrue(self.frame.GetVariables(True,True,False,True).GetSize() == 2, "variable count is off after failed FindValue()")
+ self.assertTrue(self.frame.FindValue("a",lldb.eValueTypeVariableArgument,lldb.eDynamicCanRunTarget).IsValid(), "FindValue() didn't find an argument")
+ self.assertTrue(self.frame.GetVariables(True,True,False,True).GetSize() == 2, "variable count is off after successful FindValue()")
diff --git a/packages/Python/lldbsuite/test/python_api/findvalue_duplist/main.cpp b/packages/Python/lldbsuite/test/python_api/findvalue_duplist/main.cpp
new file mode 100644
index 000000000000..7058d46b04a5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/findvalue_duplist/main.cpp
@@ -0,0 +1,7 @@
+int foo(int a, int b) {
+ return a + b; // Set breakpoint here
+}
+
+int main() {
+ return foo(1,3);
+}
diff --git a/packages/Python/lldbsuite/test/python_api/formatters/Makefile b/packages/Python/lldbsuite/test/python_api/formatters/Makefile
new file mode 100644
index 000000000000..ddffdcfb62d6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/formatters/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+# Clean renamed executable on 'make clean'
+clean: OBJECTS+=no_synth
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/formatters/TestFormattersSBAPI.py b/packages/Python/lldbsuite/test/python_api/formatters/TestFormattersSBAPI.py
new file mode 100644
index 000000000000..de7f15f76faf
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/formatters/TestFormattersSBAPI.py
@@ -0,0 +1,346 @@
+"""Test Python APIs for working with formatters"""
+
+from __future__ import print_function
+
+
+
+import os, sys, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class SBFormattersAPITestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ @add_test_categories(['pyapi'])
+ def test_formatters_api(self):
+ """Test Python APIs for working with formatters"""
+ self.build()
+ self.setTearDownCleanup()
+
+ """Test Python APIs for working with formatters"""
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synthetic clear', check=False)
+ self.runCmd('type category delete foobar', check=False)
+ self.runCmd('type category delete JASSynth', check=False)
+ self.runCmd('type category delete newbar', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+
+ format = lldb.SBTypeFormat(lldb.eFormatHex)
+ category = self.dbg.GetDefaultCategory()
+ category.AddTypeFormat(lldb.SBTypeNameSpecifier("int"),format)
+
+ self.expect("frame variable foo.A",
+ substrs = ['0x00000001'])
+ self.expect("frame variable foo.E", matching=False,
+ substrs = ['b8cca70a'])
+
+ category.AddTypeFormat(lldb.SBTypeNameSpecifier("long"),format)
+ self.expect("frame variable foo.A",
+ substrs = ['0x00000001'])
+ self.expect("frame variable foo.E",
+ substrs = ['b8cca70a'])
+
+ format.format = lldb.eFormatOctal
+ category.AddTypeFormat(lldb.SBTypeNameSpecifier("int"),format)
+ self.expect("frame variable foo.A",
+ substrs = ['01'])
+ self.expect("frame variable foo.E",
+ substrs = ['b8cca70a'])
+
+ category.DeleteTypeFormat(lldb.SBTypeNameSpecifier("int"))
+ category.DeleteTypeFormat(lldb.SBTypeNameSpecifier("long"))
+ self.expect("frame variable foo.A", matching=False,
+ substrs = ['01'])
+ self.expect("frame variable foo.E", matching=False,
+ substrs = ['b8cca70a'])
+
+ summary = lldb.SBTypeSummary.CreateWithSummaryString("the hello world you'll never see")
+ summary.SetSummaryString('hello world')
+ new_category = self.dbg.GetCategory("foobar")
+ self.assertFalse(new_category.IsValid(), "getting a non-existing category worked")
+ new_category = self.dbg.CreateCategory("foobar")
+ new_category.enabled = True
+ new_category.AddTypeSummary(lldb.SBTypeNameSpecifier("^.*t$",True),summary)
+ self.expect("frame variable foo.A",
+ substrs = ['hello world'])
+ self.expect("frame variable foo.E", matching=False,
+ substrs = ['hello world'])
+ self.expect("frame variable foo.B",
+ substrs = ['hello world'])
+ self.expect("frame variable foo.F",
+ substrs = ['hello world'])
+ new_category.enabled = False
+ self.expect("frame variable foo.A", matching=False,
+ substrs = ['hello world'])
+ self.expect("frame variable foo.E", matching=False,
+ substrs = ['hello world'])
+ self.expect("frame variable foo.B", matching=False,
+ substrs = ['hello world'])
+ self.expect("frame variable foo.F", matching=False,
+ substrs = ['hello world'])
+ self.dbg.DeleteCategory(new_category.GetName())
+ self.expect("frame variable foo.A", matching=False,
+ substrs = ['hello world'])
+ self.expect("frame variable foo.E", matching=False,
+ substrs = ['hello world'])
+ self.expect("frame variable foo.B", matching=False,
+ substrs = ['hello world'])
+ self.expect("frame variable foo.F", matching=False,
+ substrs = ['hello world'])
+
+ filter = lldb.SBTypeFilter(0)
+ filter.AppendExpressionPath("A")
+ filter.AppendExpressionPath("D")
+ self.assertTrue(filter.GetNumberOfExpressionPaths() == 2, "filter with two items does not have two items")
+
+ category.AddTypeFilter(lldb.SBTypeNameSpecifier("JustAStruct"),filter)
+ self.expect("frame variable foo",
+ substrs = ['A = 1', 'D = 6.28'])
+ self.expect("frame variable foo", matching=False,
+ substrs = ['B = ', 'C = ', 'E = ', 'F = '])
+
+ category.DeleteTypeFilter(lldb.SBTypeNameSpecifier("JustAStruct",True))
+ self.expect("frame variable foo",
+ substrs = ['A = 1', 'D = 6.28'])
+ self.expect("frame variable foo", matching=False,
+ substrs = ['B = ', 'C = ', 'E = ', 'F = '])
+
+ category.DeleteTypeFilter(lldb.SBTypeNameSpecifier("JustAStruct",False))
+ self.expect("frame variable foo",
+ substrs = ['A = 1', 'D = 6.28'])
+ self.expect("frame variable foo", matching=True,
+ substrs = ['B = ', 'C = ', 'E = ', 'F = '])
+
+ self.runCmd("command script import --allow-reload ./synth.py")
+
+ self.expect("frame variable foo", matching=False,
+ substrs = ['X = 1'])
+
+ self.dbg.GetCategory("JASSynth").SetEnabled(True)
+ self.expect("frame variable foo", matching=True,
+ substrs = ['X = 1'])
+
+ self.dbg.GetCategory("CCCSynth").SetEnabled(True)
+ self.expect("frame variable ccc", matching=True,
+ substrs = ['CCC object with leading value (int) a = 111', 'a = 111', 'b = 222', 'c = 333'])
+
+ foo_var = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('foo')
+ self.assertTrue(foo_var.IsValid(), 'could not find foo')
+ self.assertTrue(foo_var.GetDeclaration().IsValid(), 'foo declaration is invalid')
+
+ self.assertTrue(foo_var.GetNumChildren() == 2, 'synthetic value has wrong number of child items (synth)')
+ self.assertTrue(foo_var.GetChildMemberWithName('X').GetValueAsUnsigned() == 1, 'foo_synth.X has wrong value (synth)')
+ self.assertFalse(foo_var.GetChildMemberWithName('B').IsValid(), 'foo_synth.B is valid but should not (synth)')
+
+ self.dbg.GetCategory("JASSynth").SetEnabled(False)
+ foo_var = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('foo')
+ self.assertTrue(foo_var.IsValid(), 'could not find foo')
+
+ self.assertFalse(foo_var.GetNumChildren() == 2, 'still seeing synthetic value')
+
+ filter = lldb.SBTypeFilter(0)
+ filter.AppendExpressionPath("A")
+ filter.AppendExpressionPath("D")
+ category.AddTypeFilter(lldb.SBTypeNameSpecifier("JustAStruct"),filter)
+ self.expect("frame variable foo",
+ substrs = ['A = 1', 'D = 6.28'])
+
+ foo_var = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('foo')
+ self.assertTrue(foo_var.IsValid(), 'could not find foo')
+
+ self.assertTrue(foo_var.GetNumChildren() == 2, 'synthetic value has wrong number of child items (filter)')
+ self.assertTrue(foo_var.GetChildMemberWithName('X').GetValueAsUnsigned() == 0, 'foo_synth.X has wrong value (filter)')
+ self.assertTrue(foo_var.GetChildMemberWithName('A').GetValueAsUnsigned() == 1, 'foo_synth.A has wrong value (filter)')
+
+ self.assertTrue(filter.ReplaceExpressionPathAtIndex(0,"C"), "failed to replace an expression path in filter")
+ self.expect("frame variable foo",
+ substrs = ['A = 1', 'D = 6.28'])
+ category.AddTypeFilter(lldb.SBTypeNameSpecifier("JustAStruct"),filter)
+ self.expect("frame variable foo",
+ substrs = ["C = 'e'", 'D = 6.28'])
+ category.AddTypeFilter(lldb.SBTypeNameSpecifier("FooType"),filter)
+ filter.ReplaceExpressionPathAtIndex(1,"F")
+ self.expect("frame variable foo",
+ substrs = ["C = 'e'", 'D = 6.28'])
+ category.AddTypeFilter(lldb.SBTypeNameSpecifier("JustAStruct"),filter)
+ self.expect("frame variable foo",
+ substrs = ["C = 'e'", 'F = 0'])
+ self.expect("frame variable bar",
+ substrs = ["C = 'e'", 'D = 6.28'])
+
+ foo_var = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame().FindVariable('foo')
+ self.assertTrue(foo_var.IsValid(), 'could not find foo')
+ self.assertTrue(foo_var.GetChildMemberWithName('C').GetValueAsUnsigned() == ord('e'), 'foo_synth.C has wrong value (filter)')
+
+ chosen = self.dbg.GetFilterForType(lldb.SBTypeNameSpecifier("JustAStruct"))
+ self.assertTrue(chosen.count == 2, "wrong filter found for JustAStruct")
+ self.assertTrue(chosen.GetExpressionPathAtIndex(0) == 'C', "wrong item at index 0 for JustAStruct")
+ self.assertTrue(chosen.GetExpressionPathAtIndex(1) == 'F', "wrong item at index 1 for JustAStruct")
+
+ self.assertFalse(category.DeleteTypeFilter(lldb.SBTypeNameSpecifier("NoSuchType")),"deleting a non-existing filter worked")
+ self.assertFalse(category.DeleteTypeSummary(lldb.SBTypeNameSpecifier("NoSuchType")),"deleting a non-existing summary worked")
+ self.assertFalse(category.DeleteTypeFormat(lldb.SBTypeNameSpecifier("NoSuchType")),"deleting a non-existing format worked")
+ self.assertFalse(category.DeleteTypeSynthetic(lldb.SBTypeNameSpecifier("NoSuchType")),"deleting a non-existing synthetic worked")
+
+ self.assertFalse(category.DeleteTypeFilter(lldb.SBTypeNameSpecifier("")),"deleting a filter for '' worked")
+ self.assertFalse(category.DeleteTypeSummary(lldb.SBTypeNameSpecifier("")),"deleting a summary for '' worked")
+ self.assertFalse(category.DeleteTypeFormat(lldb.SBTypeNameSpecifier("")),"deleting a format for '' worked")
+ self.assertFalse(category.DeleteTypeSynthetic(lldb.SBTypeNameSpecifier("")),"deleting a synthetic for '' worked")
+
+ try:
+ self.assertFalse(category.AddTypeSummary(lldb.SBTypeNameSpecifier("NoneSuchType"), None), "adding a summary valued None worked")
+ except:
+ pass
+ else:
+ self.assertFalse(True, "adding a summary valued None worked")
+
+ try:
+ self.assertFalse(category.AddTypeFilter(lldb.SBTypeNameSpecifier("NoneSuchType"), None), "adding a filter valued None worked")
+ except:
+ pass
+ else:
+ self.assertFalse(True, "adding a filter valued None worked")
+
+ try:
+ self.assertFalse(category.AddTypeSynthetic(lldb.SBTypeNameSpecifier("NoneSuchType"), None), "adding a synthetic valued None worked")
+ except:
+ pass
+ else:
+ self.assertFalse(True, "adding a synthetic valued None worked")
+
+ try:
+ self.assertFalse(category.AddTypeFormat(lldb.SBTypeNameSpecifier("NoneSuchType"), None), "adding a format valued None worked")
+ except:
+ pass
+ else:
+ self.assertFalse(True, "adding a format valued None worked")
+
+
+ self.assertFalse(category.AddTypeSummary(lldb.SBTypeNameSpecifier("EmptySuchType"), lldb.SBTypeSummary()), "adding a summary without value worked")
+ self.assertFalse(category.AddTypeFilter(lldb.SBTypeNameSpecifier("EmptySuchType"), lldb.SBTypeFilter()), "adding a filter without value worked")
+ self.assertFalse(category.AddTypeSynthetic(lldb.SBTypeNameSpecifier("EmptySuchType"), lldb.SBTypeSynthetic()), "adding a synthetic without value worked")
+ self.assertFalse(category.AddTypeFormat(lldb.SBTypeNameSpecifier("EmptySuchType"), lldb.SBTypeFormat()), "adding a format without value worked")
+
+ self.assertFalse(category.AddTypeSummary(lldb.SBTypeNameSpecifier(""), lldb.SBTypeSummary.CreateWithSummaryString("")), "adding a summary for an invalid type worked")
+ self.assertFalse(category.AddTypeFilter(lldb.SBTypeNameSpecifier(""), lldb.SBTypeFilter(0)), "adding a filter for an invalid type worked")
+ self.assertFalse(category.AddTypeSynthetic(lldb.SBTypeNameSpecifier(""), lldb.SBTypeSynthetic.CreateWithClassName("")), "adding a synthetic for an invalid type worked")
+ self.assertFalse(category.AddTypeFormat(lldb.SBTypeNameSpecifier(""), lldb.SBTypeFormat(lldb.eFormatHex)), "adding a format for an invalid type worked")
+
+ new_category = self.dbg.CreateCategory("newbar")
+ new_category.AddTypeSummary(lldb.SBTypeNameSpecifier("JustAStruct"),
+ lldb.SBTypeSummary.CreateWithScriptCode("return 'hello scripted world';"))
+ self.expect("frame variable foo", matching=False,
+ substrs = ['hello scripted world'])
+ new_category.enabled = True
+ self.expect("frame variable foo", matching=True,
+ substrs = ['hello scripted world'])
+
+ self.expect("frame variable foo_ptr", matching=True,
+ substrs = ['hello scripted world'])
+ new_category.AddTypeSummary(lldb.SBTypeNameSpecifier("JustAStruct"),
+ lldb.SBTypeSummary.CreateWithScriptCode("return 'hello scripted world';",
+ lldb.eTypeOptionSkipPointers))
+ self.expect("frame variable foo", matching=True,
+ substrs = ['hello scripted world'])
+
+ frame = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame()
+ foo_ptr = frame.FindVariable("foo_ptr")
+ summary = foo_ptr.GetTypeSummary()
+
+ self.assertFalse(summary.IsValid(), "summary found for foo* when none was planned")
+
+ self.expect("frame variable foo_ptr", matching=False,
+ substrs = ['hello scripted world'])
+
+ new_category.AddTypeSummary(lldb.SBTypeNameSpecifier("JustAStruct"),
+ lldb.SBTypeSummary.CreateWithSummaryString("hello static world",
+ lldb.eTypeOptionNone))
+
+ summary = foo_ptr.GetTypeSummary()
+
+ self.assertTrue(summary.IsValid(), "no summary found for foo* when one was in place")
+ self.assertTrue(summary.GetData() == "hello static world", "wrong summary found for foo*")
+
+ self.expect("frame variable e1", substrs=["I am an empty Empty1 {}"])
+ self.expect("frame variable e2", substrs=["I am an empty Empty2"])
+ self.expect("frame variable e2", substrs=["I am an empty Empty2 {}"], matching=False)
+
+ self.assertTrue(self.dbg.GetCategory(lldb.eLanguageTypeObjC) is not None, "ObjC category is None")
+
+ @add_test_categories(['pyapi'])
+ def test_force_synth_off(self):
+ """Test that one can have the public API return non-synthetic SBValues if desired"""
+ self.build(dictionary={'EXE':'no_synth'})
+ self.setTearDownCleanup()
+
+ self.runCmd("file no_synth", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synthetic clear', check=False)
+ self.runCmd('type category delete foobar', check=False)
+ self.runCmd('type category delete JASSynth', check=False)
+ self.runCmd('type category delete newbar', check=False)
+ self.runCmd('settings set target.enable-synthetic-value true')
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ frame = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame()
+ int_vector = frame.FindVariable("int_vector")
+ if self.TraceOn():
+ print(int_vector)
+ self.assertTrue(int_vector.GetNumChildren() == 0, 'synthetic vector is empty')
+
+ self.runCmd('settings set target.enable-synthetic-value false')
+ frame = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame()
+ int_vector = frame.FindVariable("int_vector")
+ if self.TraceOn():
+ print(int_vector)
+ self.assertFalse(int_vector.GetNumChildren() == 0, '"physical" vector is not empty')
+
+ self.runCmd('settings set target.enable-synthetic-value true')
+ frame = self.dbg.GetSelectedTarget().GetProcess().GetSelectedThread().GetSelectedFrame()
+ int_vector = frame.FindVariable("int_vector")
+ if self.TraceOn():
+ print(int_vector)
+ self.assertTrue(int_vector.GetNumChildren() == 0, 'synthetic vector is still empty')
diff --git a/packages/Python/lldbsuite/test/python_api/formatters/main.cpp b/packages/Python/lldbsuite/test/python_api/formatters/main.cpp
new file mode 100644
index 000000000000..f21c956144c2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/formatters/main.cpp
@@ -0,0 +1,59 @@
+#include <stdio.h>
+#include <vector>
+
+struct JustAStruct
+{
+ int A;
+ float B;
+ char C;
+ double D;
+ long E;
+ short F;
+};
+
+struct FooType
+{
+ int A;
+ float B;
+ char C;
+ double D;
+ long E;
+ short F;
+};
+
+struct CCC
+{
+ int a, b, c;
+};
+
+struct Empty1 { void *data; };
+struct Empty2 { void *data; };
+
+
+int main(int argc, char const *argv[]) {
+ JustAStruct foo;
+ foo.A = 1;
+ foo.B = 3.14;
+ foo.C = 'e';
+ foo.D = 6.28;
+ foo.E = 3100419850;
+ foo.F = 0;
+
+ FooType bar;
+ bar.A = 1;
+ bar.B = 3.14;
+ bar.C = 'e';
+ bar.D = 6.28;
+ bar.E = 3100419850;
+ bar.F = 0;
+ JustAStruct* foo_ptr = &foo;
+
+ std::vector<int> int_vector;
+
+ CCC ccc = {111, 222, 333};
+
+ Empty1 e1;
+ Empty2 e2;
+
+ return 0; // Set break point at this line.
+}
diff --git a/packages/Python/lldbsuite/test/python_api/formatters/synth.py b/packages/Python/lldbsuite/test/python_api/formatters/synth.py
new file mode 100644
index 000000000000..5a30c9a94bb5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/formatters/synth.py
@@ -0,0 +1,105 @@
+import lldb
+
+class jasSynthProvider:
+ def __init__(self, valobj, dict):
+ self.valobj = valobj;
+ def num_children(self):
+ return 2;
+ def get_child_at_index(self, index):
+ child = None
+ if index == 0:
+ child = self.valobj.GetChildMemberWithName('A');
+ if index == 1:
+ child = self.valobj.CreateValueFromExpression('X', '(int)1')
+ return child;
+ def get_child_index(self, name):
+ if name == 'A':
+ return 0;
+ if name == 'X':
+ return 1;
+ return None;
+
+
+def ccc_summary(sbvalue, internal_dict):
+ sbvalue = sbvalue.GetNonSyntheticValue()
+ # This tests that the SBValue.GetNonSyntheticValue() actually returns a
+ # non-synthetic value. If it does not, then sbvalue.GetChildMemberWithName("a")
+ # in the following statement will call the 'get_child_index' method of the
+ # synthetic child provider CCCSynthProvider below (which raises an exception).
+ return "CCC object with leading value " + str(sbvalue.GetChildMemberWithName("a"))
+
+
+class CCCSynthProvider(object):
+ def __init__(self, sbvalue, internal_dict):
+ self._sbvalue = sbvalue
+
+ def num_children(self):
+ return 3
+
+ def get_child_index(self, name):
+ raise RuntimeError("I don't want to be called!")
+
+ def get_child_at_index(self, index):
+ if index == 0:
+ return self._sbvalue.GetChildMemberWithName("a")
+ if index == 1:
+ return self._sbvalue.GetChildMemberWithName("b")
+ if index == 2:
+ return self._sbvalue.GetChildMemberWithName("c")
+
+
+def empty1_summary(sbvalue, internal_dict):
+ return "I am an empty Empty1"
+
+
+class Empty1SynthProvider(object):
+ def __init__(self, sbvalue, internal_dict):
+ self._sbvalue = sbvalue
+
+ def num_children(self):
+ return 0
+
+ def get_child_at_index(self, index):
+ return None
+
+
+def empty2_summary(sbvalue, internal_dict):
+ return "I am an empty Empty2"
+
+
+class Empty2SynthProvider(object):
+ def __init__(self, sbvalue, internal_dict):
+ self._sbvalue = sbvalue
+
+ def num_children(self):
+ return 0
+
+ def get_child_at_index(self, index):
+ return None
+
+
+def __lldb_init_module(debugger,dict):
+ debugger.CreateCategory("JASSynth").AddTypeSynthetic(lldb.SBTypeNameSpecifier("JustAStruct"),
+ lldb.SBTypeSynthetic.CreateWithClassName("synth.jasSynthProvider"))
+ cat = lldb.debugger.CreateCategory("CCCSynth")
+ cat.AddTypeSynthetic(
+ lldb.SBTypeNameSpecifier("CCC"),
+ lldb.SBTypeSynthetic.CreateWithClassName("synth.CCCSynthProvider",
+ lldb.eTypeOptionCascade))
+ cat.AddTypeSummary(
+ lldb.SBTypeNameSpecifier("CCC"),
+ lldb.SBTypeSummary.CreateWithFunctionName("synth.ccc_summary",
+ lldb.eTypeOptionCascade))
+ cat.AddTypeSynthetic(
+ lldb.SBTypeNameSpecifier("Empty1"),
+ lldb.SBTypeSynthetic.CreateWithClassName("synth.Empty1SynthProvider"))
+ cat.AddTypeSummary(
+ lldb.SBTypeNameSpecifier("Empty1"),
+ lldb.SBTypeSummary.CreateWithFunctionName("synth.empty1_summary"))
+ cat.AddTypeSynthetic(
+ lldb.SBTypeNameSpecifier("Empty2"),
+ lldb.SBTypeSynthetic.CreateWithClassName("synth.Empty2SynthProvider"))
+ cat.AddTypeSummary(
+ lldb.SBTypeNameSpecifier("Empty2"),
+ lldb.SBTypeSummary.CreateWithFunctionName("synth.empty2_summary",
+ lldb.eTypeOptionHideEmptyAggregates))
diff --git a/packages/Python/lldbsuite/test/python_api/frame/Makefile b/packages/Python/lldbsuite/test/python_api/frame/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/frame/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/frame/TestFrames.py b/packages/Python/lldbsuite/test/python_api/frame/TestFrames.py
new file mode 100644
index 000000000000..7cc976fc6aa3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/frame/TestFrames.py
@@ -0,0 +1,207 @@
+"""
+Use lldb Python SBFrame API to get the argument values of the call stacks.
+And other SBFrame API tests.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class FrameAPITestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test_get_arg_vals_for_call_stack(self):
+ """Exercise SBFrame.GetVariables() API to get argument vals."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create a breakpoint on main.c by name 'c'.
+ breakpoint = target.BreakpointCreateByName('c', 'a.out')
+ #print("breakpoint:", breakpoint)
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ process = target.GetProcess()
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+
+ # Keeps track of the number of times 'a' is called where it is within a
+ # depth of 3 of the 'c' leaf function.
+ callsOfA = 0
+
+ from six import StringIO as SixStringIO
+ session = SixStringIO()
+ while process.GetState() == lldb.eStateStopped:
+ thread = process.GetThreadAtIndex(0)
+ # Inspect at most 3 frames.
+ numFrames = min(3, thread.GetNumFrames())
+ for i in range(numFrames):
+ frame = thread.GetFrameAtIndex(i)
+ if self.TraceOn():
+ print("frame:", frame)
+
+ name = frame.GetFunction().GetName()
+ if name == 'a':
+ callsOfA = callsOfA + 1
+
+ # We'll inspect only the arguments for the current frame:
+ #
+ # arguments => True
+ # locals => False
+ # statics => False
+ # in_scope_only => True
+ valList = frame.GetVariables(True, False, False, True)
+ argList = []
+ for val in valList:
+ argList.append("(%s)%s=%s" % (val.GetTypeName(),
+ val.GetName(),
+ val.GetValue()))
+ print("%s(%s)" % (name, ", ".join(argList)), file=session)
+
+ # Also check the generic pc & stack pointer. We can't test their absolute values,
+ # but they should be valid. Uses get_GPRs() from the lldbutil module.
+ gpr_reg_set = lldbutil.get_GPRs(frame)
+ pc_value = gpr_reg_set.GetChildMemberWithName("pc")
+ self.assertTrue (pc_value, "We should have a valid PC.")
+ pc_value_int = int(pc_value.GetValue(), 0)
+ # Make sure on arm targets we dont mismatch PC value on the basis of thumb bit.
+ # Frame PC will not have thumb bit set in case of a thumb instruction as PC.
+ if self.getArchitecture() in ['arm']:
+ pc_value_int &= ~1
+ self.assertTrue (pc_value_int == frame.GetPC(), "PC gotten as a value should equal frame's GetPC")
+ sp_value = gpr_reg_set.GetChildMemberWithName("sp")
+ self.assertTrue (sp_value, "We should have a valid Stack Pointer.")
+ self.assertTrue (int(sp_value.GetValue(), 0) == frame.GetSP(), "SP gotten as a value should equal frame's GetSP")
+
+ print("---", file=session)
+ process.Continue()
+
+ # At this point, the inferior process should have exited.
+ self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED)
+
+ # Expect to find 'a' on the call stacks two times.
+ self.assertTrue(callsOfA == 2,
+ "Expect to find 'a' on the call stacks two times")
+ # By design, the 'a' call frame has the following arg vals:
+ # o a((int)val=1, (char)ch='A')
+ # o a((int)val=3, (char)ch='A')
+ if self.TraceOn():
+ print("Full stack traces when stopped on the breakpoint 'c':")
+ print(session.getvalue())
+ self.expect(session.getvalue(), "Argugment values displayed correctly",
+ exe=False,
+ substrs = ["a((int)val=1, (char)ch='A')",
+ "a((int)val=3, (char)ch='A')"])
+
+ @add_test_categories(['pyapi'])
+ def test_frame_api_boundary_condition(self):
+ """Exercise SBFrame APIs with boundary condition inputs."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create a breakpoint on main.c by name 'c'.
+ breakpoint = target.BreakpointCreateByName('c', 'a.out')
+ #print("breakpoint:", breakpoint)
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ process = target.GetProcess()
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+
+ thread = process.GetThreadAtIndex(0)
+ frame = thread.GetFrameAtIndex(0)
+ if self.TraceOn():
+ print("frame:", frame)
+
+ # Boundary condition testings.
+ val1 = frame.FindVariable(None, True)
+ val2 = frame.FindVariable(None, False)
+ val3 = frame.FindValue(None, lldb.eValueTypeVariableGlobal)
+ if self.TraceOn():
+ print("val1:", val1)
+ print("val2:", val2)
+
+ frame.EvaluateExpression(None)
+
+ @add_test_categories(['pyapi'])
+ def test_frame_api_IsEqual(self):
+ """Exercise SBFrame API IsEqual."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create a breakpoint on main.c by name 'c'.
+ breakpoint = target.BreakpointCreateByName('c', 'a.out')
+ #print("breakpoint:", breakpoint)
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ process = target.GetProcess()
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+
+ thread = process.GetThreadAtIndex(0)
+ self.assertTrue(thread)
+
+ frameEntered = thread.GetFrameAtIndex(0)
+ if self.TraceOn():
+ print(frameEntered)
+ lldbutil.print_stacktrace(thread)
+ self.assertTrue(frameEntered)
+
+ # Doing two step overs while still inside c().
+ thread.StepOver()
+ thread.StepOver()
+ self.assertTrue(thread)
+ frameNow = thread.GetFrameAtIndex(0)
+ if self.TraceOn():
+ print(frameNow)
+ lldbutil.print_stacktrace(thread)
+ self.assertTrue(frameNow)
+
+ # The latest two frames are considered equal.
+ self.assertTrue(frameEntered.IsEqual(frameNow))
+
+ # Now let's step out of frame c().
+ thread.StepOutOfFrame(frameNow)
+ frameOutOfC = thread.GetFrameAtIndex(0)
+ if self.TraceOn():
+ print(frameOutOfC)
+ lldbutil.print_stacktrace(thread)
+ self.assertTrue(frameOutOfC)
+
+ # The latest two frames should not be equal.
+ self.assertFalse(frameOutOfC.IsEqual(frameNow))
diff --git a/packages/Python/lldbsuite/test/python_api/frame/inlines/Makefile b/packages/Python/lldbsuite/test/python_api/frame/inlines/Makefile
new file mode 100644
index 000000000000..641ee5d96ca6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/frame/inlines/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../../make
+
+C_SOURCES := inlines.c
+
+ifneq (,$(findstring icc,$(CC)))
+ CFLAGS += -debug inline-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/frame/inlines/TestInlinedFrame.py b/packages/Python/lldbsuite/test/python_api/frame/inlines/TestInlinedFrame.py
new file mode 100644
index 000000000000..d4cf8fe30ccd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/frame/inlines/TestInlinedFrame.py
@@ -0,0 +1,79 @@
+"""
+Testlldb Python SBFrame APIs IsInlined() and GetFunctionName().
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class InlinedFrameAPITestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to of function 'c'.
+ self.source = 'inlines.c'
+ self.first_stop = line_number(self.source, '// This should correspond to the first break stop.')
+ self.second_stop = line_number(self.source, '// This should correspond to the second break stop.')
+
+ @add_test_categories(['pyapi'])
+ def test_stop_at_outer_inline(self):
+ """Exercise SBFrame.IsInlined() and SBFrame.GetFunctionName()."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create a breakpoint on main.c by the name of 'inner_inline'.
+ breakpoint = target.BreakpointCreateByName('inner_inline', 'a.out')
+ #print("breakpoint:", breakpoint)
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() > 1,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ process = target.GetProcess()
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+
+ import lldbsuite.test.lldbutil as lldbutil
+ stack_traces1 = lldbutil.print_stacktraces(process, string_buffer=True)
+ if self.TraceOn():
+ print("Full stack traces when first stopped on the breakpoint 'inner_inline':")
+ print(stack_traces1)
+
+ # The first breakpoint should correspond to an inlined call frame.
+ # If it's an inlined call frame, expect to find, in the stack trace,
+ # that there is a frame which corresponds to the following call site:
+ #
+ # outer_inline (argc);
+ #
+ frame0 = process.GetThreadAtIndex(0).GetFrameAtIndex(0)
+ if frame0.IsInlined():
+ filename = frame0.GetLineEntry().GetFileSpec().GetFilename()
+ self.assertTrue(filename == self.source)
+ self.expect(stack_traces1, "First stop at %s:%d" % (self.source, self.first_stop), exe=False,
+ substrs = ['%s:%d' % (self.source, self.first_stop)])
+
+ # Expect to break again for the second time.
+ process.Continue()
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+ stack_traces2 = lldbutil.print_stacktraces(process, string_buffer=True)
+ if self.TraceOn():
+ print("Full stack traces when stopped on the breakpoint 'inner_inline' for the second time:")
+ print(stack_traces2)
+ self.expect(stack_traces2, "Second stop at %s:%d" % (self.source, self.second_stop), exe=False,
+ substrs = ['%s:%d' % (self.source, self.second_stop)])
diff --git a/packages/Python/lldbsuite/test/python_api/frame/inlines/inlines.c b/packages/Python/lldbsuite/test/python_api/frame/inlines/inlines.c
new file mode 100644
index 000000000000..a2a8212278d0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/frame/inlines/inlines.c
@@ -0,0 +1,53 @@
+#include <stdio.h>
+#include "inlines.h"
+
+#define INLINE_ME __inline__ __attribute__((always_inline))
+
+int
+not_inlined_2 (int input)
+{
+ printf ("Called in not_inlined_2 with : %d.\n", input);
+ return input;
+}
+
+int
+not_inlined_1 (int input)
+{
+ printf ("Called in not_inlined_1 with %d.\n", input);
+ return not_inlined_2(input);
+}
+
+INLINE_ME int
+inner_inline (int inner_input, int mod_value)
+{
+ int inner_result;
+ inner_result = inner_input % mod_value;
+ printf ("Returning: %d.\n", inner_result);
+ return not_inlined_1 (inner_result);
+}
+
+INLINE_ME int
+outer_inline (int outer_input)
+{
+ int outer_result;
+
+ outer_result = inner_inline (outer_input, outer_input % 3);
+ return outer_result;
+}
+
+int
+main (int argc, char **argv)
+{
+ printf ("Starting...\n");
+
+ int (*func_ptr) (int);
+ func_ptr = outer_inline;
+
+ outer_inline (argc); // This should correspond to the first break stop.
+
+ func_ptr (argc); // This should correspond to the second break stop.
+
+ return 0;
+}
+
+
diff --git a/packages/Python/lldbsuite/test/python_api/frame/inlines/inlines.h b/packages/Python/lldbsuite/test/python_api/frame/inlines/inlines.h
new file mode 100644
index 000000000000..265d7b4966ed
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/frame/inlines/inlines.h
@@ -0,0 +1,4 @@
+int inner_inline (int inner_input, int mod_value);
+int outer_inline (int outer_input);
+int not_inlined_2 (int input);
+int not_inlined_1 (int input);
diff --git a/packages/Python/lldbsuite/test/python_api/frame/main.c b/packages/Python/lldbsuite/test/python_api/frame/main.c
new file mode 100644
index 000000000000..35209db1812e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/frame/main.c
@@ -0,0 +1,58 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+// This simple program is to test the lldb Python API related to frames.
+
+int a(int, char);
+int b(int, char);
+int c(int, char);
+
+int a(int val, char ch)
+{
+ int my_val = val;
+ char my_ch = ch;
+ printf("a(val=%d, ch='%c')\n", val, ch);
+ if (val <= 1)
+ return b(val+1, ch+1);
+ else if (val >= 3)
+ return c(val+1, ch+1);
+
+ return val;
+}
+
+int b(int val, char ch)
+{
+ int my_val = val;
+ char my_ch = ch;
+ printf("b(val=%d, ch='%c')\n", val, ch);
+ return c(val+1, ch+1);
+}
+
+int c(int val, char ch)
+{
+ int my_val = val;
+ char my_ch = ch;
+ printf("c(val=%d, ch='%c')\n", val, ch);
+ return val + 3 + ch;
+}
+
+int main (int argc, char const *argv[])
+{
+ int A1 = a(1, 'A'); // a(1, 'A') -> b(2, 'B') -> c(3, 'C')
+ printf("a(1, 'A') returns %d\n", A1);
+
+ int B2 = b(2, 'B'); // b(2, 'B') -> c(3, 'C')
+ printf("b(2, 'B') returns %d\n", B2);
+
+ int A3 = a(3, 'A'); // a(3, 'A') -> c(4, 'B')
+ printf("a(3, 'A') returns %d\n", A3);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/python_api/function_symbol/Makefile b/packages/Python/lldbsuite/test/python_api/function_symbol/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/function_symbol/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/function_symbol/TestDisasmAPI.py b/packages/Python/lldbsuite/test/python_api/function_symbol/TestDisasmAPI.py
new file mode 100644
index 000000000000..c9876a8c8954
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/function_symbol/TestDisasmAPI.py
@@ -0,0 +1,111 @@
+"""
+Test retrieval of SBAddress from function/symbol, disassembly, and SBAddress APIs.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class DisasmAPITestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to of function 'c'.
+ self.line1 = line_number('main.c', '// Find the line number for breakpoint 1 here.')
+ self.line2 = line_number('main.c', '// Find the line number for breakpoint 2 here.')
+
+ @add_test_categories(['pyapi'])
+ def test(self):
+ """Exercise getting SBAddress objects, disassembly, and SBAddress APIs."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create the two breakpoints inside function 'a'.
+ breakpoint1 = target.BreakpointCreateByLocation('main.c', self.line1)
+ breakpoint2 = target.BreakpointCreateByLocation('main.c', self.line2)
+ #print("breakpoint1:", breakpoint1)
+ #print("breakpoint2:", breakpoint2)
+ self.assertTrue(breakpoint1 and
+ breakpoint1.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+ self.assertTrue(breakpoint2 and
+ breakpoint2.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Frame #0 should be on self.line1.
+ self.assertTrue(process.GetState() == lldb.eStateStopped)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
+ frame0 = thread.GetFrameAtIndex(0)
+ lineEntry = frame0.GetLineEntry()
+ self.assertTrue(lineEntry.GetLine() == self.line1)
+
+ address1 = lineEntry.GetStartAddress()
+ #print("address1:", address1)
+
+ # Now call SBTarget.ResolveSymbolContextForAddress() with address1.
+ context1 = target.ResolveSymbolContextForAddress(address1, lldb.eSymbolContextEverything)
+
+ self.assertTrue(context1)
+ if self.TraceOn():
+ print("context1:", context1)
+
+ # Continue the inferior, the breakpoint 2 should be hit.
+ process.Continue()
+ self.assertTrue(process.GetState() == lldb.eStateStopped)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
+ frame0 = thread.GetFrameAtIndex(0)
+ lineEntry = frame0.GetLineEntry()
+ self.assertTrue(lineEntry.GetLine() == self.line2)
+
+ # Verify that the symbol and the function has the same address range per function 'a'.
+ symbol = context1.GetSymbol()
+ function = frame0.GetFunction()
+ self.assertTrue(symbol and function)
+
+ disasm_output = lldbutil.disassemble(target, symbol)
+ if self.TraceOn():
+ print("symbol:", symbol)
+ print("disassembly=>\n", disasm_output)
+
+ disasm_output = lldbutil.disassemble(target, function)
+ if self.TraceOn():
+ print("function:", function)
+ print("disassembly=>\n", disasm_output)
+
+ sa1 = symbol.GetStartAddress()
+ #print("sa1:", sa1)
+ #print("sa1.GetFileAddress():", hex(sa1.GetFileAddress()))
+ #ea1 = symbol.GetEndAddress()
+ #print("ea1:", ea1)
+ sa2 = function.GetStartAddress()
+ #print("sa2:", sa2)
+ #print("sa2.GetFileAddress():", hex(sa2.GetFileAddress()))
+ #ea2 = function.GetEndAddress()
+ #print("ea2:", ea2)
+ self.assertTrue(sa1 and sa2 and sa1 == sa2,
+ "The two starting addresses should be the same")
+
+ from lldbsuite.test.lldbutil import get_description
+ desc1 = get_description(sa1)
+ desc2 = get_description(sa2)
+ self.assertTrue(desc1 and desc2 and desc1 == desc2,
+ "SBAddress.GetDescription() API of sa1 and sa2 should return the same string")
diff --git a/packages/Python/lldbsuite/test/python_api/function_symbol/TestSymbolAPI.py b/packages/Python/lldbsuite/test/python_api/function_symbol/TestSymbolAPI.py
new file mode 100644
index 000000000000..d45f5724f49c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/function_symbol/TestSymbolAPI.py
@@ -0,0 +1,81 @@
+"""
+Test newly added SBSymbol and SBAddress APIs.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class SymbolAPITestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to of function 'c'.
+ self.line1 = line_number('main.c', '// Find the line number for breakpoint 1 here.')
+ self.line2 = line_number('main.c', '// Find the line number for breakpoint 2 here.')
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test(self):
+ """Exercise some SBSymbol and SBAddress APIs."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create the two breakpoints inside function 'a'.
+ breakpoint1 = target.BreakpointCreateByLocation('main.c', self.line1)
+ breakpoint2 = target.BreakpointCreateByLocation('main.c', self.line2)
+ #print("breakpoint1:", breakpoint1)
+ #print("breakpoint2:", breakpoint2)
+ self.assertTrue(breakpoint1 and
+ breakpoint1.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+ self.assertTrue(breakpoint2 and
+ breakpoint2.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Frame #0 should be on self.line1.
+ self.assertTrue(process.GetState() == lldb.eStateStopped)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
+ frame0 = thread.GetFrameAtIndex(0)
+ symbol_line1 = frame0.GetSymbol()
+ # We should have a symbol type of code.
+ self.assertTrue(symbol_line1.GetType() == lldb.eSymbolTypeCode)
+ addr_line1 = symbol_line1.GetStartAddress()
+ # And a section type of code, too.
+ self.assertTrue(addr_line1.GetSection().GetSectionType() == lldb.eSectionTypeCode)
+
+ # Continue the inferior, the breakpoint 2 should be hit.
+ process.Continue()
+ self.assertTrue(process.GetState() == lldb.eStateStopped)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
+ frame0 = thread.GetFrameAtIndex(0)
+ symbol_line2 = frame0.GetSymbol()
+ # We should have a symbol type of code.
+ self.assertTrue(symbol_line2.GetType() == lldb.eSymbolTypeCode)
+ addr_line2 = symbol_line2.GetStartAddress()
+ # And a section type of code, too.
+ self.assertTrue(addr_line2.GetSection().GetSectionType() == lldb.eSectionTypeCode)
+
+ # Now verify that both addresses point to the same module.
+ if self.TraceOn():
+ print("UUID:", addr_line1.GetModule().GetUUIDString())
+ self.assertTrue(addr_line1.GetModule().GetUUIDString() == addr_line2.GetModule().GetUUIDString())
diff --git a/packages/Python/lldbsuite/test/python_api/function_symbol/main.c b/packages/Python/lldbsuite/test/python_api/function_symbol/main.c
new file mode 100644
index 000000000000..b60b2faf18dc
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/function_symbol/main.c
@@ -0,0 +1,60 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+// This simple program is to test the lldb Python APIs SBTarget, SBFrame,
+// SBFunction, SBSymbol, and SBAddress.
+//
+// When stopped on breakppint 1, we can get the line entry using SBFrame API
+// SBFrame.GetLineEntry(). We'll get the start address for the line entry
+// with the SBAddress type, resolve the symbol context using the SBTarget API
+// SBTarget.ResolveSymbolContextForAddress() in order to get the SBSymbol.
+//
+// We then stop at breakpoint 2, get the SBFrame, and the SBFunction object.
+//
+// The address from calling GetStartAddress() on the symbol and the function
+// should point to the same address, and we also verify that.
+
+int a(int);
+int b(int);
+int c(int);
+
+int a(int val)
+{
+ if (val <= 1) // Find the line number for breakpoint 1 here.
+ val = b(val);
+ else if (val >= 3)
+ val = c(val);
+
+ return val; // Find the line number for breakpoint 2 here.
+}
+
+int b(int val)
+{
+ return c(val);
+}
+
+int c(int val)
+{
+ return val + 3;
+}
+
+int main (int argc, char const *argv[])
+{
+ int A1 = a(1); // a(1) -> b(1) -> c(1)
+ printf("a(1) returns %d\n", A1);
+
+ int B2 = b(2); // b(2) -> c(2)
+ printf("b(2) returns %d\n", B2);
+
+ int A3 = a(3); // a(3) -> c(3)
+ printf("a(3) returns %d\n", A3);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/python_api/hello_world/Makefile b/packages/Python/lldbsuite/test/python_api/hello_world/Makefile
new file mode 100644
index 000000000000..9976203b63bb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/hello_world/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+# See TestHelloWorld.py, which specifies the executable name with a dictionary.
+EXE := hello_world
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/hello_world/TestHelloWorld.py b/packages/Python/lldbsuite/test/python_api/hello_world/TestHelloWorld.py
new file mode 100644
index 000000000000..47c3ba146cef
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/hello_world/TestHelloWorld.py
@@ -0,0 +1,147 @@
+"""Test Python APIs for target (launch and attach), breakpoint, and process."""
+
+from __future__ import print_function
+
+
+
+import os, sys, time
+import lldb
+import time
+from lldbsuite.test.lldbtest import *
+
+class HelloWorldTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Get the full path to our executable to be attached/debugged.
+ self.exe = os.path.join(os.getcwd(), self.testMethodName)
+ self.d = {'EXE': self.testMethodName}
+ # Find a couple of the line numbers within main.c.
+ self.line1 = line_number('main.c', '// Set break point at this line.')
+ self.line2 = line_number('main.c', '// Waiting to be attached...')
+
+ def tearDown(self):
+ # Destroy process before TestBase.tearDown()
+ self.dbg.GetSelectedTarget().GetProcess().Destroy()
+ # Call super's tearDown().
+ TestBase.tearDown(self)
+
+ @add_test_categories(['pyapi'])
+ @skipIfiOSSimulator
+ def test_with_process_launch_api(self):
+ """Create target, breakpoint, launch a process, and then kill it."""
+ self.build(dictionary=self.d)
+ self.setTearDownCleanup(dictionary=self.d)
+ target = self.dbg.CreateTarget(self.exe)
+
+ breakpoint = target.BreakpointCreateByLocation("main.c", self.line1)
+
+ # The default state after breakpoint creation should be enabled.
+ self.assertTrue(breakpoint.IsEnabled(),
+ "Breakpoint should be enabled after creation")
+
+ breakpoint.SetEnabled(False)
+ self.assertTrue(not breakpoint.IsEnabled(),
+ "Breakpoint.SetEnabled(False) works")
+
+ breakpoint.SetEnabled(True)
+ self.assertTrue(breakpoint.IsEnabled(),
+ "Breakpoint.SetEnabled(True) works")
+
+ # rdar://problem/8364687
+ # SBTarget.Launch() issue (or is there some race condition)?
+
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ # The following isn't needed anymore, rdar://8364687 is fixed.
+ #
+ # Apply some dances after LaunchProcess() in order to break at "main".
+ # It only works sometimes.
+ #self.breakAfterLaunch(process, "main")
+
+ process = target.GetProcess()
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ thread = process.GetThreadAtIndex(0)
+ if thread.GetStopReason() != lldb.eStopReasonBreakpoint:
+ from lldbsuite.test.lldbutil import stop_reason_to_str
+ self.fail(STOPPED_DUE_TO_BREAKPOINT_WITH_STOP_REASON_AS %
+ stop_reason_to_str(thread.GetStopReason()))
+
+ # The breakpoint should have a hit count of 1.
+ self.assertTrue(breakpoint.GetHitCount() == 1, BREAKPOINT_HIT_ONCE)
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureWindows("llvm.org/pr24600")
+ @expectedFailurei386("llvm.org/pr25338")
+ @skipIfiOSSimulator
+ def test_with_attach_to_process_with_id_api(self):
+ """Create target, spawn a process, and attach to it with process id."""
+ self.build(dictionary=self.d)
+ self.setTearDownCleanup(dictionary=self.d)
+ target = self.dbg.CreateTarget(self.exe)
+
+ # Spawn a new process
+ popen = self.spawnSubprocess(self.exe, ["abc", "xyz"])
+ self.addTearDownHook(self.cleanupSubprocesses)
+
+ # Give the subprocess time to start and wait for user input
+ time.sleep(0.25)
+
+ listener = lldb.SBListener("my.attach.listener")
+ error = lldb.SBError()
+ process = target.AttachToProcessWithID(listener, popen.pid, error)
+
+ self.assertTrue(error.Success() and process, PROCESS_IS_VALID)
+
+ # Let's check the stack traces of the attached process.
+ import lldbsuite.test.lldbutil as lldbutil
+ stacktraces = lldbutil.print_stacktraces(process, string_buffer=True)
+ self.expect(stacktraces, exe=False,
+ substrs = ['main.c:%d' % self.line2,
+ '(int)argc=3'])
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureWindows("llvm.org/pr24600")
+ @expectedFailurei386("llvm.org/pr25338")
+ @skipIfiOSSimulator
+ def test_with_attach_to_process_with_name_api(self):
+ """Create target, spawn a process, and attach to it with process name."""
+ self.build(dictionary=self.d)
+ self.setTearDownCleanup(dictionary=self.d)
+ target = self.dbg.CreateTarget(self.exe)
+
+ # Spawn a new process
+ popen = self.spawnSubprocess(self.exe, ["abc", "xyz"])
+ self.addTearDownHook(self.cleanupSubprocesses)
+
+ # Give the subprocess time to start and wait for user input
+ time.sleep(0.25)
+
+ listener = lldb.SBListener("my.attach.listener")
+ error = lldb.SBError()
+ # Pass 'False' since we don't want to wait for new instance of "hello_world" to be launched.
+ name = os.path.basename(self.exe)
+
+ # While we're at it, make sure that passing a None as the process name
+ # does not hang LLDB.
+ target.AttachToProcessWithName(listener, None, False, error)
+ # Also boundary condition test ConnectRemote(), too.
+ target.ConnectRemote(listener, None, None, error)
+
+ process = target.AttachToProcessWithName(listener, name, False, error)
+
+ self.assertTrue(error.Success() and process, PROCESS_IS_VALID)
+
+ # Verify that after attach, our selected target indeed matches name.
+ self.expect(self.dbg.GetSelectedTarget().GetExecutable().GetFilename(), exe=False,
+ startstr = name)
+
+ # Let's check the stack traces of the attached process.
+ import lldbsuite.test.lldbutil as lldbutil
+ stacktraces = lldbutil.print_stacktraces(process, string_buffer=True)
+ self.expect(stacktraces, exe=False,
+ substrs = ['main.c:%d' % self.line2,
+ '(int)argc=3'])
diff --git a/packages/Python/lldbsuite/test/python_api/hello_world/main.c b/packages/Python/lldbsuite/test/python_api/hello_world/main.c
new file mode 100644
index 000000000000..31a041ede741
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/hello_world/main.c
@@ -0,0 +1,35 @@
+#include <stdio.h>
+
+#if defined(__linux__)
+#include <sys/prctl.h>
+#endif
+
+int main(int argc, char const *argv[]) {
+
+#if defined(__linux__)
+ // Immediately enable any ptracer so that we can allow the stub attach
+ // operation to succeed. Some Linux kernels are locked down so that
+ // only an ancestor process can be a ptracer of a process. This disables that
+ // restriction. Without it, attach-related stub tests will fail.
+#if defined(PR_SET_PTRACER) && defined(PR_SET_PTRACER_ANY)
+ int prctl_result;
+
+ // For now we execute on best effort basis. If this fails for
+ // some reason, so be it.
+ prctl_result = prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
+ (void) prctl_result;
+#endif
+#endif
+
+ printf("Hello world.\n"); // Set break point at this line.
+ if (argc == 1)
+ return 0;
+
+ // Waiting to be attached by the debugger, otherwise.
+ char line[100];
+ while (fgets(line, sizeof(line), stdin)) { // Waiting to be attached...
+ printf("input line=>%s\n", line);
+ }
+
+ printf("Exiting now\n");
+}
diff --git a/packages/Python/lldbsuite/test/python_api/interpreter/Makefile b/packages/Python/lldbsuite/test/python_api/interpreter/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/interpreter/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/interpreter/TestCommandInterpreterAPI.py b/packages/Python/lldbsuite/test/python_api/interpreter/TestCommandInterpreterAPI.py
new file mode 100644
index 000000000000..faff11818da7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/interpreter/TestCommandInterpreterAPI.py
@@ -0,0 +1,73 @@
+"""Test the SBCommandInterpreter APIs."""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class CommandInterpreterAPICase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break on inside main.cpp.
+ self.line = line_number('main.c', 'Hello world.')
+
+ @add_test_categories(['pyapi'])
+ def test_with_process_launch_api(self):
+ """Test the SBCommandInterpreter APIs."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Retrieve the associated command interpreter from our debugger.
+ ci = self.dbg.GetCommandInterpreter()
+ self.assertTrue(ci, VALID_COMMAND_INTERPRETER)
+
+ # Exercise some APIs....
+
+ self.assertTrue(ci.HasCommands())
+ self.assertTrue(ci.HasAliases())
+ self.assertTrue(ci.HasAliasOptions())
+ self.assertTrue(ci.CommandExists("breakpoint"))
+ self.assertTrue(ci.CommandExists("target"))
+ self.assertTrue(ci.CommandExists("platform"))
+ self.assertTrue(ci.AliasExists("file"))
+ self.assertTrue(ci.AliasExists("run"))
+ self.assertTrue(ci.AliasExists("bt"))
+
+ res = lldb.SBCommandReturnObject()
+ ci.HandleCommand("breakpoint set -f main.c -l %d" % self.line, res)
+ self.assertTrue(res.Succeeded())
+ ci.HandleCommand("process launch", res)
+ self.assertTrue(res.Succeeded())
+
+ # Boundary conditions should not crash lldb!
+ self.assertFalse(ci.CommandExists(None))
+ self.assertFalse(ci.AliasExists(None))
+ ci.HandleCommand(None, res)
+ self.assertFalse(res.Succeeded())
+ res.AppendMessage("Just appended a message.")
+ res.AppendMessage(None)
+ if self.TraceOn():
+ print(res)
+
+ process = ci.GetProcess()
+ self.assertTrue(process)
+
+ import lldbsuite.test.lldbutil as lldbutil
+ if process.GetState() != lldb.eStateStopped:
+ self.fail("Process should be in the 'stopped' state, "
+ "instead the actual state is: '%s'" %
+ lldbutil.state_type_to_str(process.GetState()))
+
+ if self.TraceOn():
+ lldbutil.print_stacktraces(process)
diff --git a/packages/Python/lldbsuite/test/python_api/interpreter/main.c b/packages/Python/lldbsuite/test/python_api/interpreter/main.c
new file mode 100644
index 000000000000..277aa54a4eea
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/interpreter/main.c
@@ -0,0 +1,6 @@
+#include <stdio.h>
+
+int main(int argc, char const *argv[]) {
+ printf("Hello world.\n");
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/python_api/lldbutil/frame/Makefile b/packages/Python/lldbsuite/test/python_api/lldbutil/frame/Makefile
new file mode 100644
index 000000000000..69b74b5d7531
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/lldbutil/frame/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+MAKE_DSYM :=NO
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/lldbutil/frame/TestFrameUtils.py b/packages/Python/lldbsuite/test/python_api/lldbutil/frame/TestFrameUtils.py
new file mode 100644
index 000000000000..2cde05af0c39
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/lldbutil/frame/TestFrameUtils.py
@@ -0,0 +1,59 @@
+"""
+Test utility functions for the frame object.
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class FrameUtilsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.c',
+ "// Find the line number here.")
+
+ @add_test_categories(['pyapi'])
+ def test_frame_utils(self):
+ """Test utility functions for the frame object."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByLocation("main.c", self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ if not process:
+ self.fail("SBTarget.LaunchProcess() failed")
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+
+ import lldbsuite.test.lldbutil as lldbutil
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue (thread)
+ frame0 = thread.GetFrameAtIndex(0)
+ self.assertTrue (frame0)
+ frame1 = thread.GetFrameAtIndex(1)
+ self.assertTrue (frame1)
+ parent = lldbutil.get_parent_frame(frame0)
+ self.assertTrue(parent and parent.GetFrameID() == frame1.GetFrameID())
+ frame0_args = lldbutil.get_args_as_string(frame0)
+ parent_args = lldbutil.get_args_as_string(parent)
+ self.assertTrue(frame0_args and parent_args and "(int)val=1" in frame0_args)
+ if self.TraceOn():
+ lldbutil.print_stacktrace(thread)
+ print("Current frame: %s" % frame0_args)
+ print("Parent frame: %s" % parent_args)
diff --git a/packages/Python/lldbsuite/test/python_api/lldbutil/frame/main.c b/packages/Python/lldbsuite/test/python_api/lldbutil/frame/main.c
new file mode 100644
index 000000000000..e6eeef5b46d9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/lldbutil/frame/main.c
@@ -0,0 +1,47 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+int a(int);
+int b(int);
+int c(int);
+
+int a(int val)
+{
+ if (val <= 1)
+ return b(val);
+ else if (val >= 3)
+ return c(val);
+
+ return val;
+}
+
+int b(int val)
+{
+ return c(val);
+}
+
+int c(int val)
+{
+ return val + 3; // Find the line number here.
+}
+
+int main (int argc, char const *argv[])
+{
+ int A1 = a(1); // a(1) -> b(1) -> c(1)
+ printf("a(1) returns %d\n", A1);
+
+ int B2 = b(2); // b(2) -> c(2)
+ printf("b(2) returns %d\n", B2);
+
+ int A3 = a(3); // a(3) -> c(3)
+ printf("a(3) returns %d\n", A3);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/python_api/lldbutil/iter/Makefile b/packages/Python/lldbsuite/test/python_api/lldbutil/iter/Makefile
new file mode 100644
index 000000000000..051354123495
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/lldbutil/iter/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../../make
+
+CFLAGS_EXTRAS += -D__STDC_LIMIT_MACROS
+ENABLE_THREADS := YES
+CXX_SOURCES := main.cpp
+MAKE_DSYM := NO
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestLLDBIterator.py b/packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestLLDBIterator.py
new file mode 100644
index 000000000000..07177c1fae4a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestLLDBIterator.py
@@ -0,0 +1,122 @@
+"""
+Test the iteration protocol for some lldb container objects.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class LLDBIteratorTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line numbers to break inside main().
+ self.line1 = line_number('main.cpp', '// Set break point at this line.')
+ self.line2 = line_number('main.cpp', '// And that line.')
+
+ @add_test_categories(['pyapi'])
+ def test_lldb_iter_module(self):
+ """Test module_iter works correctly for SBTarget -> SBModule."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line1)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ if not process:
+ self.fail("SBTarget.LaunchProcess() failed")
+
+ from lldbsuite.test.lldbutil import get_description
+ yours = []
+ for i in range(target.GetNumModules()):
+ yours.append(target.GetModuleAtIndex(i))
+ mine = []
+ for m in target.module_iter():
+ mine.append(m)
+
+ self.assertTrue(len(yours) == len(mine))
+ for i in range(len(yours)):
+ if self.TraceOn():
+ print("yours[%d]='%s'" % (i, get_description(yours[i])))
+ print("mine[%d]='%s'" % (i, get_description(mine[i])))
+ self.assertTrue(yours[i] == mine[i],
+ "UUID+FileSpec of yours[{0}] and mine[{0}] matches".format(i))
+
+ @add_test_categories(['pyapi'])
+ def test_lldb_iter_breakpoint(self):
+ """Test breakpoint_iter works correctly for SBTarget -> SBBreakpoint."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line1)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+ breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line2)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ self.assertTrue(target.GetNumBreakpoints() == 2)
+
+ from lldbsuite.test.lldbutil import get_description
+ yours = []
+ for i in range(target.GetNumBreakpoints()):
+ yours.append(target.GetBreakpointAtIndex(i))
+ mine = []
+ for b in target.breakpoint_iter():
+ mine.append(b)
+
+ self.assertTrue(len(yours) == len(mine))
+ for i in range(len(yours)):
+ if self.TraceOn():
+ print("yours[%d]='%s'" % (i, get_description(yours[i])))
+ print("mine[%d]='%s'" % (i, get_description(mine[i])))
+ self.assertTrue(yours[i] == mine[i],
+ "ID of yours[{0}] and mine[{0}] matches".format(i))
+
+ @add_test_categories(['pyapi'])
+ def test_lldb_iter_frame(self):
+ """Test iterator works correctly for SBProcess->SBThread->SBFrame."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line1)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ if not process:
+ self.fail("SBTarget.LaunchProcess() failed")
+
+ from lldbsuite.test.lldbutil import print_stacktrace
+ stopped_due_to_breakpoint = False
+ for thread in process:
+ if self.TraceOn():
+ print_stacktrace(thread)
+ ID = thread.GetThreadID()
+ if thread.GetStopReason() == lldb.eStopReasonBreakpoint:
+ stopped_due_to_breakpoint = True
+ for frame in thread:
+ self.assertTrue(frame.GetThread().GetThreadID() == ID)
+ if self.TraceOn():
+ print(frame)
+
+ self.assertTrue(stopped_due_to_breakpoint)
diff --git a/packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestRegistersIterator.py b/packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestRegistersIterator.py
new file mode 100644
index 000000000000..1645ae1f2a5d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/lldbutil/iter/TestRegistersIterator.py
@@ -0,0 +1,94 @@
+"""
+Test the iteration protocol for frame registers.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class RegistersIteratorTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line1 = line_number('main.cpp', '// Set break point at this line.')
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureWindows # Test crashes
+ def test_iter_registers(self):
+ """Test iterator works correctly for lldbutil.iter_registers()."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line1)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ if not process:
+ self.fail("SBTarget.LaunchProcess() failed")
+
+ import lldbsuite.test.lldbutil as lldbutil
+ for thread in process:
+ if thread.GetStopReason() == lldb.eStopReasonBreakpoint:
+ for frame in thread:
+ # Dump the registers of this frame using lldbutil.get_GPRs() and friends.
+ if self.TraceOn():
+ print(frame)
+
+ REGs = lldbutil.get_GPRs(frame)
+ num = len(REGs)
+ if self.TraceOn():
+ print("\nNumber of general purpose registers: %d" % num)
+ for reg in REGs:
+ self.assertTrue(reg)
+ if self.TraceOn():
+ print("%s => %s" % (reg.GetName(), reg.GetValue()))
+
+ REGs = lldbutil.get_FPRs(frame)
+ num = len(REGs)
+ if self.TraceOn():
+ print("\nNumber of floating point registers: %d" % num)
+ for reg in REGs:
+ self.assertTrue(reg)
+ if self.TraceOn():
+ print("%s => %s" % (reg.GetName(), reg.GetValue()))
+
+ REGs = lldbutil.get_ESRs(frame)
+ if self.platformIsDarwin():
+ num = len(REGs)
+ if self.TraceOn():
+ print("\nNumber of exception state registers: %d" % num)
+ for reg in REGs:
+ self.assertTrue(reg)
+ if self.TraceOn():
+ print("%s => %s" % (reg.GetName(), reg.GetValue()))
+ else:
+ self.assertIsNone(REGs)
+
+ # And these should also work.
+ for kind in ["General Purpose Registers",
+ "Floating Point Registers"]:
+ REGs = lldbutil.get_registers(frame, kind)
+ self.assertTrue(REGs)
+
+ REGs = lldbutil.get_registers(frame, "Exception State Registers")
+ if self.platformIsDarwin():
+ self.assertIsNotNone(REGs)
+ else:
+ self.assertIsNone(REGs)
+
+ # We've finished dumping the registers for frame #0.
+ break
diff --git a/packages/Python/lldbsuite/test/python_api/lldbutil/iter/main.cpp b/packages/Python/lldbsuite/test/python_api/lldbutil/iter/main.cpp
new file mode 100644
index 000000000000..8fb45f94b1ef
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/lldbutil/iter/main.cpp
@@ -0,0 +1,134 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+// C includes
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+// C++ includes
+#include <chrono>
+#include <mutex>
+#include <random>
+#include <thread>
+
+std::thread g_thread_1;
+std::thread g_thread_2;
+std::thread g_thread_3;
+std::mutex g_mask_mutex;
+
+typedef enum {
+ eGet,
+ eAssign,
+ eClearBits
+} MaskAction;
+
+uint32_t mask_access (MaskAction action, uint32_t mask = 0);
+
+uint32_t
+mask_access (MaskAction action, uint32_t mask)
+{
+ static uint32_t g_mask = 0;
+
+ std::lock_guard<std::mutex> lock(g_mask_mutex);
+ switch (action)
+ {
+ case eGet:
+ break;
+
+ case eAssign:
+ g_mask |= mask;
+ break;
+
+ case eClearBits:
+ g_mask &= ~mask;
+ break;
+ }
+ return g_mask;
+}
+
+void *
+thread_func (void *arg)
+{
+ uint32_t thread_index = *((uint32_t *)arg);
+ uint32_t thread_mask = (1u << (thread_index));
+ printf ("%s (thread index = %u) startng...\n", __FUNCTION__, thread_index);
+
+ std::default_random_engine generator;
+ std::uniform_int_distribution<int> distribution(0, 3000000);
+
+ while (mask_access(eGet) & thread_mask)
+ {
+ // random micro second sleep from zero to 3 seconds
+ int usec = distribution(generator);
+ printf ("%s (thread = %u) doing a usleep (%d)...\n", __FUNCTION__, thread_index, usec);
+
+ std::chrono::microseconds duration(usec);
+ std::this_thread::sleep_for(duration);
+ printf ("%s (thread = %u) after usleep ...\n", __FUNCTION__, thread_index); // Set break point at this line.
+ }
+ printf ("%s (thread index = %u) exiting...\n", __FUNCTION__, thread_index);
+ return NULL;
+}
+
+
+int main (int argc, char const *argv[])
+{
+ uint32_t thread_index_1 = 1;
+ uint32_t thread_index_2 = 2;
+ uint32_t thread_index_3 = 3;
+ uint32_t thread_mask_1 = (1u << thread_index_1);
+ uint32_t thread_mask_2 = (1u << thread_index_2);
+ uint32_t thread_mask_3 = (1u << thread_index_3);
+
+ // Make a mask that will keep all threads alive
+ mask_access (eAssign, thread_mask_1 | thread_mask_2 | thread_mask_3); // And that line.
+
+ // Create 3 threads
+ g_thread_1 = std::thread(thread_func, (void*)&thread_index_1);
+ g_thread_2 = std::thread(thread_func, (void*)&thread_index_2);
+ g_thread_3 = std::thread(thread_func, (void*)&thread_index_3);
+
+ char line[64];
+ while (mask_access(eGet) != 0)
+ {
+ printf ("Enter thread index to kill or ENTER for all:\n");
+ fflush (stdout);
+ // Kill threads by index, or ENTER for all threads
+
+ if (fgets (line, sizeof(line), stdin))
+ {
+ if (line[0] == '\n' || line[0] == '\r' || line[0] == '\0')
+ {
+ printf ("Exiting all threads...\n");
+ break;
+ }
+ int32_t index = strtoul (line, NULL, 0);
+ switch (index)
+ {
+ case 1: mask_access (eClearBits, thread_mask_1); break;
+ case 2: mask_access (eClearBits, thread_mask_2); break;
+ case 3: mask_access (eClearBits, thread_mask_3); break;
+ }
+ continue;
+ }
+
+ break;
+ }
+
+ // Clear all thread bits to they all exit
+ mask_access (eClearBits, UINT32_MAX);
+
+ // Join all of our threads
+ g_thread_1.join();
+ g_thread_2.join();
+ g_thread_3.join();
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/python_api/lldbutil/process/Makefile b/packages/Python/lldbsuite/test/python_api/lldbutil/process/Makefile
new file mode 100644
index 000000000000..93fc28b4ee07
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/lldbutil/process/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../../make
+
+CFLAGS_EXTRAS += -D__STDC_LIMIT_MACROS
+ENABLE_THREADS := YES
+CXX_SOURCES := main.cpp
+MAKE_DSYM :=NO
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/lldbutil/process/TestPrintStackTraces.py b/packages/Python/lldbsuite/test/python_api/lldbutil/process/TestPrintStackTraces.py
new file mode 100644
index 000000000000..b48ded4dd365
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/lldbutil/process/TestPrintStackTraces.py
@@ -0,0 +1,52 @@
+"""
+Test SBprocess and SBThread APIs with printing of the stack traces using lldbutil.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class ThreadsStackTracesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ @expectedFailureAll("llvm.org/pr23043", ["linux"], archs=["i386"]) # We are unable to produce a backtrace of the main thread when the thread is blocked in fgets
+ @expectedFailureWindows("llvm.org/pr24778")
+ @add_test_categories(['pyapi'])
+ def test_stack_traces(self):
+ """Test SBprocess and SBThread APIs with printing of the stack traces."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (["abc", "xyz"], None, self.get_process_working_directory())
+
+ if not process:
+ self.fail("SBTarget.LaunchProcess() failed")
+
+ import lldbsuite.test.lldbutil as lldbutil
+ if process.GetState() != lldb.eStateStopped:
+ self.fail("Process should be in the 'stopped' state, "
+ "instead the actual state is: '%s'" %
+ lldbutil.state_type_to_str(process.GetState()))
+
+ stacktraces = lldbutil.print_stacktraces(process, string_buffer=True)
+ self.expect(stacktraces, exe=False,
+ substrs = ['(int)argc=3'])
diff --git a/packages/Python/lldbsuite/test/python_api/lldbutil/process/main.cpp b/packages/Python/lldbsuite/test/python_api/lldbutil/process/main.cpp
new file mode 100644
index 000000000000..6b87c3d649e6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/lldbutil/process/main.cpp
@@ -0,0 +1,136 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+// C includes
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+// C++ includes
+#include <chrono>
+#include <mutex>
+#include <random>
+#include <thread>
+
+std::thread g_thread_1;
+std::thread g_thread_2;
+std::thread g_thread_3;
+std::mutex g_mask_mutex;
+
+typedef enum {
+ eGet,
+ eAssign,
+ eClearBits
+} MaskAction;
+
+uint32_t mask_access (MaskAction action, uint32_t mask = 0);
+
+uint32_t
+mask_access (MaskAction action, uint32_t mask)
+{
+ static uint32_t g_mask = 0;
+
+ std::lock_guard<std::mutex> lock(g_mask_mutex);
+ switch (action)
+ {
+ case eGet:
+ break;
+
+ case eAssign:
+ g_mask |= mask;
+ break;
+
+ case eClearBits:
+ g_mask &= ~mask;
+ break;
+ }
+ return g_mask;
+}
+
+void *
+thread_func (void *arg)
+{
+ uint32_t thread_index = *((uint32_t *)arg);
+ uint32_t thread_mask = (1u << (thread_index));
+ printf ("%s (thread index = %u) startng...\n", __FUNCTION__, thread_index);
+
+ std::default_random_engine generator;
+ std::uniform_int_distribution<int> distribution(0, 3000000);
+
+ while (mask_access(eGet) & thread_mask)
+ {
+ // random micro second sleep from zero to 3 seconds
+ int usec = distribution(generator);
+
+ printf ("%s (thread = %u) doing a usleep (%d)...\n", __FUNCTION__, thread_index, usec);
+ std::chrono::microseconds duration(usec);
+ std::this_thread::sleep_for(duration);
+ printf ("%s (thread = %u) after usleep ...\n", __FUNCTION__, thread_index); // Set break point at this line.
+ }
+ printf ("%s (thread index = %u) exiting...\n", __FUNCTION__, thread_index);
+ return NULL;
+}
+
+
+int main (int argc, char const *argv[])
+{
+ int err;
+ void *thread_result = NULL;
+ uint32_t thread_index_1 = 1;
+ uint32_t thread_index_2 = 2;
+ uint32_t thread_index_3 = 3;
+ uint32_t thread_mask_1 = (1u << thread_index_1);
+ uint32_t thread_mask_2 = (1u << thread_index_2);
+ uint32_t thread_mask_3 = (1u << thread_index_3);
+
+ // Make a mask that will keep all threads alive
+ mask_access (eAssign, thread_mask_1 | thread_mask_2 | thread_mask_3); // And that line.
+
+ // Create 3 threads
+ g_thread_1 = std::thread(thread_func, (void*)&thread_index_1);
+ g_thread_2 = std::thread(thread_func, (void*)&thread_index_2);
+ g_thread_3 = std::thread(thread_func, (void*)&thread_index_3);
+
+ char line[64];
+ while (mask_access(eGet) != 0)
+ {
+ printf ("Enter thread index to kill or ENTER for all:\n");
+ fflush (stdout);
+ // Kill threads by index, or ENTER for all threads
+
+ if (fgets (line, sizeof(line), stdin))
+ {
+ if (line[0] == '\n' || line[0] == '\r' || line[0] == '\0')
+ {
+ printf ("Exiting all threads...\n");
+ break;
+ }
+ int32_t index = strtoul (line, NULL, 0);
+ switch (index)
+ {
+ case 1: mask_access (eClearBits, thread_mask_1); break;
+ case 2: mask_access (eClearBits, thread_mask_2); break;
+ case 3: mask_access (eClearBits, thread_mask_3); break;
+ }
+ continue;
+ }
+
+ break;
+ }
+
+ // Clear all thread bits to they all exit
+ mask_access (eClearBits, UINT32_MAX);
+
+ // Join all of our threads
+ g_thread_1.join();
+ g_thread_2.join();
+ g_thread_3.join();
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/python_api/module_section/Makefile b/packages/Python/lldbsuite/test/python_api/module_section/Makefile
new file mode 100644
index 000000000000..ee74ebae1f42
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/module_section/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../make
+
+CFLAGS_EXTRAS += -D__STDC_LIMIT_MACROS
+ENABLE_THREADS := YES
+CXX_SOURCES := main.cpp b.cpp c.cpp
+MAKE_DSYM :=NO
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/module_section/TestModuleAndSection.py b/packages/Python/lldbsuite/test/python_api/module_section/TestModuleAndSection.py
new file mode 100644
index 000000000000..bc97d432406f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/module_section/TestModuleAndSection.py
@@ -0,0 +1,127 @@
+"""
+Test some SBModule and SBSection APIs.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+from lldbsuite.test.lldbtest import *
+from lldbsuite.test.lldbutil import symbol_type_to_str
+
+class ModuleAndSectionAPIsTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @add_test_categories(['pyapi'])
+ def test_module_and_section(self):
+ """Test module and section APIs."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+ self.assertTrue(target.GetNumModules() > 0)
+
+ # Hide stdout if not running with '-t' option.
+ if not self.TraceOn():
+ self.HideStdout()
+
+ print("Number of modules for the target: %d" % target.GetNumModules())
+ for module in target.module_iter():
+ print(module)
+
+ # Get the executable module at index 0.
+ exe_module = target.GetModuleAtIndex(0)
+
+ print("Exe module: %s" % str(exe_module))
+ print("Number of sections: %d" % exe_module.GetNumSections())
+ INDENT = ' ' * 4
+ INDENT2 = INDENT * 2
+ for sec in exe_module.section_iter():
+ print(sec)
+ print(INDENT + "Number of subsections: %d" % sec.GetNumSubSections())
+ if sec.GetNumSubSections() == 0:
+ for sym in exe_module.symbol_in_section_iter(sec):
+ print(INDENT + str(sym))
+ print(INDENT + "symbol type: %s" % symbol_type_to_str(sym.GetType()))
+ else:
+ for subsec in sec:
+ print(INDENT + str(subsec))
+ # Now print the symbols belonging to the subsection....
+ for sym in exe_module.symbol_in_section_iter(subsec):
+ print(INDENT2 + str(sym))
+ print(INDENT2 + "symbol type: %s" % symbol_type_to_str(sym.GetType()))
+
+ @add_test_categories(['pyapi'])
+ def test_module_and_section_boundary_condition(self):
+ """Test module and section APIs by passing None when it expects a Python string."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+ self.assertTrue(target.GetNumModules() > 0)
+
+ # Hide stdout if not running with '-t' option.
+ if not self.TraceOn():
+ self.HideStdout()
+
+ print("Number of modules for the target: %d" % target.GetNumModules())
+ for module in target.module_iter():
+ print(module)
+
+ # Get the executable module at index 0.
+ exe_module = target.GetModuleAtIndex(0)
+
+ print("Exe module: %s" % str(exe_module))
+ print("Number of sections: %d" % exe_module.GetNumSections())
+
+ # Boundary condition testings. Should not crash lldb!
+ exe_module.FindFirstType(None)
+ exe_module.FindTypes(None)
+ exe_module.FindGlobalVariables(target, None, 1)
+ exe_module.FindFunctions(None, 0)
+ exe_module.FindSection(None)
+
+ # Get the section at index 1.
+ if exe_module.GetNumSections() > 1:
+ sec1 = exe_module.GetSectionAtIndex(1)
+ print(sec1)
+ else:
+ sec1 = None
+
+ if sec1:
+ sec1.FindSubSection(None)
+
+ @add_test_categories(['pyapi'])
+ def test_module_compile_unit_iter(self):
+ """Test module's compile unit iterator APIs."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+ self.assertTrue(target.GetNumModules() > 0)
+
+ # Hide stdout if not running with '-t' option.
+ if not self.TraceOn():
+ self.HideStdout()
+
+ print("Number of modules for the target: %d" % target.GetNumModules())
+ for module in target.module_iter():
+ print(module)
+
+ # Get the executable module at index 0.
+ exe_module = target.GetModuleAtIndex(0)
+
+ print("Exe module: %s" % str(exe_module))
+ print("Number of compile units: %d" % exe_module.GetNumCompileUnits())
+ INDENT = ' ' * 4
+ INDENT2 = INDENT * 2
+ for cu in exe_module.compile_unit_iter():
+ print(cu)
+
diff --git a/packages/Python/lldbsuite/test/python_api/module_section/b.cpp b/packages/Python/lldbsuite/test/python_api/module_section/b.cpp
new file mode 100644
index 000000000000..4e3e54138e5b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/module_section/b.cpp
@@ -0,0 +1,3 @@
+int b_function(int input) {
+ return input * 2;
+}
diff --git a/packages/Python/lldbsuite/test/python_api/module_section/c.cpp b/packages/Python/lldbsuite/test/python_api/module_section/c.cpp
new file mode 100644
index 000000000000..3c87bfe30c6c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/module_section/c.cpp
@@ -0,0 +1,3 @@
+int c_function(int input) {
+ return input * 3;
+}
diff --git a/packages/Python/lldbsuite/test/python_api/module_section/main.cpp b/packages/Python/lldbsuite/test/python_api/module_section/main.cpp
new file mode 100644
index 000000000000..6b87c3d649e6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/module_section/main.cpp
@@ -0,0 +1,136 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+// C includes
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+// C++ includes
+#include <chrono>
+#include <mutex>
+#include <random>
+#include <thread>
+
+std::thread g_thread_1;
+std::thread g_thread_2;
+std::thread g_thread_3;
+std::mutex g_mask_mutex;
+
+typedef enum {
+ eGet,
+ eAssign,
+ eClearBits
+} MaskAction;
+
+uint32_t mask_access (MaskAction action, uint32_t mask = 0);
+
+uint32_t
+mask_access (MaskAction action, uint32_t mask)
+{
+ static uint32_t g_mask = 0;
+
+ std::lock_guard<std::mutex> lock(g_mask_mutex);
+ switch (action)
+ {
+ case eGet:
+ break;
+
+ case eAssign:
+ g_mask |= mask;
+ break;
+
+ case eClearBits:
+ g_mask &= ~mask;
+ break;
+ }
+ return g_mask;
+}
+
+void *
+thread_func (void *arg)
+{
+ uint32_t thread_index = *((uint32_t *)arg);
+ uint32_t thread_mask = (1u << (thread_index));
+ printf ("%s (thread index = %u) startng...\n", __FUNCTION__, thread_index);
+
+ std::default_random_engine generator;
+ std::uniform_int_distribution<int> distribution(0, 3000000);
+
+ while (mask_access(eGet) & thread_mask)
+ {
+ // random micro second sleep from zero to 3 seconds
+ int usec = distribution(generator);
+
+ printf ("%s (thread = %u) doing a usleep (%d)...\n", __FUNCTION__, thread_index, usec);
+ std::chrono::microseconds duration(usec);
+ std::this_thread::sleep_for(duration);
+ printf ("%s (thread = %u) after usleep ...\n", __FUNCTION__, thread_index); // Set break point at this line.
+ }
+ printf ("%s (thread index = %u) exiting...\n", __FUNCTION__, thread_index);
+ return NULL;
+}
+
+
+int main (int argc, char const *argv[])
+{
+ int err;
+ void *thread_result = NULL;
+ uint32_t thread_index_1 = 1;
+ uint32_t thread_index_2 = 2;
+ uint32_t thread_index_3 = 3;
+ uint32_t thread_mask_1 = (1u << thread_index_1);
+ uint32_t thread_mask_2 = (1u << thread_index_2);
+ uint32_t thread_mask_3 = (1u << thread_index_3);
+
+ // Make a mask that will keep all threads alive
+ mask_access (eAssign, thread_mask_1 | thread_mask_2 | thread_mask_3); // And that line.
+
+ // Create 3 threads
+ g_thread_1 = std::thread(thread_func, (void*)&thread_index_1);
+ g_thread_2 = std::thread(thread_func, (void*)&thread_index_2);
+ g_thread_3 = std::thread(thread_func, (void*)&thread_index_3);
+
+ char line[64];
+ while (mask_access(eGet) != 0)
+ {
+ printf ("Enter thread index to kill or ENTER for all:\n");
+ fflush (stdout);
+ // Kill threads by index, or ENTER for all threads
+
+ if (fgets (line, sizeof(line), stdin))
+ {
+ if (line[0] == '\n' || line[0] == '\r' || line[0] == '\0')
+ {
+ printf ("Exiting all threads...\n");
+ break;
+ }
+ int32_t index = strtoul (line, NULL, 0);
+ switch (index)
+ {
+ case 1: mask_access (eClearBits, thread_mask_1); break;
+ case 2: mask_access (eClearBits, thread_mask_2); break;
+ case 3: mask_access (eClearBits, thread_mask_3); break;
+ }
+ continue;
+ }
+
+ break;
+ }
+
+ // Clear all thread bits to they all exit
+ mask_access (eClearBits, UINT32_MAX);
+
+ // Join all of our threads
+ g_thread_1.join();
+ g_thread_2.join();
+ g_thread_3.join();
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/python_api/objc_type/Makefile b/packages/Python/lldbsuite/test/python_api/objc_type/Makefile
new file mode 100644
index 000000000000..31e57fe28a58
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/objc_type/Makefile
@@ -0,0 +1,9 @@
+LEVEL = ../../make
+
+OBJC_SOURCES := main.m
+
+CFLAGS_EXTRAS += -w
+
+include $(LEVEL)/Makefile.rules
+
+LDFLAGS += -framework Foundation
diff --git a/packages/Python/lldbsuite/test/python_api/objc_type/TestObjCType.py b/packages/Python/lldbsuite/test/python_api/objc_type/TestObjCType.py
new file mode 100644
index 000000000000..e9b29b90e1a6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/objc_type/TestObjCType.py
@@ -0,0 +1,64 @@
+"""
+Test SBType for ObjC classes.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ObjCSBTypeTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ self.line = line_number("main.m", '// Break at this line')
+
+ @skipUnlessDarwin
+ @add_test_categories(['pyapi'])
+ def test(self):
+ """Test SBType for ObjC classes."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Create the breakpoint inside function 'main'.
+ breakpoint = target.BreakpointCreateByLocation("main.m", self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+
+
+ # Get Frame #0.
+ self.assertTrue(process.GetState() == lldb.eStateStopped)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
+
+ aBar = self.frame().FindVariable("aBar")
+ aBarType = aBar.GetType()
+ self.assertTrue(aBarType.IsValid(), "Bar should be a valid data type")
+ self.assertTrue(aBarType.GetName() == "Bar *", "Bar has the right name")
+
+ self.assertTrue(aBarType.GetNumberOfDirectBaseClasses() == 1, "Bar has a superclass")
+ aFooType = aBarType.GetDirectBaseClassAtIndex(0)
+
+ self.assertTrue(aFooType.IsValid(), "Foo should be a valid data type")
+ self.assertTrue(aFooType.GetName() == "Foo", "Foo has the right name")
+
+ self.assertTrue(aBarType.GetNumberOfFields() == 1, "Bar has a field")
+ aBarField = aBarType.GetFieldAtIndex(0)
+
+ self.assertTrue(aBarField.GetName() == "_iVar", "The field has the right name")
diff --git a/packages/Python/lldbsuite/test/python_api/objc_type/main.m b/packages/Python/lldbsuite/test/python_api/objc_type/main.m
new file mode 100644
index 000000000000..6ae54ade09ac
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/objc_type/main.m
@@ -0,0 +1,52 @@
+//===-- main.m ------------------------------------------------*- ObjC -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#import <Foundation/Foundation.h>
+
+@interface Foo: NSObject
+{}
+- (id) init;
+@end
+
+@interface Bar: Foo
+{
+ int _iVar;
+}
+- (id) init;
+@end
+
+@implementation Foo
+
+- (id) init
+{
+ self = [super init];
+ return self;
+}
+
+@end
+
+@implementation Bar
+
+- (id) init
+{
+ self = [super init];
+ if (self)
+ self->_iVar = 5;
+ return self;
+}
+
+@end
+
+int main()
+{
+ Bar* aBar = [Bar new];
+ id nothing = [aBar noSuchSelector]; // Break at this line
+ return 0;
+}
+
diff --git a/packages/Python/lldbsuite/test/python_api/process/Makefile b/packages/Python/lldbsuite/test/python_api/process/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/process/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/process/TestProcessAPI.py b/packages/Python/lldbsuite/test/python_api/process/TestProcessAPI.py
new file mode 100644
index 000000000000..f312bc8a9247
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/process/TestProcessAPI.py
@@ -0,0 +1,289 @@
+"""
+Test SBProcess APIs, including ReadMemory(), WriteMemory(), and others.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbutil import get_stopped_thread, state_type_to_str
+from lldbsuite.test.lldbtest import *
+
+class ProcessAPITestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number("main.cpp", "// Set break point at this line and check variable 'my_char'.")
+
+ @add_test_categories(['pyapi'])
+ def test_read_memory(self):
+ """Test Python SBProcess.ReadMemory() API."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint")
+ frame = thread.GetFrameAtIndex(0)
+
+ # Get the SBValue for the global variable 'my_char'.
+ val = frame.FindValue("my_char", lldb.eValueTypeVariableGlobal)
+ self.DebugSBValue(val)
+
+ # Due to the typemap magic (see lldb.swig), we pass in 1 to ReadMemory and
+ # expect to get a Python string as the result object!
+ error = lldb.SBError()
+ self.assertFalse(val.TypeIsPointerType())
+ content = process.ReadMemory(val.AddressOf().GetValueAsUnsigned(), 1, error)
+ if not error.Success():
+ self.fail("SBProcess.ReadMemory() failed")
+ if self.TraceOn():
+ print("memory content:", content)
+
+ self.expect(content, "Result from SBProcess.ReadMemory() matches our expected output: 'x'",
+ exe=False,
+ startstr = 'x')
+
+ # Read (char *)my_char_ptr.
+ val = frame.FindValue("my_char_ptr", lldb.eValueTypeVariableGlobal)
+ self.DebugSBValue(val)
+ cstring = process.ReadCStringFromMemory(val.GetValueAsUnsigned(), 256, error)
+ if not error.Success():
+ self.fail("SBProcess.ReadCStringFromMemory() failed")
+ if self.TraceOn():
+ print("cstring read is:", cstring)
+
+ self.expect(cstring, "Result from SBProcess.ReadCStringFromMemory() matches our expected output",
+ exe=False,
+ startstr = 'Does it work?')
+
+ # Get the SBValue for the global variable 'my_cstring'.
+ val = frame.FindValue("my_cstring", lldb.eValueTypeVariableGlobal)
+ self.DebugSBValue(val)
+
+ # Due to the typemap magic (see lldb.swig), we pass in 256 to read at most 256 bytes
+ # from the address, and expect to get a Python string as the result object!
+ self.assertFalse(val.TypeIsPointerType())
+ cstring = process.ReadCStringFromMemory(val.AddressOf().GetValueAsUnsigned(), 256, error)
+ if not error.Success():
+ self.fail("SBProcess.ReadCStringFromMemory() failed")
+ if self.TraceOn():
+ print("cstring read is:", cstring)
+
+ self.expect(cstring, "Result from SBProcess.ReadCStringFromMemory() matches our expected output",
+ exe=False,
+ startstr = 'lldb.SBProcess.ReadCStringFromMemory() works!')
+
+ # Get the SBValue for the global variable 'my_uint32'.
+ val = frame.FindValue("my_uint32", lldb.eValueTypeVariableGlobal)
+ self.DebugSBValue(val)
+
+ # Due to the typemap magic (see lldb.swig), we pass in 4 to read 4 bytes
+ # from the address, and expect to get an int as the result!
+ self.assertFalse(val.TypeIsPointerType())
+ my_uint32 = process.ReadUnsignedFromMemory(val.AddressOf().GetValueAsUnsigned(), 4, error)
+ if not error.Success():
+ self.fail("SBProcess.ReadCStringFromMemory() failed")
+ if self.TraceOn():
+ print("uint32 read is:", my_uint32)
+
+ if my_uint32 != 12345:
+ self.fail("Result from SBProcess.ReadUnsignedFromMemory() does not match our expected output")
+
+ @add_test_categories(['pyapi'])
+ def test_write_memory(self):
+ """Test Python SBProcess.WriteMemory() API."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint")
+ frame = thread.GetFrameAtIndex(0)
+
+ # Get the SBValue for the global variable 'my_char'.
+ val = frame.FindValue("my_char", lldb.eValueTypeVariableGlobal)
+ self.DebugSBValue(val)
+
+ # If the variable does not have a load address, there's no sense continuing.
+ if not val.GetLocation().startswith("0x"):
+ return
+
+ # OK, let's get the hex location of the variable.
+ location = int(val.GetLocation(), 16)
+
+ # The program logic makes the 'my_char' variable to have memory content as 'x'.
+ # But we want to use the WriteMemory() API to assign 'a' to the variable.
+
+ # Now use WriteMemory() API to write 'a' into the global variable.
+ error = lldb.SBError()
+ result = process.WriteMemory(location, 'a', error)
+ if not error.Success() or result != 1:
+ self.fail("SBProcess.WriteMemory() failed")
+
+ # Read from the memory location. This time it should be 'a'.
+ # Due to the typemap magic (see lldb.swig), we pass in 1 to ReadMemory and
+ # expect to get a Python string as the result object!
+ content = process.ReadMemory(location, 1, error)
+ if not error.Success():
+ self.fail("SBProcess.ReadMemory() failed")
+ if self.TraceOn():
+ print("memory content:", content)
+
+ self.expect(content, "Result from SBProcess.ReadMemory() matches our expected output: 'a'",
+ exe=False,
+ startstr = 'a')
+
+ @add_test_categories(['pyapi'])
+ def test_access_my_int(self):
+ """Test access 'my_int' using Python SBProcess.GetByteOrder() and other APIs."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint")
+ frame = thread.GetFrameAtIndex(0)
+
+ # Get the SBValue for the global variable 'my_int'.
+ val = frame.FindValue("my_int", lldb.eValueTypeVariableGlobal)
+ self.DebugSBValue(val)
+
+ # If the variable does not have a load address, there's no sense continuing.
+ if not val.GetLocation().startswith("0x"):
+ return
+
+ # OK, let's get the hex location of the variable.
+ location = int(val.GetLocation(), 16)
+
+ # Note that the canonical from of the bytearray is little endian.
+ from lldbsuite.test.lldbutil import int_to_bytearray, bytearray_to_int
+
+ byteSize = val.GetByteSize()
+ bytes = int_to_bytearray(256, byteSize)
+
+ byteOrder = process.GetByteOrder()
+ if byteOrder == lldb.eByteOrderBig:
+ bytes.reverse()
+ elif byteOrder == lldb.eByteOrderLittle:
+ pass
+ else:
+ # Neither big endian nor little endian? Return for now.
+ # Add more logic here if we want to handle other types.
+ return
+
+ # The program logic makes the 'my_int' variable to have int type and value of 0.
+ # But we want to use the WriteMemory() API to assign 256 to the variable.
+
+ # Now use WriteMemory() API to write 256 into the global variable.
+ new_value = str(bytes)
+ error = lldb.SBError()
+ result = process.WriteMemory(location, new_value, error)
+ if not error.Success() or result != byteSize:
+ self.fail("SBProcess.WriteMemory() failed")
+
+ # Make sure that the val we got originally updates itself to notice the change:
+ self.expect(val.GetValue(),
+ "SBProcess.ReadMemory() successfully writes (int)256 to the memory location for 'my_int'",
+ exe=False,
+ startstr = '256')
+
+ # And for grins, get the SBValue for the global variable 'my_int' again, to make sure that also tracks the new value:
+ val = frame.FindValue("my_int", lldb.eValueTypeVariableGlobal)
+ self.expect(val.GetValue(),
+ "SBProcess.ReadMemory() successfully writes (int)256 to the memory location for 'my_int'",
+ exe=False,
+ startstr = '256')
+
+ # Now read the memory content. The bytearray should have (byte)1 as the second element.
+ content = process.ReadMemory(location, byteSize, error)
+ if not error.Success():
+ self.fail("SBProcess.ReadMemory() failed")
+
+ # Use "ascii" as the encoding because each element of 'content' is in the range [0..255].
+ new_bytes = bytearray(content, "ascii")
+
+ # The bytearray_to_int utility function expects a little endian bytearray.
+ if byteOrder == lldb.eByteOrderBig:
+ new_bytes.reverse()
+
+ new_value = bytearray_to_int(new_bytes, byteSize)
+ if new_value != 256:
+ self.fail("Memory content read from 'my_int' does not match (int)256")
+
+ # Dump the memory content....
+ if self.TraceOn():
+ for i in new_bytes:
+ print("byte:", i)
+
+ @add_test_categories(['pyapi'])
+ def test_remote_launch(self):
+ """Test SBProcess.RemoteLaunch() API with a process not in eStateConnected, and it should fail."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ if self.TraceOn():
+ print("process state:", state_type_to_str(process.GetState()))
+ self.assertTrue(process.GetState() != lldb.eStateConnected)
+
+ error = lldb.SBError()
+ success = process.RemoteLaunch(None, None, None, None, None, None, 0, False, error)
+ self.assertTrue(not success, "RemoteLaunch() should fail for process state != eStateConnected")
+
+ @add_test_categories(['pyapi'])
+ def test_get_num_supported_hardware_watchpoints(self):
+ """Test SBProcess.GetNumSupportedHardwareWatchpoints() API with a process."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByLocation("main.cpp", self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ error = lldb.SBError();
+ num = process.GetNumSupportedHardwareWatchpoints(error)
+ if self.TraceOn() and error.Success():
+ print("Number of supported hardware watchpoints: %d" % num)
+
diff --git a/packages/Python/lldbsuite/test/python_api/process/io/Makefile b/packages/Python/lldbsuite/test/python_api/process/io/Makefile
new file mode 100644
index 000000000000..5361f2a5bbea
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/process/io/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+EXE := process_io
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/process/io/TestProcessIO.py b/packages/Python/lldbsuite/test/python_api/process/io/TestProcessIO.py
new file mode 100644
index 000000000000..2944ee78acf1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/process/io/TestProcessIO.py
@@ -0,0 +1,206 @@
+"""Test Python APIs for process IO."""
+
+from __future__ import print_function
+
+
+
+import os, sys, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class ProcessIOTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Get the full path to our executable to be debugged.
+ self.exe = os.path.join(os.getcwd(), "process_io")
+ self.local_input_file = os.path.join(os.getcwd(), "input.txt")
+ self.local_output_file = os.path.join(os.getcwd(), "output.txt")
+ self.local_error_file = os.path.join(os.getcwd(), "error.txt")
+
+ self.input_file = os.path.join(self.get_process_working_directory(), "input.txt")
+ self.output_file = os.path.join(self.get_process_working_directory(), "output.txt")
+ self.error_file = os.path.join(self.get_process_working_directory(), "error.txt")
+ self.lines = ["Line 1", "Line 2", "Line 3"]
+
+ @skipIfWindows # stdio manipulation unsupported on Windows
+ @add_test_categories(['pyapi'])
+ def test_stdin_by_api(self):
+ """Exercise SBProcess.PutSTDIN()."""
+ self.build()
+ self.create_target()
+ self.run_process(True)
+ output = self.process.GetSTDOUT(1000)
+ self.check_process_output(output, output)
+
+ @skipIfWindows # stdio manipulation unsupported on Windows
+ @add_test_categories(['pyapi'])
+ def test_stdin_redirection(self):
+ """Exercise SBLaunchInfo::AddOpenFileAction() for STDIN without specifying STDOUT or STDERR."""
+ self.build()
+ self.create_target()
+ self.redirect_stdin()
+ self.run_process(False)
+ output = self.process.GetSTDOUT(1000)
+ self.check_process_output(output, output)
+
+ @skipIfWindows # stdio manipulation unsupported on Windows
+ @add_test_categories(['pyapi'])
+ def test_stdout_redirection(self):
+ """Exercise SBLaunchInfo::AddOpenFileAction() for STDOUT without specifying STDIN or STDERR."""
+ self.build()
+ self.create_target()
+ self.redirect_stdout()
+ self.run_process(True)
+ output = self.read_output_file_and_delete()
+ error = self.process.GetSTDOUT(1000)
+ self.check_process_output(output, error)
+
+ @skipIfWindows # stdio manipulation unsupported on Windows
+ @add_test_categories(['pyapi'])
+ def test_stderr_redirection(self):
+ """Exercise SBLaunchInfo::AddOpenFileAction() for STDERR without specifying STDIN or STDOUT."""
+ self.build()
+ self.create_target()
+ self.redirect_stderr()
+ self.run_process(True)
+ output = self.process.GetSTDOUT(1000)
+ error = self.read_error_file_and_delete()
+ self.check_process_output(output, error)
+
+ @skipIfWindows # stdio manipulation unsupported on Windows
+ @add_test_categories(['pyapi'])
+ def test_stdout_stderr_redirection(self):
+ """Exercise SBLaunchInfo::AddOpenFileAction() for STDOUT and STDERR without redirecting STDIN."""
+ self.build()
+ self.create_target()
+ self.redirect_stdout()
+ self.redirect_stderr()
+ self.run_process(True)
+ output = self.read_output_file_and_delete()
+ error = self.read_error_file_and_delete()
+ self.check_process_output(output, error)
+
+ # target_file - path on local file system or remote file system if running remote
+ # local_file - path on local system
+ def read_file_and_delete(self, target_file, local_file):
+ if lldb.remote_platform:
+ self.runCmd('platform get-file "{remote}" "{local}"'.format(
+ remote=target_file, local=local_file))
+
+ self.assertTrue(os.path.exists(local_file), 'Make sure "{local}" file exists'.format(local=local_file))
+ f = open(local_file, 'r')
+ contents = f.read()
+ f.close()
+
+ #TODO: add 'platform delete-file' file command
+ #if lldb.remote_platform:
+ # self.runCmd('platform delete-file "{remote}"'.format(remote=target_file))
+ os.unlink(local_file)
+ return contents
+
+ def read_output_file_and_delete(self):
+ return self.read_file_and_delete(self.output_file, self.local_output_file)
+
+ def read_error_file_and_delete(self):
+ return self.read_file_and_delete(self.error_file, self.local_error_file)
+
+ def create_target(self):
+ '''Create the target and launch info that will be used by all tests'''
+ self.target = self.dbg.CreateTarget(self.exe)
+ self.launch_info = lldb.SBLaunchInfo([self.exe])
+ self.launch_info.SetWorkingDirectory(self.get_process_working_directory())
+
+ def redirect_stdin(self):
+ '''Redirect STDIN (file descriptor 0) to use our input.txt file
+
+ Make the input.txt file to use when redirecting STDIN, setup a cleanup action
+ to delete the input.txt at the end of the test in case exceptions are thrown,
+ and redirect STDIN in the launch info.'''
+ f = open(self.local_input_file, 'w')
+ for line in self.lines:
+ f.write(line + "\n")
+ f.close()
+
+ if lldb.remote_platform:
+ self.runCmd('platform put-file "{local}" "{remote}"'.format(
+ local=self.local_input_file, remote=self.input_file))
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ os.unlink(self.local_input_file)
+ #TODO: add 'platform delete-file' file command
+ #if lldb.remote_platform:
+ # self.runCmd('platform delete-file "{remote}"'.format(remote=self.input_file))
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+ self.launch_info.AddOpenFileAction(0, self.input_file, True, False);
+
+ def redirect_stdout(self):
+ '''Redirect STDOUT (file descriptor 1) to use our output.txt file'''
+ self.launch_info.AddOpenFileAction(1, self.output_file, False, True);
+
+ def redirect_stderr(self):
+ '''Redirect STDERR (file descriptor 2) to use our error.txt file'''
+ self.launch_info.AddOpenFileAction(2, self.error_file, False, True);
+
+ def run_process(self, put_stdin):
+ '''Run the process to completion and optionally put lines to STDIN via the API if "put_stdin" is True'''
+ # Set the breakpoints
+ self.breakpoint = self.target.BreakpointCreateBySourceRegex('Set breakpoint here', lldb.SBFileSpec("main.c"))
+ self.assertTrue(self.breakpoint.GetNumLocations() > 0, VALID_BREAKPOINT)
+
+ # Launch the process, and do not stop at the entry point.
+ error = lldb.SBError()
+ # This should launch the process and it should exit by the time we get back
+ # because we have synchronous mode enabled
+ self.process = self.target.Launch (self.launch_info, error)
+
+ self.assertTrue(error.Success(), "Make sure process launched successfully")
+ self.assertTrue(self.process, PROCESS_IS_VALID)
+
+ if self.TraceOn():
+ print("process launched.")
+
+ # Frame #0 should be at our breakpoint.
+ threads = lldbutil.get_threads_stopped_at_breakpoint (self.process, self.breakpoint)
+
+ self.assertTrue(len(threads) == 1)
+ self.thread = threads[0]
+ self.frame = self.thread.frames[0]
+ self.assertTrue(self.frame, "Frame 0 is valid.")
+
+ if self.TraceOn():
+ print("process stopped at breakpoint, sending STDIN via LLDB API.")
+
+ # Write data to stdin via the public API if we were asked to
+ if put_stdin:
+ for line in self.lines:
+ self.process.PutSTDIN(line + "\n")
+
+ # Let process continue so it will exit
+ self.process.Continue()
+ state = self.process.GetState()
+ self.assertTrue(state == lldb.eStateExited, PROCESS_IS_VALID)
+
+ def check_process_output (self, output, error):
+ # Since we launched the process without specifying stdin/out/err,
+ # a pseudo terminal is used for stdout/err, and we are satisfied
+ # once "input line=>1" appears in stdout.
+ # See also main.c.
+ if self.TraceOn():
+ print("output = '%s'" % output)
+ print("error = '%s'" % error)
+
+ for line in self.lines:
+ check_line = 'input line to stdout: %s' % (line)
+ self.assertTrue(check_line in output, "verify stdout line shows up in STDOUT")
+ for line in self.lines:
+ check_line = 'input line to stderr: %s' % (line)
+ self.assertTrue(check_line in error, "verify stderr line shows up in STDERR")
diff --git a/packages/Python/lldbsuite/test/python_api/process/io/main.c b/packages/Python/lldbsuite/test/python_api/process/io/main.c
new file mode 100644
index 000000000000..c9a5707f0e17
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/process/io/main.c
@@ -0,0 +1,19 @@
+#include <stdio.h>
+
+int main(int argc, char const *argv[]) {
+ printf("Hello world.\n"); // Set breakpoint here
+ char line[100];
+ if (fgets(line, sizeof(line), stdin)) {
+ fprintf(stdout, "input line to stdout: %s", line);
+ fprintf(stderr, "input line to stderr: %s", line);
+ }
+ if (fgets(line, sizeof(line), stdin)) {
+ fprintf(stdout, "input line to stdout: %s", line);
+ fprintf(stderr, "input line to stderr: %s", line);
+ }
+ if (fgets(line, sizeof(line), stdin)) {
+ fprintf(stdout, "input line to stdout: %s", line);
+ fprintf(stderr, "input line to stderr: %s", line);
+ }
+ printf("Exiting now\n");
+}
diff --git a/packages/Python/lldbsuite/test/python_api/process/main.cpp b/packages/Python/lldbsuite/test/python_api/process/main.cpp
new file mode 100644
index 000000000000..9610936e0534
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/process/main.cpp
@@ -0,0 +1,31 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+#include <stdint.h>
+
+// This simple program is to test the lldb Python API related to process.
+
+char my_char = 'u';
+char my_cstring[] = "lldb.SBProcess.ReadCStringFromMemory() works!";
+char *my_char_ptr = (char *)"Does it work?";
+uint32_t my_uint32 = 12345;
+int my_int = 0;
+
+int main (int argc, char const *argv[])
+{
+ for (int i = 0; i < 3; ++i) {
+ printf("my_char='%c'\n", my_char);
+ ++my_char;
+ }
+
+ printf("after the loop: my_char='%c'\n", my_char); // 'my_char' should print out as 'x'.
+
+ return 0; // Set break point at this line and check variable 'my_char'.
+ // Use lldb Python API to set memory content for my_int and check the result.
+}
diff --git a/packages/Python/lldbsuite/test/python_api/rdar-12481949/Makefile b/packages/Python/lldbsuite/test/python_api/rdar-12481949/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/rdar-12481949/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/rdar-12481949/Test-rdar-12481949.py b/packages/Python/lldbsuite/test/python_api/rdar-12481949/Test-rdar-12481949.py
new file mode 100644
index 000000000000..f56fd96e4665
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/rdar-12481949/Test-rdar-12481949.py
@@ -0,0 +1,54 @@
+"""
+Check that SBValue.GetValueAsSigned() does the right thing for a 32-bit -1.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class Radar12481949DataFormatterTestCase(TestBase):
+
+ # test for rdar://problem/12481949
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Set break point at this line.')
+
+ def test_with_run_command(self):
+ """Check that SBValue.GetValueAsSigned() does the right thing for a 32-bit -1."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format delete hex', check=False)
+ self.runCmd('type summary clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.assertTrue(self.frame().FindVariable("myvar").GetValueAsSigned() == -1, "GetValueAsSigned() says -1")
+ self.assertTrue(self.frame().FindVariable("myvar").GetValueAsSigned() != 0xFFFFFFFF, "GetValueAsSigned() does not say 0xFFFFFFFF")
+ self.assertTrue(self.frame().FindVariable("myvar").GetValueAsSigned() != 0xFFFFFFFFFFFFFFFF, "GetValueAsSigned() does not say 0xFFFFFFFFFFFFFFFF")
+
+ self.assertTrue(self.frame().FindVariable("myvar").GetValueAsUnsigned() != -1, "GetValueAsUnsigned() does not say -1")
+ self.assertTrue(self.frame().FindVariable("myvar").GetValueAsUnsigned() == 0xFFFFFFFF, "GetValueAsUnsigned() says 0xFFFFFFFF")
+ self.assertTrue(self.frame().FindVariable("myvar").GetValueAsUnsigned() != 0xFFFFFFFFFFFFFFFF, "GetValueAsUnsigned() does not says 0xFFFFFFFFFFFFFFFF")
diff --git a/packages/Python/lldbsuite/test/python_api/rdar-12481949/main.cpp b/packages/Python/lldbsuite/test/python_api/rdar-12481949/main.cpp
new file mode 100644
index 000000000000..e8ebf36f6190
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/rdar-12481949/main.cpp
@@ -0,0 +1,17 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+#include <stdint.h>
+int main ()
+{
+ int32_t myvar = -1;
+ printf ("%d\n", myvar); // Set break point at this line.
+ return myvar+1;
+}
diff --git a/packages/Python/lldbsuite/test/python_api/sbdata/Makefile b/packages/Python/lldbsuite/test/python_api/sbdata/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/sbdata/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/sbdata/TestSBData.py b/packages/Python/lldbsuite/test/python_api/sbdata/TestSBData.py
new file mode 100644
index 000000000000..2ff516e10d8e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/sbdata/TestSBData.py
@@ -0,0 +1,348 @@
+"""Test the SBData APIs."""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+from math import fabs
+import lldbsuite.test.lldbutil as lldbutil
+
+class SBDataAPICase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break on inside main.cpp.
+ self.line = line_number('main.cpp', '// set breakpoint here')
+
+ @add_test_categories(['pyapi'])
+ def test_with_run_command(self):
+ """Test the SBData APIs."""
+ self.build()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ target = self.dbg.GetSelectedTarget()
+
+ process = target.GetProcess()
+
+ thread = process.GetThreadAtIndex(0)
+
+ frame = thread.GetSelectedFrame()
+ if self.TraceOn():
+ print(frame)
+ foobar = frame.FindVariable('foobar')
+ self.assertTrue(foobar.IsValid())
+ if self.TraceOn():
+ print(foobar)
+
+ data = foobar.GetPointeeData(0, 2)
+
+ if self.TraceOn():
+ print(data)
+
+ offset = 0
+ error = lldb.SBError()
+
+ self.assert_data(data.GetUnsignedInt32, offset, 1)
+ offset += 4
+ low = data.GetSignedInt16(error, offset)
+ self.assertTrue(error.Success())
+ offset += 2
+ high = data.GetSignedInt16(error, offset)
+ self.assertTrue(error.Success())
+ offset += 2
+ self.assertTrue ((low == 9 and high == 0) or (low == 0 and high == 9), 'foo[0].b == 9')
+ self.assertTrue( fabs(data.GetFloat(error, offset) - 3.14) < 1, 'foo[0].c == 3.14')
+ self.assertTrue(error.Success())
+ offset += 4
+ self.assert_data(data.GetUnsignedInt32, offset, 8)
+ offset += 4
+ self.assert_data(data.GetUnsignedInt32, offset, 5)
+ offset += 4
+
+ self.runCmd("n")
+
+ offset = 16
+
+ self.assert_data(data.GetUnsignedInt32, offset, 5)
+
+ data = foobar.GetPointeeData(1, 1)
+
+ offset = 0
+
+ self.assert_data(data.GetSignedInt32, offset, 8)
+ offset += 4
+ self.assert_data(data.GetSignedInt32, offset, 7)
+ offset += 8
+ self.assertTrue(data.GetUnsignedInt32(error, offset) == 0, 'do not read beyond end')
+ self.assertTrue(not error.Success())
+ error.Clear() # clear the error for the next test
+
+ star_foobar = foobar.Dereference()
+ self.assertTrue(star_foobar.IsValid())
+
+ data = star_foobar.GetData()
+
+ if self.TraceOn():
+ print(data)
+
+ offset = 0
+ self.assert_data(data.GetUnsignedInt32, offset, 1)
+ offset += 4
+ self.assert_data(data.GetUnsignedInt32, offset, 9)
+
+ foobar_addr = star_foobar.GetLoadAddress()
+ foobar_addr += 12
+
+ # http://llvm.org/bugs/show_bug.cgi?id=11579
+ # lldb::SBValue::CreateValueFromAddress does not verify SBType::GetPointerType succeeds
+ # This should not crash LLDB.
+ nothing = foobar.CreateValueFromAddress("nothing", foobar_addr, star_foobar.GetType().GetBasicType(lldb.eBasicTypeInvalid))
+
+ new_foobar = foobar.CreateValueFromAddress("f00", foobar_addr, star_foobar.GetType())
+ self.assertTrue(new_foobar.IsValid())
+ if self.TraceOn():
+ print(new_foobar)
+
+ data = new_foobar.GetData()
+
+ if self.TraceOn():
+ print(data)
+
+ self.assertTrue(data.uint32[0] == 8, 'then foo[1].a == 8')
+ self.assertTrue(data.uint32[1] == 7, 'then foo[1].b == 7')
+ self.assertTrue(fabs(data.float[2] - 3.14) < 1, 'foo[1].c == 3.14') # exploiting that sizeof(uint32) == sizeof(float)
+
+ self.runCmd("n")
+
+ offset = 0
+ self.assert_data(data.GetUnsignedInt32, offset, 8)
+ offset += 4
+ self.assert_data(data.GetUnsignedInt32, offset, 7)
+ offset += 4
+ self.assertTrue(fabs(data.GetFloat(error, offset) - 3.14) < 1, 'foo[1].c == 3.14')
+ self.assertTrue(error.Success())
+
+ data = new_foobar.GetData()
+
+ if self.TraceOn():
+ print(data)
+
+ offset = 0
+ self.assert_data(data.GetUnsignedInt32, offset, 8)
+ offset += 4
+ self.assert_data(data.GetUnsignedInt32, offset, 7)
+ offset += 4
+ self.assertTrue(fabs(data.GetFloat(error, offset) - 6.28) < 1, 'foo[1].c == 6.28')
+ self.assertTrue(error.Success())
+
+ self.runCmd("n")
+
+ barfoo = frame.FindVariable('barfoo')
+
+ data = barfoo.GetData()
+
+ if self.TraceOn():
+ print(barfoo)
+
+ if self.TraceOn():
+ print(data)
+
+ offset = 0
+ self.assert_data(data.GetUnsignedInt32, offset, 1)
+ offset += 4
+ self.assert_data(data.GetUnsignedInt32, offset, 2)
+ offset += 4
+ self.assertTrue(fabs(data.GetFloat(error, offset) - 3) < 1, 'barfoo[0].c == 3')
+ self.assertTrue(error.Success())
+ offset += 4
+ self.assert_data(data.GetUnsignedInt32, offset, 4)
+ offset += 4
+ self.assert_data(data.GetUnsignedInt32, offset, 5)
+ offset += 4
+ self.assertTrue(fabs(data.GetFloat(error, offset) - 6) < 1, 'barfoo[1].c == 6')
+ self.assertTrue(error.Success())
+
+ new_object = barfoo.CreateValueFromData("new_object",data,barfoo.GetType().GetBasicType(lldb.eBasicTypeInt))
+
+ if self.TraceOn():
+ print(new_object)
+
+ self.assertTrue(new_object.GetValue() == "1", 'new_object == 1')
+
+ data.SetData(error, 'A\0\0\0', data.GetByteOrder(), data.GetAddressByteSize())
+ self.assertTrue(error.Success())
+
+ data2 = lldb.SBData()
+ data2.SetData(error, 'BCD', data.GetByteOrder(), data.GetAddressByteSize())
+ self.assertTrue(error.Success())
+
+ data.Append(data2)
+
+ if self.TraceOn():
+ print(data)
+
+ # this breaks on EBCDIC
+ offset = 0
+ self.assert_data(data.GetUnsignedInt32, offset, 65)
+ offset += 4
+ self.assert_data(data.GetUnsignedInt8, offset, 66)
+ offset += 1
+ self.assert_data(data.GetUnsignedInt8, offset, 67)
+ offset += 1
+ self.assert_data(data.GetUnsignedInt8, offset, 68)
+ offset += 1
+
+ # check the new API calls introduced per LLVM llvm.org/prenhancement request
+ # 11619 (Allow creating SBData values from arrays or primitives in Python)
+
+ hello_str = "hello!"
+ data2 = lldb.SBData.CreateDataFromCString(process.GetByteOrder(),process.GetAddressByteSize(),hello_str)
+ self.assertTrue(len(data2.uint8) == len(hello_str))
+ self.assertTrue(data2.uint8[0] == 104, 'h == 104')
+ self.assertTrue(data2.uint8[1] == 101, 'e == 101')
+ self.assertTrue(data2.uint8[2] == 108, 'l == 108')
+ self.assert_data(data2.GetUnsignedInt8, 3, 108) # l
+ self.assertTrue(data2.uint8[4] == 111, 'o == 111')
+ self.assert_data(data2.GetUnsignedInt8, 5, 33) # !
+
+ uint_lists = [ [1,2,3,4,5], [int(i) for i in [1, 2, 3, 4, 5]] ]
+ int_lists = [ [2, -2], [int(i) for i in [2, -2]] ]
+
+ for l in uint_lists:
+ data2 = lldb.SBData.CreateDataFromUInt64Array(process.GetByteOrder(), process.GetAddressByteSize(), l)
+ self.assert_data(data2.GetUnsignedInt64, 0, 1)
+ self.assert_data(data2.GetUnsignedInt64, 8, 2)
+ self.assert_data(data2.GetUnsignedInt64, 16, 3)
+ self.assert_data(data2.GetUnsignedInt64, 24, 4)
+ self.assert_data(data2.GetUnsignedInt64, 32, 5)
+
+ self.assertTrue(data2.uint64s == [1,2,3,4,5], 'read_data_helper failure: data2 == [1,2,3,4,5]')
+
+ for l in int_lists:
+ data2 = lldb.SBData.CreateDataFromSInt32Array(process.GetByteOrder(), process.GetAddressByteSize(), l)
+ self.assertTrue(data2.sint32[0:2] == [2,-2], 'signed32 data2 = [2,-2]')
+
+ data2.Append(lldb.SBData.CreateDataFromSInt64Array(process.GetByteOrder(), process.GetAddressByteSize(), int_lists[0]))
+ self.assert_data(data2.GetSignedInt32, 0, 2)
+ self.assert_data(data2.GetSignedInt32, 4, -2)
+ self.assertTrue(data2.sint64[1:3] == [2,-2], 'signed64 data2 = [2,-2]')
+
+ for l in int_lists:
+ data2 = lldb.SBData.CreateDataFromSInt64Array(process.GetByteOrder(), process.GetAddressByteSize(), l)
+ self.assert_data(data2.GetSignedInt64, 0, 2)
+ self.assert_data(data2.GetSignedInt64, 8, -2)
+ self.assertTrue(data2.sint64[0:2] == [2,-2], 'signed64 data2 = [2,-2]')
+
+ for l in uint_lists:
+ data2 = lldb.SBData.CreateDataFromUInt32Array(process.GetByteOrder(), process.GetAddressByteSize(), l)
+ self.assert_data(data2.GetUnsignedInt32,0, 1)
+ self.assert_data(data2.GetUnsignedInt32,4, 2)
+ self.assert_data(data2.GetUnsignedInt32,8, 3)
+ self.assert_data(data2.GetUnsignedInt32,12, 4)
+ self.assert_data(data2.GetUnsignedInt32,16, 5)
+
+ bool_list = [True, True, False, False, True, False]
+
+ data2 = lldb.SBData.CreateDataFromSInt32Array(process.GetByteOrder(), process.GetAddressByteSize(), bool_list)
+ self.assertTrue(data2.sint32[0:6] == [1, 1, 0, 0, 1, 0], 'signed32 data2 = [1, 1, 0, 0, 1, 0]')
+
+ data2 = lldb.SBData.CreateDataFromUInt32Array(process.GetByteOrder(), process.GetAddressByteSize(), bool_list)
+ self.assertTrue(data2.uint32[0:6] == [1, 1, 0, 0, 1, 0], 'unsigned32 data2 = [1, 1, 0, 0, 1, 0]')
+
+ data2 = lldb.SBData.CreateDataFromSInt64Array(process.GetByteOrder(), process.GetAddressByteSize(), bool_list)
+ self.assertTrue(data2.sint64[0:6] == [1, 1, 0, 0, 1, 0], 'signed64 data2 = [1, 1, 0, 0, 1, 0]')
+
+ data2 = lldb.SBData.CreateDataFromUInt64Array(process.GetByteOrder(), process.GetAddressByteSize(), bool_list)
+ self.assertTrue(data2.uint64[0:6] == [1, 1, 0, 0, 1, 0], 'signed64 data2 = [1, 1, 0, 0, 1, 0]')
+
+ data2 = lldb.SBData.CreateDataFromDoubleArray(process.GetByteOrder(),process.GetAddressByteSize(),[3.14,6.28,2.71])
+ self.assertTrue( fabs(data2.GetDouble(error,0) - 3.14) < 0.5, 'double data2[0] = 3.14')
+ self.assertTrue(error.Success())
+ self.assertTrue( fabs(data2.GetDouble(error,8) - 6.28) < 0.5, 'double data2[1] = 6.28')
+ self.assertTrue(error.Success())
+ self.assertTrue( fabs(data2.GetDouble(error,16) - 2.71) < 0.5, 'double data2[2] = 2.71')
+ self.assertTrue(error.Success())
+
+ data2 = lldb.SBData()
+
+ data2.SetDataFromCString(hello_str)
+ self.assertTrue(len(data2.uint8) == len(hello_str))
+ self.assert_data(data2.GetUnsignedInt8, 0, 104)
+ self.assert_data(data2.GetUnsignedInt8, 1, 101)
+ self.assert_data(data2.GetUnsignedInt8, 2, 108)
+ self.assert_data(data2.GetUnsignedInt8, 3, 108)
+ self.assert_data(data2.GetUnsignedInt8, 4, 111)
+ self.assert_data(data2.GetUnsignedInt8, 5, 33)
+
+ data2.SetDataFromUInt64Array([1,2,3,4,5])
+ self.assert_data(data2.GetUnsignedInt64, 0, 1)
+ self.assert_data(data2.GetUnsignedInt64, 8, 2)
+ self.assert_data(data2.GetUnsignedInt64, 16, 3)
+ self.assert_data(data2.GetUnsignedInt64, 24, 4)
+ self.assert_data(data2.GetUnsignedInt64, 32, 5)
+
+ self.assertTrue(data2.uint64[0] == 1, 'read_data_helper failure: set data2[0] = 1')
+ self.assertTrue(data2.uint64[1] == 2, 'read_data_helper failure: set data2[1] = 2')
+ self.assertTrue(data2.uint64[2] == 3, 'read_data_helper failure: set data2[2] = 3')
+ self.assertTrue(data2.uint64[3] == 4, 'read_data_helper failure: set data2[3] = 4')
+ self.assertTrue(data2.uint64[4] == 5, 'read_data_helper failure: set data2[4] = 5')
+
+ self.assertTrue(data2.uint64[0:2] == [1,2], 'read_data_helper failure: set data2[0:2] = [1,2]')
+
+ data2.SetDataFromSInt32Array([2, -2])
+ self.assert_data(data2.GetSignedInt32, 0, 2)
+ self.assert_data(data2.GetSignedInt32, 4, -2)
+
+ data2.SetDataFromSInt64Array([2, -2])
+ self.assert_data(data2.GetSignedInt32, 0, 2)
+ self.assert_data(data2.GetSignedInt32, 8, -2)
+
+ data2.SetDataFromUInt32Array([1,2,3,4,5])
+ self.assert_data(data2.GetUnsignedInt32, 0, 1)
+ self.assert_data(data2.GetUnsignedInt32, 4, 2)
+ self.assert_data(data2.GetUnsignedInt32, 8, 3)
+ self.assert_data(data2.GetUnsignedInt32, 12, 4)
+ self.assert_data(data2.GetUnsignedInt32, 16, 5)
+
+ self.assertTrue(data2.uint32[0] == 1, 'read_data_helper failure: set 32-bit data2[0] = 1')
+ self.assertTrue(data2.uint32[1] == 2, 'read_data_helper failure: set 32-bit data2[1] = 2')
+ self.assertTrue(data2.uint32[2] == 3, 'read_data_helper failure: set 32-bit data2[2] = 3')
+ self.assertTrue(data2.uint32[3] == 4, 'read_data_helper failure: set 32-bit data2[3] = 4')
+ self.assertTrue(data2.uint32[4] == 5, 'read_data_helper failure: set 32-bit data2[4] = 5')
+
+ data2.SetDataFromDoubleArray([3.14,6.28,2.71])
+ self.assertTrue( fabs(data2.GetDouble(error,0) - 3.14) < 0.5, 'set double data2[0] = 3.14')
+ self.assertTrue( fabs(data2.GetDouble(error,8) - 6.28) < 0.5, 'set double data2[1] = 6.28')
+ self.assertTrue( fabs(data2.GetDouble(error,16) - 2.71) < 0.5, 'set double data2[2] = 2.71')
+
+ self.assertTrue( fabs(data2.double[0] - 3.14) < 0.5, 'read_data_helper failure: set double data2[0] = 3.14')
+ self.assertTrue( fabs(data2.double[1] - 6.28) < 0.5, 'read_data_helper failure: set double data2[1] = 6.28')
+ self.assertTrue( fabs(data2.double[2] - 2.71) < 0.5, 'read_data_helper failure: set double data2[2] = 2.71')
+
+ def assert_data(self, func, arg, expected):
+ """ Asserts func(SBError error, arg) == expected. """
+ error = lldb.SBError()
+ result = func(error, arg)
+ if not error.Success():
+ stream = lldb.SBStream()
+ error.GetDescription(stream)
+ self.assertTrue(error.Success(),
+ "%s(error, %s) did not succeed: %s" % (func.__name__,
+ arg,
+ stream.GetData()))
+ self.assertTrue(expected == result, "%s(error, %s) == %s != %s" % (func.__name__, arg, result, expected))
diff --git a/packages/Python/lldbsuite/test/python_api/sbdata/main.cpp b/packages/Python/lldbsuite/test/python_api/sbdata/main.cpp
new file mode 100644
index 000000000000..6018475d83c0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/sbdata/main.cpp
@@ -0,0 +1,43 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdint.h>
+
+struct foo
+{
+ uint32_t a;
+ uint32_t b;
+ float c;
+ foo() : a(0), b(1), c(3.14) {}
+ foo(uint32_t A, uint32_t B, float C) :
+ a(A),
+ b(B),
+ c(C)
+ {}
+};
+
+int main (int argc, char const *argv[])
+{
+ foo* foobar = new foo[2];
+
+ foobar[0].a = 1;
+ foobar[0].b = 9;
+
+ foobar[1].a = 8;
+ foobar[1].b = 5;
+
+ foobar[1].b = 7; // set breakpoint here
+
+ foobar[1].c = 6.28;
+
+ foo barfoo[] = {foo(1,2,3), foo(4,5,6)};
+
+ delete[] foobar;
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/python_api/sbtype_typeclass/TestSBTypeTypeClass.py b/packages/Python/lldbsuite/test/python_api/sbtype_typeclass/TestSBTypeTypeClass.py
new file mode 100644
index 000000000000..80305e303d03
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/sbtype_typeclass/TestSBTypeTypeClass.py
@@ -0,0 +1,4 @@
+import lldbsuite.test.lldbinline as lldbinline
+import lldbsuite.test.lldbtest as lldbtest
+
+lldbinline.MakeInlineTest(__file__, globals(), [lldbtest.skipIfFreeBSD,lldbtest.skipIfLinux,lldbtest.skipIfWindows])
diff --git a/packages/Python/lldbsuite/test/python_api/sbtype_typeclass/main.m b/packages/Python/lldbsuite/test/python_api/sbtype_typeclass/main.m
new file mode 100644
index 000000000000..599d36107f41
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/sbtype_typeclass/main.m
@@ -0,0 +1,34 @@
+//===-- main.m --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#import <Cocoa/Cocoa.h>
+
+@interface ThisClassTestsThings : NSObject
+@end
+
+@implementation ThisClassTestsThings
+- (int)doSomething {
+
+ id s = self;
+ NSLog(@"%@",s); //% s = self.frame().FindVariable("s"); s.SetPreferDynamicValue(lldb.eDynamicCanRunTarget)
+ //% s_type = s.GetType()
+ //% typeClass = s_type.GetTypeClass()
+ //% condition = (typeClass == lldb.eTypeClassClass) or (typeClass ==lldb.eTypeClassObjCObject) or (typeClass == lldb.eTypeClassObjCInterface) or (typeClass == lldb.eTypeClassObjCObjectPointer) or (typeClass == lldb.eTypeClassPointer)
+ //% self.assertTrue(condition, "s has the wrong TypeClass")
+ return 0;
+}
+- (id)init {
+ return (self = [super init]);
+}
+@end
+
+
+int main (int argc, char const *argv[])
+{
+ return [[[ThisClassTestsThings alloc] init] doSomething];
+}
diff --git a/packages/Python/lldbsuite/test/python_api/sbvalue_const_addrof/Makefile b/packages/Python/lldbsuite/test/python_api/sbvalue_const_addrof/Makefile
new file mode 100644
index 000000000000..a9c1edd1bdcf
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/sbvalue_const_addrof/Makefile
@@ -0,0 +1,4 @@
+LEVEL = ../../make
+CXX_SOURCES := main.cpp
+CXXFLAGS += -std=c++11
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/sbvalue_const_addrof/TestSBValueConstAddrOf.py b/packages/Python/lldbsuite/test/python_api/sbvalue_const_addrof/TestSBValueConstAddrOf.py
new file mode 100644
index 000000000000..a3d43c1bdeeb
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/sbvalue_const_addrof/TestSBValueConstAddrOf.py
@@ -0,0 +1,3 @@
+import lldbsuite.test.lldbinline as lldbinline
+
+lldbinline.MakeInlineTest(__file__, globals())
diff --git a/packages/Python/lldbsuite/test/python_api/sbvalue_const_addrof/main.cpp b/packages/Python/lldbsuite/test/python_api/sbvalue_const_addrof/main.cpp
new file mode 100644
index 000000000000..eb9c8e0c142a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/sbvalue_const_addrof/main.cpp
@@ -0,0 +1,40 @@
+#include <stdio.h>
+#include <stdint.h>
+
+struct RegisterContext
+{
+ uintptr_t r0;
+ uintptr_t r1;
+ uintptr_t r2;
+ uintptr_t r3;
+ uintptr_t r4;
+ uintptr_t pc;
+ uintptr_t fp;
+ uintptr_t sp;
+};
+
+struct ThreadInfo {
+ uint32_t tid;
+ const char *name;
+ RegisterContext regs;
+ ThreadInfo *next;
+};
+int main (int argc, char const *argv[], char const *envp[]);
+
+ThreadInfo g_thread2 = { 0x2222, "thread2", { 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, (uintptr_t)&main, 0x2006, 0x2007 }, NULL };
+ThreadInfo g_thread1 = { 0x1111, "thread1", { 0x1000, 0x1001, 0x1002, 0x1003, 0x1004, (uintptr_t)&main, 0x1006, 0x1007 }, &g_thread2 };
+ThreadInfo *g_thread_list_ptr = &g_thread1;
+
+int main (int argc, char const *argv[], char const *envp[])
+{
+ printf ("g_thread_list is %p\n", g_thread_list_ptr);
+ return 0; //% v = lldb.target.FindFirstGlobalVariable('g_thread_list_ptr')
+ //% v_gla = v.GetChildMemberWithName('regs').GetLoadAddress()
+ //% v_aof = v.GetChildMemberWithName('regs').AddressOf().GetValueAsUnsigned(lldb.LLDB_INVALID_ADDRESS)
+ //% expr = '(%s)0x%x' % (v.GetType().GetName(), v.GetValueAsUnsigned(0))
+ //% e = v.CreateValueFromExpression('e', expr)
+ //% e_gla = e.GetChildMemberWithName('regs').GetLoadAddress()
+ //% e_aof = e.GetChildMemberWithName('regs').AddressOf().GetValueAsUnsigned(lldb.LLDB_INVALID_ADDRESS)
+ //% self.assertTrue(v_gla == e_gla, "GetLoadAddress() differs")
+ //% self.assertTrue(v_aof == e_aof, "AddressOf() differs")
+}
diff --git a/packages/Python/lldbsuite/test/python_api/sbvalue_persist/Makefile b/packages/Python/lldbsuite/test/python_api/sbvalue_persist/Makefile
new file mode 100644
index 000000000000..e5c7b9150738
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/sbvalue_persist/Makefile
@@ -0,0 +1,15 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+# Clean renamed executable on 'make clean'
+clean: OBJECTS+=no_synth
+
+# clang-3.5+ outputs FullDebugInfo by default for Darwin/FreeBSD
+# targets. Other targets do not, which causes this test to fail.
+# This flag enables FullDebugInfo for all targets.
+ifneq (,$(findstring clang,$(CC)))
+ CFLAGS_EXTRAS += -fno-limit-debug-info
+endif
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/sbvalue_persist/TestSBValuePersist.py b/packages/Python/lldbsuite/test/python_api/sbvalue_persist/TestSBValuePersist.py
new file mode 100644
index 000000000000..6edbbda4c112
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/sbvalue_persist/TestSBValuePersist.py
@@ -0,0 +1,74 @@
+"""Test SBValue::Persist"""
+
+from __future__ import print_function
+
+
+
+import os, sys, time
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class SBValuePersistTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureWindows("llvm.org/pr24772")
+ def test(self):
+ """Test SBValue::Persist"""
+ self.build()
+ self.setTearDownCleanup()
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_source_regexp (self, "break here")
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ # This is the function to remove the custom formats in order to have a
+ # clean slate for the next test case.
+ def cleanup():
+ self.runCmd('type format clear', check=False)
+ self.runCmd('type summary clear', check=False)
+ self.runCmd('type filter clear', check=False)
+ self.runCmd('type synthetic clear', check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ foo = self.frame().FindVariable("foo")
+ bar = self.frame().FindVariable("bar")
+ baz = self.frame().FindVariable("baz")
+
+ self.assertTrue(foo.IsValid(), "foo is not valid")
+ self.assertTrue(bar.IsValid(), "bar is not valid")
+ self.assertTrue(baz.IsValid(), "baz is not valid")
+
+ fooPersist = foo.Persist()
+ barPersist = bar.Persist()
+ bazPersist = baz.Persist()
+
+ self.assertTrue(fooPersist.IsValid(), "fooPersist is not valid")
+ self.assertTrue(barPersist.IsValid(), "barPersist is not valid")
+ self.assertTrue(bazPersist.IsValid(), "bazPersist is not valid")
+
+ self.assertTrue(fooPersist.GetValueAsUnsigned(0) == 10, "fooPersist != 10")
+ self.assertTrue(barPersist.GetPointeeData().sint32[0] == 4, "barPersist != 4")
+ self.assertTrue(bazPersist.GetSummary() == '"85"', "bazPersist != 85")
+
+ self.runCmd("continue")
+
+ self.assertTrue(fooPersist.IsValid(), "fooPersist is not valid")
+ self.assertTrue(barPersist.IsValid(), "barPersist is not valid")
+ self.assertTrue(bazPersist.IsValid(), "bazPersist is not valid")
+
+ self.assertTrue(fooPersist.GetValueAsUnsigned(0) == 10, "fooPersist != 10")
+ self.assertTrue(barPersist.GetPointeeData().sint32[0] == 4, "barPersist != 4")
+ self.assertTrue(bazPersist.GetSummary() == '"85"', "bazPersist != 85")
+
+ self.expect("expr *(%s)" % (barPersist.GetName()), substrs = ['= 4'])
diff --git a/packages/Python/lldbsuite/test/python_api/sbvalue_persist/main.cpp b/packages/Python/lldbsuite/test/python_api/sbvalue_persist/main.cpp
new file mode 100644
index 000000000000..650d87acd6e6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/sbvalue_persist/main.cpp
@@ -0,0 +1,14 @@
+#include <vector>
+#include <string>
+
+void f() {}
+
+int main() {
+ int foo = 10;
+ int *bar = new int(4);
+ std::string baz = "85";
+
+ f(); // break here
+ f(); // break here
+ return 0;
+} \ No newline at end of file
diff --git a/packages/Python/lldbsuite/test/python_api/section/Makefile b/packages/Python/lldbsuite/test/python_api/section/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/section/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/section/TestSectionAPI.py b/packages/Python/lldbsuite/test/python_api/section/TestSectionAPI.py
new file mode 100644
index 000000000000..587216468f06
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/section/TestSectionAPI.py
@@ -0,0 +1,41 @@
+"""
+Test SBSection APIs.
+"""
+
+from __future__ import print_function
+
+
+
+from lldbsuite.test.lldbtest import *
+
+class SectionAPITestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @add_test_categories(['pyapi'])
+ def test_get_target_byte_size(self):
+ d = {'EXE': 'b.out'}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ exe = os.path.join(os.getcwd(), 'b.out')
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # find the .data section of the main module
+ mod = target.GetModuleAtIndex(0)
+ data_section = None
+ for s in mod.sections:
+ sect_type = s.GetSectionType()
+ if sect_type == lldb.eSectionTypeData:
+ data_section = s
+ break
+ elif sect_type == lldb.eSectionTypeContainer:
+ for i in range(s.GetNumSubSections()):
+ ss = s.GetSubSectionAtIndex(i)
+ sect_type = ss.GetSectionType()
+ if sect_type == lldb.eSectionTypeData:
+ data_section = ss
+ break
+
+ self.assertIsNotNone(data_section)
+ self.assertEqual(data_section.target_byte_size, 1)
diff --git a/packages/Python/lldbsuite/test/python_api/section/main.c b/packages/Python/lldbsuite/test/python_api/section/main.c
new file mode 100644
index 000000000000..746681d721a9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/section/main.c
@@ -0,0 +1,28 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+#include <string.h>
+
+// This simple program is to test the lldb Python API SBSection. It includes
+// somes global data, and so the build process produces a DATA section, which
+// the test code can use to query for the target byte size
+
+char my_global_var_of_char_type = 'X';
+
+int main (int argc, char const *argv[])
+{
+ // this code just "does something" with the global so that it is not
+ // optimised away
+ if (argc > 1 && strlen(argv[1]))
+ {
+ my_global_var_of_char_type += argv[1][0];
+ }
+
+ return my_global_var_of_char_type;
+}
diff --git a/packages/Python/lldbsuite/test/python_api/signals/Makefile b/packages/Python/lldbsuite/test/python_api/signals/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/signals/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/signals/TestSignalsAPI.py b/packages/Python/lldbsuite/test/python_api/signals/TestSignalsAPI.py
new file mode 100644
index 000000000000..9825c553cce9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/signals/TestSignalsAPI.py
@@ -0,0 +1,47 @@
+"""
+Test SBProcess APIs, including ReadMemory(), WriteMemory(), and others.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbutil import get_stopped_thread, state_type_to_str
+from lldbsuite.test.lldbtest import *
+
+class SignalsAPITestCase(TestBase):
+ mydir = TestBase.compute_mydir(__file__)
+
+ @add_test_categories(['pyapi'])
+ @expectedFlakeyLinux # this test fails 1/100 dosep runs
+ @skipIfWindows # Windows doesn't have signals
+ def test_ignore_signal(self):
+ """Test Python SBUnixSignals.Suppress/Stop/Notify() API."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ line = line_number("main.cpp", "// Set break point at this line and setup signal ignores.")
+ breakpoint = target.BreakpointCreateByLocation("main.cpp", line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint")
+
+ unix_signals = process.GetUnixSignals()
+ sigint = unix_signals.GetSignalNumberFromName("SIGINT")
+ unix_signals.SetShouldSuppress(sigint, True)
+ unix_signals.SetShouldStop(sigint, False)
+ unix_signals.SetShouldNotify(sigint, False)
+
+ process.Continue()
+ self.assertTrue(process.state == lldb.eStateExited, "The process should have exited")
+ self.assertTrue(process.GetExitStatus() == 0, "The process should have returned 0")
diff --git a/packages/Python/lldbsuite/test/python_api/signals/main.cpp b/packages/Python/lldbsuite/test/python_api/signals/main.cpp
new file mode 100644
index 000000000000..81924f435a1a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/signals/main.cpp
@@ -0,0 +1,28 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+#include <sys/types.h>
+#if defined(_WIN32)
+#include <windows.h>
+#else
+#include <unistd.h>
+#include <signal.h>
+#endif
+
+// This simple program is to test the lldb Python API related to process.
+
+int main (int argc, char const *argv[])
+{
+#if defined(_WIN32)
+ ::ExitProcess(1);
+#else
+ kill(getpid(), SIGINT); // Set break point at this line and setup signal ignores.
+#endif
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/python_api/symbol-context/Makefile b/packages/Python/lldbsuite/test/python_api/symbol-context/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/symbol-context/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/symbol-context/TestSymbolContext.py b/packages/Python/lldbsuite/test/python_api/symbol-context/TestSymbolContext.py
new file mode 100644
index 000000000000..2fec8dba0365
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/symbol-context/TestSymbolContext.py
@@ -0,0 +1,89 @@
+"""
+Test SBSymbolContext APIs.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class SymbolContextAPITestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to of function 'c'.
+ self.line = line_number('main.c', '// Find the line number of function "c" here.')
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test(self):
+ """Exercise SBSymbolContext API extensively."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create a breakpoint on main.c by name 'c'.
+ breakpoint = target.BreakpointCreateByName('c', 'a.out')
+ #print("breakpoint:", breakpoint)
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Frame #0 should be on self.line.
+ from lldbsuite.test.lldbutil import get_stopped_thread
+ thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint")
+ frame0 = thread.GetFrameAtIndex(0)
+ self.assertTrue(frame0.GetLineEntry().GetLine() == self.line)
+
+ # Now get the SBSymbolContext from this frame. We want everything. :-)
+ context = frame0.GetSymbolContext(lldb.eSymbolContextEverything)
+ self.assertTrue(context)
+
+ # Get the description of this module.
+ module = context.GetModule()
+ desc = lldbutil.get_description(module)
+ self.expect(desc, "The module should match", exe=False,
+ substrs = [os.path.join(self.mydir, 'a.out')])
+
+ compileUnit = context.GetCompileUnit()
+ self.expect(str(compileUnit), "The compile unit should match", exe=False,
+ substrs = [os.path.join(self.mydir, 'main.c')])
+
+ function = context.GetFunction()
+ self.assertTrue(function)
+ #print("function:", function)
+
+ block = context.GetBlock()
+ self.assertTrue(block)
+ #print("block:", block)
+
+ lineEntry = context.GetLineEntry()
+ #print("line entry:", lineEntry)
+ self.expect(lineEntry.GetFileSpec().GetDirectory(), "The line entry should have the correct directory",
+ exe=False,
+ substrs = [self.mydir])
+ self.expect(lineEntry.GetFileSpec().GetFilename(), "The line entry should have the correct filename",
+ exe=False,
+ substrs = ['main.c'])
+ self.assertTrue(lineEntry.GetLine() == self.line,
+ "The line entry's line number should match ")
+
+ symbol = context.GetSymbol()
+ self.assertTrue(function.GetName() == symbol.GetName() and symbol.GetName() == 'c',
+ "The symbol name should be 'c'")
diff --git a/packages/Python/lldbsuite/test/python_api/symbol-context/main.c b/packages/Python/lldbsuite/test/python_api/symbol-context/main.c
new file mode 100644
index 000000000000..3ac1825d8d21
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/symbol-context/main.c
@@ -0,0 +1,51 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+// This simple program is to test the lldb Python API SBSymbolContext.
+// When stopped on a frame, we can get the symbol context using the SBFrame API
+// SBFrame.GetSymbolContext().
+
+int a(int);
+int b(int);
+int c(int);
+
+int a(int val)
+{
+ if (val <= 1)
+ return b(val);
+ else if (val >= 3)
+ return c(val);
+
+ return val;
+}
+
+int b(int val)
+{
+ return c(val);
+}
+
+int c(int val)
+{
+ return val + 3; // Find the line number of function "c" here.
+}
+
+int main (int argc, char const *argv[])
+{
+ int A1 = a(1); // a(1) -> b(1) -> c(1)
+ printf("a(1) returns %d\n", A1);
+
+ int B2 = b(2); // b(2) -> c(2)
+ printf("b(2) returns %d\n", B2);
+
+ int A3 = a(3); // a(3) -> c(3)
+ printf("a(3) returns %d\n", A3);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/python_api/target/Makefile b/packages/Python/lldbsuite/test/python_api/target/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/target/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/target/TestTargetAPI.py b/packages/Python/lldbsuite/test/python_api/target/TestTargetAPI.py
new file mode 100644
index 000000000000..0231d285ecf9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/target/TestTargetAPI.py
@@ -0,0 +1,372 @@
+"""
+Test SBTarget APIs.
+"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TargetAPITestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to of function 'c'.
+ self.line1 = line_number('main.c', '// Find the line number for breakpoint 1 here.')
+ self.line2 = line_number('main.c', '// Find the line number for breakpoint 2 here.')
+ self.line_main = line_number("main.c", "// Set a break at entry to main.")
+
+ #rdar://problem/9700873
+ # Find global variable value fails for dwarf if inferior not started
+ # (Was CrashTracer: [USER] 1 crash in Python at _lldb.so: lldb_private::MemoryCache::Read + 94)
+ #
+ # It does not segfaults now. But for dwarf, the variable value is None if
+ # the inferior process does not exist yet. The radar has been updated.
+ #@unittest232.skip("segmentation fault -- skipping")
+ @add_test_categories(['pyapi'])
+ def test_find_global_variables(self):
+ """Exercise SBTarget.FindGlobalVariables() API."""
+ d = {'EXE': 'b.out'}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ self.find_global_variables('b.out')
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureWindows("llvm.org/pr24778")
+ def test_find_functions(self):
+ """Exercise SBTarget.FindFunctions() API."""
+ d = {'EXE': 'b.out'}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ self.find_functions('b.out')
+
+ @add_test_categories(['pyapi'])
+ def test_get_description(self):
+ """Exercise SBTarget.GetDescription() API."""
+ self.build()
+ self.get_description()
+
+ @add_test_categories(['pyapi'])
+ def test_launch_new_process_and_redirect_stdout(self):
+ """Exercise SBTarget.Launch() API."""
+ self.build()
+ self.launch_new_process_and_redirect_stdout()
+
+ @add_test_categories(['pyapi'])
+ def test_resolve_symbol_context_with_address(self):
+ """Exercise SBTarget.ResolveSymbolContextForAddress() API."""
+ self.build()
+ self.resolve_symbol_context_with_address()
+
+ @add_test_categories(['pyapi'])
+ def test_get_platform(self):
+ d = {'EXE': 'b.out'}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ target = self.create_simple_target('b.out')
+ platform = target.platform
+ self.assertTrue(platform, VALID_PLATFORM)
+
+ @add_test_categories(['pyapi'])
+ def test_get_data_byte_size(self):
+ d = {'EXE': 'b.out'}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ target = self.create_simple_target('b.out')
+ self.assertEqual(target.data_byte_size, 1)
+
+ @add_test_categories(['pyapi'])
+ def test_get_code_byte_size(self):
+ d = {'EXE': 'b.out'}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ target = self.create_simple_target('b.out')
+ self.assertEqual(target.code_byte_size, 1)
+
+ @add_test_categories(['pyapi'])
+ def test_resolve_file_address(self):
+ d = {'EXE': 'b.out'}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ target = self.create_simple_target('b.out')
+
+ # find the file address in the .data section of the main
+ # module
+ data_section = self.find_data_section(target)
+ data_section_addr = data_section.file_addr
+
+ # resolve the above address, and compare the address produced
+ # by the resolution against the original address/section
+ res_file_addr = target.ResolveFileAddress(data_section_addr)
+ self.assertTrue(res_file_addr.IsValid())
+
+ self.assertEqual(data_section_addr, res_file_addr.file_addr)
+
+ data_section2 = res_file_addr.section
+ self.assertIsNotNone(data_section2)
+ self.assertEqual(data_section.name, data_section2.name)
+
+ @add_test_categories(['pyapi'])
+ def test_read_memory(self):
+ d = {'EXE': 'b.out'}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ target = self.create_simple_target('b.out')
+
+ breakpoint = target.BreakpointCreateByLocation("main.c", self.line_main)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Put debugger into synchronous mode so when we target.LaunchSimple returns
+ # it will guaranteed to be at the breakpoint
+ self.dbg.SetAsync(False)
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ # find the file address in the .data section of the main
+ # module
+ data_section = self.find_data_section(target)
+ sb_addr = lldb.SBAddress(data_section, 0)
+ error = lldb.SBError()
+ content = target.ReadMemory(sb_addr, 1, error)
+ self.assertTrue(error.Success(), "Make sure memory read succeeded")
+ self.assertEqual(len(content), 1)
+
+ def create_simple_target(self, fn):
+ exe = os.path.join(os.getcwd(), fn)
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+ return target
+
+ def find_data_section(self, target):
+ mod = target.GetModuleAtIndex(0)
+ data_section = None
+ for s in mod.sections:
+ sect_type = s.GetSectionType()
+ if sect_type == lldb.eSectionTypeData:
+ data_section = s
+ break
+ elif sect_type == lldb.eSectionTypeContainer:
+ for i in range(s.GetNumSubSections()):
+ ss = s.GetSubSectionAtIndex(i)
+ sect_type = ss.GetSectionType()
+ if sect_type == lldb.eSectionTypeData:
+ data_section = ss
+ break
+
+ self.assertIsNotNone(data_section)
+ return data_section
+
+ def find_global_variables(self, exe_name):
+ """Exercise SBTaget.FindGlobalVariables() API."""
+ exe = os.path.join(os.getcwd(), exe_name)
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ #rdar://problem/9700873
+ # Find global variable value fails for dwarf if inferior not started
+ # (Was CrashTracer: [USER] 1 crash in Python at _lldb.so: lldb_private::MemoryCache::Read + 94)
+ #
+ # Remove the lines to create a breakpoint and to start the inferior
+ # which are workarounds for the dwarf case.
+
+ breakpoint = target.BreakpointCreateByLocation('main.c', self.line1)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+ # Make sure we hit our breakpoint:
+ thread_list = lldbutil.get_threads_stopped_at_breakpoint (process, breakpoint)
+ self.assertTrue (len(thread_list) == 1)
+
+ value_list = target.FindGlobalVariables('my_global_var_of_char_type', 3)
+ self.assertTrue(value_list.GetSize() == 1)
+ my_global_var = value_list.GetValueAtIndex(0)
+ self.DebugSBValue(my_global_var)
+ self.assertTrue(my_global_var)
+ self.expect(my_global_var.GetName(), exe=False,
+ startstr = "my_global_var_of_char_type")
+ self.expect(my_global_var.GetTypeName(), exe=False,
+ startstr = "char")
+ self.expect(my_global_var.GetValue(), exe=False,
+ startstr = "'X'")
+
+ # While we are at it, let's also exercise the similar SBModule.FindGlobalVariables() API.
+ for m in target.module_iter():
+ if os.path.normpath(m.GetFileSpec().GetDirectory()) == os.getcwd() and m.GetFileSpec().GetFilename() == exe_name:
+ value_list = m.FindGlobalVariables(target, 'my_global_var_of_char_type', 3)
+ self.assertTrue(value_list.GetSize() == 1)
+ self.assertTrue(value_list.GetValueAtIndex(0).GetValue() == "'X'")
+ break
+
+ def find_functions(self, exe_name):
+ """Exercise SBTaget.FindFunctions() API."""
+ exe = os.path.join(os.getcwd(), exe_name)
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ list = target.FindFunctions('c', lldb.eFunctionNameTypeAuto)
+ self.assertTrue(list.GetSize() == 1)
+
+ for sc in list:
+ self.assertTrue(sc.GetModule().GetFileSpec().GetFilename() == exe_name)
+ self.assertTrue(sc.GetSymbol().GetName() == 'c')
+
+ def get_description(self):
+ """Exercise SBTaget.GetDescription() API."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ from lldbsuite.test.lldbutil import get_description
+
+ # get_description() allows no option to mean lldb.eDescriptionLevelBrief.
+ desc = get_description(target)
+ #desc = get_description(target, option=lldb.eDescriptionLevelBrief)
+ if not desc:
+ self.fail("SBTarget.GetDescription() failed")
+ self.expect(desc, exe=False,
+ substrs = ['a.out'])
+ self.expect(desc, exe=False, matching=False,
+ substrs = ['Target', 'Module', 'Breakpoint'])
+
+ desc = get_description(target, option=lldb.eDescriptionLevelFull)
+ if not desc:
+ self.fail("SBTarget.GetDescription() failed")
+ self.expect(desc, exe=False,
+ substrs = ['a.out', 'Target', 'Module', 'Breakpoint'])
+
+ @not_remote_testsuite_ready
+ def launch_new_process_and_redirect_stdout(self):
+ """Exercise SBTaget.Launch() API with redirected stdout."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Add an extra twist of stopping the inferior in a breakpoint, and then continue till it's done.
+ # We should still see the entire stdout redirected once the process is finished.
+ line = line_number('main.c', '// a(3) -> c(3)')
+ breakpoint = target.BreakpointCreateByLocation('main.c', line)
+
+ # Now launch the process, do not stop at entry point, and redirect stdout to "stdout.txt" file.
+ # The inferior should run to completion after "process.Continue()" call.
+ local_path = "stdout.txt";
+ if lldb.remote_platform:
+ stdout_path = lldbutil.append_to_process_working_directory("lldb-stdout-redirect.txt")
+ else:
+ stdout_path = local_path
+ error = lldb.SBError()
+ process = target.Launch (self.dbg.GetListener(), None, None, None, stdout_path, None, None, 0, False, error)
+ process.Continue()
+ #self.runCmd("process status")
+ if lldb.remote_platform:
+ # copy output file to host
+ lldb.remote_platform.Get(lldb.SBFileSpec(stdout_path), lldb.SBFileSpec(local_path))
+
+ # The 'stdout.txt' file should now exist.
+ self.assertTrue(os.path.isfile("stdout.txt"),
+ "'stdout.txt' exists due to redirected stdout via SBTarget.Launch() API.")
+
+ # Read the output file produced by running the program.
+ with open('stdout.txt', 'r') as f:
+ output = f.read()
+
+ # Let's delete the 'stdout.txt' file as a cleanup step.
+ try:
+ os.remove("stdout.txt")
+ pass
+ except OSError:
+ pass
+
+ self.expect(output, exe=False,
+ substrs = ["a(1)", "b(2)", "a(3)"])
+
+
+ def resolve_symbol_context_with_address(self):
+ """Exercise SBTaget.ResolveSymbolContextForAddress() API."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create the two breakpoints inside function 'a'.
+ breakpoint1 = target.BreakpointCreateByLocation('main.c', self.line1)
+ breakpoint2 = target.BreakpointCreateByLocation('main.c', self.line2)
+ #print("breakpoint1:", breakpoint1)
+ #print("breakpoint2:", breakpoint2)
+ self.assertTrue(breakpoint1 and
+ breakpoint1.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+ self.assertTrue(breakpoint2 and
+ breakpoint2.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Frame #0 should be on self.line1.
+ self.assertTrue(process.GetState() == lldb.eStateStopped)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
+ #self.runCmd("process status")
+ frame0 = thread.GetFrameAtIndex(0)
+ lineEntry = frame0.GetLineEntry()
+ self.assertTrue(lineEntry.GetLine() == self.line1)
+
+ address1 = lineEntry.GetStartAddress()
+
+ # Continue the inferior, the breakpoint 2 should be hit.
+ process.Continue()
+ self.assertTrue(process.GetState() == lldb.eStateStopped)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
+ #self.runCmd("process status")
+ frame0 = thread.GetFrameAtIndex(0)
+ lineEntry = frame0.GetLineEntry()
+ self.assertTrue(lineEntry.GetLine() == self.line2)
+
+ address2 = lineEntry.GetStartAddress()
+
+ #print("address1:", address1)
+ #print("address2:", address2)
+
+ # Now call SBTarget.ResolveSymbolContextForAddress() with the addresses from our line entry.
+ context1 = target.ResolveSymbolContextForAddress(address1, lldb.eSymbolContextEverything)
+ context2 = target.ResolveSymbolContextForAddress(address2, lldb.eSymbolContextEverything)
+
+ self.assertTrue(context1 and context2)
+ #print("context1:", context1)
+ #print("context2:", context2)
+
+ # Verify that the context point to the same function 'a'.
+ symbol1 = context1.GetSymbol()
+ symbol2 = context2.GetSymbol()
+ self.assertTrue(symbol1 and symbol2)
+ #print("symbol1:", symbol1)
+ #print("symbol2:", symbol2)
+
+ from lldbsuite.test.lldbutil import get_description
+ desc1 = get_description(symbol1)
+ desc2 = get_description(symbol2)
+ self.assertTrue(desc1 and desc2 and desc1 == desc2,
+ "The two addresses should resolve to the same symbol")
diff --git a/packages/Python/lldbsuite/test/python_api/target/main.c b/packages/Python/lldbsuite/test/python_api/target/main.c
new file mode 100644
index 000000000000..ba82a5437ae3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/target/main.c
@@ -0,0 +1,60 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+// This simple program is to test the lldb Python API SBTarget.
+//
+// When stopped on breakppint 1, and then 2, we can get the line entries using
+// SBFrame API SBFrame.GetLineEntry(). We'll get the start addresses for the
+// two line entries; with the start address (of SBAddress type), we can then
+// resolve the symbol context using the SBTarget API
+// SBTarget.ResolveSymbolContextForAddress().
+//
+// The two symbol context should point to the same symbol, i.e., 'a' function.
+
+char my_global_var_of_char_type = 'X'; // Test SBTarget.FindGlobalVariables(...).
+
+int a(int);
+int b(int);
+int c(int);
+
+int a(int val)
+{
+ if (val <= 1) // Find the line number for breakpoint 1 here.
+ val = b(val);
+ else if (val >= 3)
+ val = c(val);
+
+ return val; // Find the line number for breakpoint 2 here.
+}
+
+int b(int val)
+{
+ return c(val);
+}
+
+int c(int val)
+{
+ return val + 3;
+}
+
+int main (int argc, char const *argv[])
+{
+ // Set a break at entry to main.
+ int A1 = a(1); // a(1) -> b(1) -> c(1)
+ printf("a(1) returns %d\n", A1);
+
+ int B2 = b(2); // b(2) -> c(2)
+ printf("b(2) returns %d\n", B2);
+
+ int A3 = a(3); // a(3) -> c(3)
+ printf("a(3) returns %d\n", A3);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/python_api/thread/Makefile b/packages/Python/lldbsuite/test/python_api/thread/Makefile
new file mode 100644
index 000000000000..aa257ae2bd2a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/thread/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES ?= main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/thread/TestThreadAPI.py b/packages/Python/lldbsuite/test/python_api/thread/TestThreadAPI.py
new file mode 100644
index 000000000000..dad829a48f2f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/thread/TestThreadAPI.py
@@ -0,0 +1,245 @@
+"""
+Test SBThread APIs.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbutil import get_stopped_thread, get_caller_symbol
+from lldbsuite.test.lldbtest import *
+
+class ThreadAPITestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @add_test_categories(['pyapi'])
+ def test_get_process(self):
+ """Test Python SBThread.GetProcess() API."""
+ self.build()
+ self.get_process()
+
+ @add_test_categories(['pyapi'])
+ def test_get_stop_description(self):
+ """Test Python SBThread.GetStopDescription() API."""
+ self.build()
+ self.get_stop_description()
+
+ @add_test_categories(['pyapi'])
+ def test_run_to_address(self):
+ """Test Python SBThread.RunToAddress() API."""
+ # We build a different executable than the default build() does.
+ d = {'CXX_SOURCES': 'main2.cpp', 'EXE': self.exe_name}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ self.run_to_address(self.exe_name)
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureFreeBSD # llvm.org/pr20476
+ @expectedFailureWindows # Test crashes
+ def test_step_out_of_malloc_into_function_b(self):
+ """Test Python SBThread.StepOut() API to step out of a malloc call where the call site is at function b()."""
+ # We build a different executable than the default build() does.
+ d = {'CXX_SOURCES': 'main2.cpp', 'EXE': self.exe_name}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ self.step_out_of_malloc_into_function_b(self.exe_name)
+
+ @add_test_categories(['pyapi'])
+ def test_step_over_3_times(self):
+ """Test Python SBThread.StepOver() API."""
+ # We build a different executable than the default build() does.
+ d = {'CXX_SOURCES': 'main2.cpp', 'EXE': self.exe_name}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ self.step_over_3_times(self.exe_name)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number within main.cpp to break inside main().
+ self.break_line = line_number("main.cpp", "// Set break point at this line and check variable 'my_char'.")
+ # Find the line numbers within main2.cpp for step_out_of_malloc_into_function_b() and step_over_3_times().
+ self.step_out_of_malloc = line_number("main2.cpp", "// thread step-out of malloc into function b.")
+ self.after_3_step_overs = line_number("main2.cpp", "// we should reach here after 3 step-over's.")
+
+ # We'll use the test method name as the exe_name for executable comppiled from main2.cpp.
+ self.exe_name = self.testMethodName
+
+ def get_process(self):
+ """Test Python SBThread.GetProcess() API."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByLocation("main.cpp", self.break_line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+ self.runCmd("breakpoint list")
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint")
+ self.runCmd("process status")
+
+ proc_of_thread = thread.GetProcess()
+ #print("proc_of_thread:", proc_of_thread)
+ self.assertTrue(proc_of_thread.GetProcessID() == process.GetProcessID())
+
+ def get_stop_description(self):
+ """Test Python SBThread.GetStopDescription() API."""
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByLocation("main.cpp", self.break_line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+ #self.runCmd("breakpoint list")
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint")
+ #self.runCmd("process status")
+
+ # Due to the typemap magic (see lldb.swig), we pass in an (int)length to GetStopDescription
+ # and expect to get a Python string as the return object!
+ # The 100 is just an arbitrary number specifying the buffer size.
+ stop_description = thread.GetStopDescription(100)
+ self.expect(stop_description, exe=False,
+ startstr = 'breakpoint')
+
+ def step_out_of_malloc_into_function_b(self, exe_name):
+ """Test Python SBThread.StepOut() API to step out of a malloc call where the call site is at function b()."""
+ exe = os.path.join(os.getcwd(), exe_name)
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByName('malloc')
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ while True:
+ thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint")
+ caller_symbol = get_caller_symbol(thread)
+ if not caller_symbol:
+ self.fail("Test failed: could not locate the caller symbol of malloc")
+
+ # Our top frame may be an inlined function in malloc() (e.g., on
+ # FreeBSD). Apply a simple heuristic of stepping out until we find
+ # a non-malloc caller
+ while caller_symbol.startswith("malloc"):
+ thread.StepOut()
+ self.assertTrue(thread.IsValid(), "Thread valid after stepping to outer malloc")
+ caller_symbol = get_caller_symbol(thread)
+
+ if caller_symbol == "b(int)":
+ break
+ process.Continue()
+
+ # On Linux malloc calls itself in some case. Remove the breakpoint because we don't want
+ # to hit it during step-out.
+ target.BreakpointDelete(breakpoint.GetID())
+
+ thread.StepOut()
+ self.runCmd("thread backtrace")
+ self.assertTrue(thread.GetFrameAtIndex(0).GetLineEntry().GetLine() == self.step_out_of_malloc,
+ "step out of malloc into function b is successful")
+
+ def step_over_3_times(self, exe_name):
+ """Test Python SBThread.StepOver() API."""
+ exe = os.path.join(os.getcwd(), exe_name)
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByLocation('main2.cpp', self.step_out_of_malloc)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+ self.runCmd("breakpoint list")
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Frame #0 should be on self.step_out_of_malloc.
+ self.assertTrue(process.GetState() == lldb.eStateStopped)
+ thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
+ self.runCmd("thread backtrace")
+ frame0 = thread.GetFrameAtIndex(0)
+ lineEntry = frame0.GetLineEntry()
+ self.assertTrue(lineEntry.GetLine() == self.step_out_of_malloc)
+
+ thread.StepOver()
+ thread.StepOver()
+ thread.StepOver()
+ self.runCmd("thread backtrace")
+
+ # Verify that we are stopped at the correct source line number in main2.cpp.
+ frame0 = thread.GetFrameAtIndex(0)
+ lineEntry = frame0.GetLineEntry()
+ self.assertTrue(thread.GetStopReason() == lldb.eStopReasonPlanComplete)
+ # Expected failure with clang as the compiler.
+ # rdar://problem/9223880
+ #
+ # Which has been fixed on the lldb by compensating for inaccurate line
+ # table information with r140416.
+ self.assertTrue(lineEntry.GetLine() == self.after_3_step_overs)
+
+ def run_to_address(self, exe_name):
+ """Test Python SBThread.RunToAddress() API."""
+ exe = os.path.join(os.getcwd(), exe_name)
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ breakpoint = target.BreakpointCreateByLocation('main2.cpp', self.step_out_of_malloc)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+ self.runCmd("breakpoint list")
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Frame #0 should be on self.step_out_of_malloc.
+ self.assertTrue(process.GetState() == lldb.eStateStopped)
+ thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
+ self.runCmd("thread backtrace")
+ frame0 = thread.GetFrameAtIndex(0)
+ lineEntry = frame0.GetLineEntry()
+ self.assertTrue(lineEntry.GetLine() == self.step_out_of_malloc)
+
+ # Get the start/end addresses for this line entry.
+ start_addr = lineEntry.GetStartAddress().GetLoadAddress(target)
+ end_addr = lineEntry.GetEndAddress().GetLoadAddress(target)
+ if self.TraceOn():
+ print("start addr:", hex(start_addr))
+ print("end addr:", hex(end_addr))
+
+ # Disable the breakpoint.
+ self.assertTrue(target.DisableAllBreakpoints())
+ self.runCmd("breakpoint list")
+
+ thread.StepOver()
+ thread.StepOver()
+ thread.StepOver()
+ self.runCmd("thread backtrace")
+
+ # Now ask SBThread to run to the address 'start_addr' we got earlier, which
+ # corresponds to self.step_out_of_malloc line entry's start address.
+ thread.RunToAddress(start_addr)
+ self.runCmd("process status")
+ #self.runCmd("thread backtrace")
diff --git a/packages/Python/lldbsuite/test/python_api/thread/main.cpp b/packages/Python/lldbsuite/test/python_api/thread/main.cpp
new file mode 100644
index 000000000000..8d8069036898
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/thread/main.cpp
@@ -0,0 +1,26 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+// This simple program is to test the lldb Python API related to thread.
+
+char my_char = 'u';
+int my_int = 0;
+
+int main (int argc, char const *argv[])
+{
+ for (int i = 0; i < 3; ++i) {
+ printf("my_char='%c'\n", my_char);
+ ++my_char;
+ }
+
+ printf("after the loop: my_char='%c'\n", my_char); // 'my_char' should print out as 'x'.
+
+ return 0; // Set break point at this line and check variable 'my_char'.
+}
diff --git a/packages/Python/lldbsuite/test/python_api/thread/main2.cpp b/packages/Python/lldbsuite/test/python_api/thread/main2.cpp
new file mode 100644
index 000000000000..a95d7d7aec1a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/thread/main2.cpp
@@ -0,0 +1,54 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+#include <stdlib.h>
+
+int a(int);
+int b(int);
+int c(int);
+
+int a(int val)
+{
+ if (val <= 1)
+ return b(val);
+ else if (val >= 3)
+ return c(val);
+
+ return val;
+}
+
+int b(int val)
+{
+ int rc = c(val);
+ void *ptr = malloc(1024); // thread step-out of malloc into function b.
+ if (!ptr)
+ return -1;
+ else
+ printf("ptr=%p\n", ptr);
+ return rc; // we should reach here after 3 step-over's.
+}
+
+int c(int val)
+{
+ return val + 3;
+}
+
+int main (int argc, char const *argv[])
+{
+ int A1 = a(1);
+ printf("a(1) returns %d\n", A1);
+
+ int B2 = b(2);
+ printf("b(2) returns %d\n", B2);
+
+ int A3 = a(3);
+ printf("a(3) returns %d\n", A3);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/python_api/type/Makefile b/packages/Python/lldbsuite/test/python_api/type/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/type/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/type/TestTypeList.py b/packages/Python/lldbsuite/test/python_api/type/TestTypeList.py
new file mode 100644
index 000000000000..d9e5719844e2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/type/TestTypeList.py
@@ -0,0 +1,116 @@
+"""
+Test SBType and SBTypeList API.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TypeAndTypeListTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # We'll use the test method name as the exe_name.
+ self.exe_name = self.testMethodName
+ # Find the line number to break at.
+ self.source = 'main.cpp'
+ self.line = line_number(self.source, '// Break at this line')
+
+ @add_test_categories(['pyapi'])
+ def test(self):
+ """Exercise SBType and SBTypeList API."""
+ d = {'EXE': self.exe_name}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ exe = os.path.join(os.getcwd(), self.exe_name)
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Create the breakpoint inside function 'main'.
+ breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Get Frame #0.
+ self.assertTrue(process.GetState() == lldb.eStateStopped)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
+ frame0 = thread.GetFrameAtIndex(0)
+
+ # Get the type 'Task'.
+ type_list = target.FindTypes('Task')
+ if self.TraceOn():
+ print("Size of type_list from target.FindTypes('Task') query: %d" % type_list.GetSize())
+ self.assertTrue(len(type_list) >= 1) # a second Task make be scared up by the Objective-C runtime
+ for type in type_list:
+ self.assertTrue(type)
+ self.DebugSBType(type)
+ self.assertFalse(type.IsAnonymousType(), "Task is not anonymous")
+ for field in type.fields:
+ if field.name == "type":
+ for enum_member in field.type.enum_members:
+ self.assertTrue(enum_member)
+ self.DebugSBType(enum_member.type)
+ elif field.name == "my_type_is_nameless":
+ self.assertTrue(field.type.IsAnonymousType(), "my_type_is_nameless has an anonymous type")
+ elif field.name == "my_type_is_named":
+ self.assertFalse(field.type.IsAnonymousType(), "my_type_is_named has a named type")
+
+ # Pass an empty string. LLDB should not crash. :-)
+ fuzz_types = target.FindTypes(None)
+ fuzz_type = target.FindFirstType(None)
+
+ # Now use the SBTarget.FindFirstType() API to find 'Task'.
+ task_type = target.FindFirstType('Task')
+ self.assertTrue(task_type)
+ self.DebugSBType(task_type)
+
+ # Get the reference type of 'Task', just for fun.
+ task_ref_type = task_type.GetReferenceType()
+ self.assertTrue(task_ref_type)
+ self.DebugSBType(task_ref_type)
+
+ # Get the pointer type of 'Task', which is the same as task_head's type.
+ task_pointer_type = task_type.GetPointerType()
+ self.assertTrue(task_pointer_type)
+ self.DebugSBType(task_pointer_type)
+
+ # Get variable 'task_head'.
+ task_head = frame0.FindVariable('task_head')
+ self.assertTrue(task_head, VALID_VARIABLE)
+ self.DebugSBValue(task_head)
+ task_head_type = task_head.GetType()
+ self.DebugSBType(task_head_type)
+ self.assertTrue(task_head_type.IsPointerType())
+
+ self.assertTrue(task_head_type == task_pointer_type)
+
+ # Get the pointee type of 'task_head'.
+ task_head_pointee_type = task_head_type.GetPointeeType()
+ self.DebugSBType(task_head_pointee_type)
+
+ self.assertTrue(task_type == task_head_pointee_type)
+
+ # We'll now get the child member 'id' from 'task_head'.
+ id = task_head.GetChildMemberWithName('id')
+ self.DebugSBValue(id)
+ id_type = id.GetType()
+ self.DebugSBType(id_type)
+
+ # SBType.GetBasicType() takes an enum 'BasicType' (lldb-enumerations.h).
+ int_type = id_type.GetBasicType(lldb.eBasicTypeInt)
+ self.assertTrue(id_type == int_type)
diff --git a/packages/Python/lldbsuite/test/python_api/type/main.cpp b/packages/Python/lldbsuite/test/python_api/type/main.cpp
new file mode 100644
index 000000000000..b7f3dcc7fbea
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/type/main.cpp
@@ -0,0 +1,60 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+class Task {
+public:
+ int id;
+ Task *next;
+ enum {
+ TASK_TYPE_1,
+ TASK_TYPE_2
+ } type;
+ struct {
+ int x;
+ } my_type_is_nameless;
+ struct name {
+ int x;
+ } my_type_is_named;
+ Task(int i, Task *n):
+ id(i),
+ next(n),
+ type(TASK_TYPE_1)
+ {}
+};
+
+
+int main (int argc, char const *argv[])
+{
+ Task *task_head = new Task(-1, NULL);
+ Task *task1 = new Task(1, NULL);
+ Task *task2 = new Task(2, NULL);
+ Task *task3 = new Task(3, NULL); // Orphaned.
+ Task *task4 = new Task(4, NULL);
+ Task *task5 = new Task(5, NULL);
+
+ task_head->next = task1;
+ task1->next = task2;
+ task2->next = task4;
+ task4->next = task5;
+
+ int total = 0;
+ Task *t = task_head;
+ while (t != NULL) {
+ if (t->id >= 0)
+ ++total;
+ t = t->next;
+ }
+ printf("We have a total number of %d tasks\n", total);
+
+ // This corresponds to an empty task list.
+ Task *empty_task_head = new Task(-1, NULL);
+
+ return 0; // Break at this line
+}
diff --git a/packages/Python/lldbsuite/test/python_api/value/Makefile b/packages/Python/lldbsuite/test/python_api/value/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/value/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/value/TestValueAPI.py b/packages/Python/lldbsuite/test/python_api/value/TestValueAPI.py
new file mode 100644
index 000000000000..77ff07ea6488
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/value/TestValueAPI.py
@@ -0,0 +1,135 @@
+"""
+Test some SBValue APIs.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ValueAPITestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # We'll use the test method name as the exe_name.
+ self.exe_name = self.testMethodName
+ # Find the line number to of function 'c'.
+ self.line = line_number('main.c', '// Break at this line')
+
+ @expectedFailureWindows("llvm.org/pr24772")
+ @add_test_categories(['pyapi'])
+ def test(self):
+ """Exercise some SBValue APIs."""
+ d = {'EXE': self.exe_name}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ exe = os.path.join(os.getcwd(), self.exe_name)
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Create the breakpoint inside function 'main'.
+ breakpoint = target.BreakpointCreateByLocation('main.c', self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Get Frame #0.
+ self.assertTrue(process.GetState() == lldb.eStateStopped)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
+ frame0 = thread.GetFrameAtIndex(0)
+
+ # Get global variable 'days_of_week'.
+ list = target.FindGlobalVariables('days_of_week', 1)
+ days_of_week = list.GetValueAtIndex(0)
+ self.assertTrue(days_of_week, VALID_VARIABLE)
+ self.assertTrue(days_of_week.GetNumChildren() == 7, VALID_VARIABLE)
+ self.DebugSBValue(days_of_week)
+
+ # Get global variable 'weekdays'.
+ list = target.FindGlobalVariables('weekdays', 1)
+ weekdays = list.GetValueAtIndex(0)
+ self.assertTrue(weekdays, VALID_VARIABLE)
+ self.assertTrue(weekdays.GetNumChildren() == 5, VALID_VARIABLE)
+ self.DebugSBValue(weekdays)
+
+ # Get global variable 'g_table'.
+ list = target.FindGlobalVariables('g_table', 1)
+ g_table = list.GetValueAtIndex(0)
+ self.assertTrue(g_table, VALID_VARIABLE)
+ self.assertTrue(g_table.GetNumChildren() == 2, VALID_VARIABLE)
+ self.DebugSBValue(g_table)
+
+ fmt = lldbutil.BasicFormatter()
+ cvf = lldbutil.ChildVisitingFormatter(indent_child=2)
+ rdf = lldbutil.RecursiveDecentFormatter(indent_child=2)
+ if self.TraceOn():
+ print(fmt.format(days_of_week))
+ print(cvf.format(days_of_week))
+ print(cvf.format(weekdays))
+ print(rdf.format(g_table))
+
+ # Get variable 'my_int_ptr'.
+ value = frame0.FindVariable('my_int_ptr')
+ self.assertTrue(value, VALID_VARIABLE)
+ self.DebugSBValue(value)
+
+ # Get what 'my_int_ptr' points to.
+ pointed = value.GetChildAtIndex(0)
+ self.assertTrue(pointed, VALID_VARIABLE)
+ self.DebugSBValue(pointed)
+
+ # While we are at it, verify that 'my_int_ptr' points to 'g_my_int'.
+ symbol = target.ResolveLoadAddress(int(pointed.GetLocation(), 0)).GetSymbol()
+ self.assertTrue(symbol)
+ self.expect(symbol.GetName(), exe=False,
+ startstr = 'g_my_int')
+
+ # Get variable 'str_ptr'.
+ value = frame0.FindVariable('str_ptr')
+ self.assertTrue(value, VALID_VARIABLE)
+ self.DebugSBValue(value)
+
+ # SBValue::TypeIsPointerType() should return true.
+ self.assertTrue(value.TypeIsPointerType())
+
+ # Verify the SBValue::GetByteSize() API is working correctly.
+ arch = self.getArchitecture()
+ if arch == 'i386':
+ self.assertTrue(value.GetByteSize() == 4)
+ elif arch == 'x86_64':
+ self.assertTrue(value.GetByteSize() == 8)
+
+ # Get child at index 5 => 'Friday'.
+ child = value.GetChildAtIndex(5, lldb.eNoDynamicValues, True)
+ self.assertTrue(child, VALID_VARIABLE)
+ self.DebugSBValue(child)
+
+ self.expect(child.GetSummary(), exe=False,
+ substrs = ['Friday'])
+
+ # Now try to get at the same variable using GetValueForExpressionPath().
+ # These two SBValue objects should have the same value.
+ val2 = value.GetValueForExpressionPath('[5]')
+ self.assertTrue(val2, VALID_VARIABLE)
+ self.DebugSBValue(val2)
+ self.assertTrue(child.GetValue() == val2.GetValue() and
+ child.GetSummary() == val2.GetSummary())
+
+ val_i = target.EvaluateExpression('i')
+ val_s = target.EvaluateExpression('s')
+ val_a = target.EvaluateExpression('a')
+ self.assertTrue(val_s.GetChildMemberWithName('a').AddressOf(), VALID_VARIABLE)
+ self.assertTrue(val_a.Cast(val_i.GetType()).AddressOf(), VALID_VARIABLE)
diff --git a/packages/Python/lldbsuite/test/python_api/value/change_values/Makefile b/packages/Python/lldbsuite/test/python_api/value/change_values/Makefile
new file mode 100644
index 000000000000..b09a579159d4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/value/change_values/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/value/change_values/TestChangeValueAPI.py b/packages/Python/lldbsuite/test/python_api/value/change_values/TestChangeValueAPI.py
new file mode 100644
index 000000000000..77aefe05be46
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/value/change_values/TestChangeValueAPI.py
@@ -0,0 +1,148 @@
+"""
+Test some SBValue APIs.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ChangeValueAPITestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # We'll use the test method name as the exe_name.
+ self.exe_name = self.testMethodName
+ # Find the line number to of function 'c'.
+ self.line = line_number('main.c', '// Stop here and set values')
+ self.check_line = line_number('main.c', '// Stop here and check values')
+ self.end_line = line_number ('main.c', '// Set a breakpoint here at the end')
+
+ @expectedFailureWindows("llvm.org/pr24772")
+ @add_test_categories(['pyapi'])
+ def test_change_value(self):
+ """Exercise the SBValue::SetValueFromCString API."""
+ d = {'EXE': self.exe_name}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ exe = os.path.join(os.getcwd(), self.exe_name)
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Create the breakpoint inside function 'main'.
+ breakpoint = target.BreakpointCreateByLocation('main.c', self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Create the breakpoint inside the function 'main'
+ check_breakpoint = target.BreakpointCreateByLocation('main.c', self.check_line)
+ self.assertTrue(check_breakpoint, VALID_BREAKPOINT)
+
+ # Create the breakpoint inside function 'main'.
+ end_breakpoint = target.BreakpointCreateByLocation('main.c', self.end_line)
+ self.assertTrue(end_breakpoint, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Get Frame #0.
+ self.assertTrue(process.GetState() == lldb.eStateStopped)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
+ frame0 = thread.GetFrameAtIndex(0)
+ self.assertTrue (frame0.IsValid(), "Got a valid frame.")
+
+ # Get the val variable and change it:
+ error = lldb.SBError()
+
+ val_value = frame0.FindVariable ("val")
+ self.assertTrue (val_value.IsValid(), "Got the SBValue for val")
+ actual_value = val_value.GetValueAsSigned (error, 0);
+ self.assertTrue (error.Success(), "Got a value from val")
+ self.assertTrue (actual_value == 100, "Got the right value from val")
+
+ result = val_value.SetValueFromCString ("12345")
+ self.assertTrue (result, "Setting val returned True.")
+ actual_value = val_value.GetValueAsSigned (error, 0);
+ self.assertTrue (error.Success(), "Got a changed value from val")
+ self.assertTrue (actual_value == 12345, "Got the right changed value from val")
+
+ # Now check that we can set a structure element:
+
+ mine_value = frame0.FindVariable ("mine")
+ self.assertTrue (mine_value.IsValid(), "Got the SBValue for mine")
+
+ mine_second_value = mine_value.GetChildMemberWithName ("second_val")
+ self.assertTrue (mine_second_value.IsValid(), "Got second_val from mine")
+ actual_value = mine_second_value.GetValueAsUnsigned (error, 0)
+ self.assertTrue (error.Success(), "Got an unsigned value for second_val")
+ self.assertTrue (actual_value == 5555)
+
+ result = mine_second_value.SetValueFromCString ("98765")
+ self.assertTrue (result, "Success setting mine.second_value.")
+ actual_value = mine_second_value.GetValueAsSigned (error, 0);
+ self.assertTrue (error.Success(), "Got a changed value from mine.second_val")
+ self.assertTrue (actual_value == 98765, "Got the right changed value from mine.second_val")
+
+ # Next do the same thing with the pointer version.
+ ptr_value = frame0.FindVariable ("ptr")
+ self.assertTrue (ptr_value.IsValid(), "Got the SBValue for ptr")
+
+ ptr_second_value = ptr_value.GetChildMemberWithName ("second_val")
+ self.assertTrue (ptr_second_value.IsValid(), "Got second_val from ptr")
+ actual_value = ptr_second_value.GetValueAsUnsigned (error, 0)
+ self.assertTrue (error.Success(), "Got an unsigned value for ptr->second_val")
+ self.assertTrue (actual_value == 6666)
+
+ result = ptr_second_value.SetValueFromCString ("98765")
+ self.assertTrue (result, "Success setting ptr->second_value.")
+ actual_value = ptr_second_value.GetValueAsSigned (error, 0);
+ self.assertTrue (error.Success(), "Got a changed value from ptr->second_val")
+ self.assertTrue (actual_value == 98765, "Got the right changed value from ptr->second_val")
+
+ # gcc may set multiple locations for breakpoint
+ breakpoint.SetEnabled(False)
+
+ # Now continue, grab the stdout and make sure we changed the real values as well...
+ process.Continue();
+
+ self.assertTrue(process.GetState() == lldb.eStateStopped)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
+
+ expected_value = "Val - 12345 Mine - 55, 98765, 55555555. Ptr - 66, 98765, 66666666"
+ stdout = process.GetSTDOUT(1000)
+ self.assertTrue (expected_value in stdout, "STDOUT showed changed values.")
+
+ # Finally, change the stack pointer to 0, and we should not make it to our end breakpoint.
+ frame0 = thread.GetFrameAtIndex(0)
+ self.assertTrue (frame0.IsValid(), "Second time: got a valid frame.")
+ sp_value = frame0.FindValue ("sp", lldb.eValueTypeRegister);
+ self.assertTrue (sp_value.IsValid(), "Got a stack pointer value")
+ result = sp_value.SetValueFromCString("1")
+ self.assertTrue (result, "Setting sp returned true.")
+ actual_value = sp_value.GetValueAsUnsigned (error, 0)
+ self.assertTrue (error.Success(), "Got a changed value for sp")
+ self.assertTrue (actual_value == 1, "Got the right changed value for sp.")
+
+ # Boundary condition test the SBValue.CreateValueFromExpression() API.
+ # LLDB should not crash!
+ nosuchval = mine_value.CreateValueFromExpression(None, None)
+
+ process.Continue()
+
+ self.assertTrue(process.GetState() == lldb.eStateStopped)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread == None, "We should not have managed to hit our second breakpoint with sp == 1")
+
+ process.Kill()
diff --git a/packages/Python/lldbsuite/test/python_api/value/change_values/main.c b/packages/Python/lldbsuite/test/python_api/value/change_values/main.c
new file mode 100644
index 000000000000..01455c019647
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/value/change_values/main.c
@@ -0,0 +1,29 @@
+#include <stdio.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+struct foo
+{
+ uint8_t first_val;
+ uint32_t second_val;
+ uint64_t third_val;
+};
+
+int main ()
+{
+ int val = 100;
+ struct foo mine = {55, 5555, 55555555};
+ struct foo *ptr = (struct foo *) malloc (sizeof (struct foo));
+ ptr->first_val = 66;
+ ptr->second_val = 6666;
+ ptr->third_val = 66666666;
+
+ // Stop here and set values
+ printf ("Val - %d Mine - %d, %d, %llu. Ptr - %d, %d, %llu\n", val,
+ mine.first_val, mine.second_val, mine.third_val,
+ ptr->first_val, ptr->second_val, ptr->third_val);
+
+ // Stop here and check values
+ printf ("This is just another call which we won't make it over %d.", val);
+ return 0; // Set a breakpoint here at the end
+}
diff --git a/packages/Python/lldbsuite/test/python_api/value/linked_list/Makefile b/packages/Python/lldbsuite/test/python_api/value/linked_list/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/value/linked_list/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/value/linked_list/TestValueAPILinkedList.py b/packages/Python/lldbsuite/test/python_api/value/linked_list/TestValueAPILinkedList.py
new file mode 100644
index 000000000000..22d7e7ebf7e8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/value/linked_list/TestValueAPILinkedList.py
@@ -0,0 +1,133 @@
+"""
+Test SBValue API linked_list_iter which treats the SBValue as a linked list and
+supports iteration till the end of list is reached.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class ValueAsLinkedListTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # We'll use the test method name as the exe_name.
+ self.exe_name = self.testMethodName
+ # Find the line number to break at.
+ self.line = line_number('main.cpp', '// Break at this line')
+
+ @add_test_categories(['pyapi'])
+ def test(self):
+ """Exercise SBValue API linked_list_iter."""
+ d = {'EXE': self.exe_name}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ exe = os.path.join(os.getcwd(), self.exe_name)
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Create the breakpoint inside function 'main'.
+ breakpoint = target.BreakpointCreateByLocation('main.cpp', self.line)
+ self.assertTrue(breakpoint, VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+
+ # Get Frame #0.
+ self.assertTrue(process.GetState() == lldb.eStateStopped)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ self.assertTrue(thread.IsValid(), "There should be a thread stopped due to breakpoint condition")
+ frame0 = thread.GetFrameAtIndex(0)
+
+ # Get variable 'task_head'.
+ task_head = frame0.FindVariable('task_head')
+ self.assertTrue(task_head, VALID_VARIABLE)
+ self.DebugSBValue(task_head)
+
+ # By design (see main.cpp), the visited id's are: [1, 2, 4, 5].
+ visitedIDs = [1, 2, 4, 5]
+ list = []
+
+ cvf = lldbutil.ChildVisitingFormatter(indent_child=2)
+ for t in task_head.linked_list_iter('next'):
+ self.assertTrue(t, VALID_VARIABLE)
+ # Make sure that 'next' corresponds to an SBValue with pointer type.
+ self.assertTrue(t.TypeIsPointerType())
+ if self.TraceOn():
+ print(cvf.format(t))
+ list.append(int(t.GetChildMemberWithName("id").GetValue()))
+
+ # Sanity checks that the we visited all the items (no more, no less).
+ if self.TraceOn():
+ print("visited IDs:", list)
+ self.assertTrue(visitedIDs == list)
+
+ # Let's exercise the linked_list_iter() API again, this time supplying
+ # our end of list test function.
+ def eol(val):
+ """Test function to determine end of list."""
+ # End of list is reached if either the value object is invalid
+ # or it corresponds to a null pointer.
+ if not val or int(val.GetValue(), 16) == 0:
+ return True
+ # Also check the "id" for correct semantics. If id <= 0, the item
+ # is corrupted, let's return True to signify end of list.
+ if int(val.GetChildMemberWithName("id").GetValue(), 0) <= 0:
+ return True
+
+ # Otherwise, return False.
+ return False
+
+ list = []
+ for t in task_head.linked_list_iter('next', eol):
+ self.assertTrue(t, VALID_VARIABLE)
+ # Make sure that 'next' corresponds to an SBValue with pointer type.
+ self.assertTrue(t.TypeIsPointerType())
+ if self.TraceOn():
+ print(cvf.format(t))
+ list.append(int(t.GetChildMemberWithName("id").GetValue()))
+
+ # Sanity checks that the we visited all the items (no more, no less).
+ if self.TraceOn():
+ print("visited IDs:", list)
+ self.assertTrue(visitedIDs == list)
+
+ # Get variable 'empty_task_head'.
+ empty_task_head = frame0.FindVariable('empty_task_head')
+ self.assertTrue(empty_task_head, VALID_VARIABLE)
+ self.DebugSBValue(empty_task_head)
+
+ list = []
+ # There is no iterable item from empty_task_head.linked_list_iter().
+ for t in empty_task_head.linked_list_iter('next', eol):
+ if self.TraceOn():
+ print(cvf.format(t))
+ list.append(int(t.GetChildMemberWithName("id").GetValue()))
+
+ self.assertTrue(len(list) == 0)
+
+ # Get variable 'task_evil'.
+ task_evil = frame0.FindVariable('task_evil')
+ self.assertTrue(task_evil, VALID_VARIABLE)
+ self.DebugSBValue(task_evil)
+
+ list = []
+ # There 3 iterable items from task_evil.linked_list_iter(). :-)
+ for t in task_evil.linked_list_iter('next'):
+ if self.TraceOn():
+ print(cvf.format(t))
+ list.append(int(t.GetChildMemberWithName("id").GetValue()))
+
+ self.assertTrue(len(list) == 3)
diff --git a/packages/Python/lldbsuite/test/python_api/value/linked_list/main.cpp b/packages/Python/lldbsuite/test/python_api/value/linked_list/main.cpp
new file mode 100644
index 000000000000..50517f487749
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/value/linked_list/main.cpp
@@ -0,0 +1,56 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+class Task {
+public:
+ int id;
+ Task *next;
+ Task(int i, Task *n):
+ id(i),
+ next(n)
+ {}
+};
+
+
+int main (int argc, char const *argv[])
+{
+ Task *task_head = NULL;
+ Task *task1 = new Task(1, NULL);
+ Task *task2 = new Task(2, NULL);
+ Task *task3 = new Task(3, NULL); // Orphaned.
+ Task *task4 = new Task(4, NULL);
+ Task *task5 = new Task(5, NULL);
+
+ task_head = task1;
+ task1->next = task2;
+ task2->next = task4;
+ task4->next = task5;
+
+ int total = 0;
+ Task *t = task_head;
+ while (t != NULL) {
+ if (t->id >= 0)
+ ++total;
+ t = t->next;
+ }
+ printf("We have a total number of %d tasks\n", total);
+
+ // This corresponds to an empty task list.
+ Task *empty_task_head = NULL;
+
+ Task *task_evil = new Task(1, NULL);
+ Task *task_2 = new Task(2, NULL);
+ Task *task_3 = new Task(3, NULL);
+ task_evil->next = task_2;
+ task_2->next = task_3;
+ task_3->next = task_evil; // In order to cause inifinite loop. :-)
+
+ return 0; // Break at this line
+}
diff --git a/packages/Python/lldbsuite/test/python_api/value/main.c b/packages/Python/lldbsuite/test/python_api/value/main.c
new file mode 100644
index 000000000000..a00795750de0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/value/main.c
@@ -0,0 +1,52 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+
+// This simple program is to test the lldb Python API SBValue.GetChildAtIndex().
+
+int g_my_int = 100;
+
+const char *days_of_week[7] = { "Sunday",
+ "Monday",
+ "Tuesday",
+ "Wednesday",
+ "Thursday",
+ "Friday",
+ "Saturday" };
+
+const char *weekdays[5] = { "Monday",
+ "Tuesday",
+ "Wednesday",
+ "Thursday",
+ "Friday" };
+
+const char **g_table[2] = { days_of_week, weekdays };
+
+typedef int MyInt;
+
+struct MyStruct
+{
+ int a;
+ int b;
+};
+
+int main (int argc, char const *argv[])
+{
+ int i;
+ MyInt a = 12345;
+ struct MyStruct s = { 11, 22 };
+ int *my_int_ptr = &g_my_int;
+ printf("my_int_ptr points to location %p\n", my_int_ptr);
+ const char **str_ptr = days_of_week;
+ for (i = 0; i < 7; ++i)
+ printf("%s\n", str_ptr[i]); // Break at this line
+ // and do str_ptr_val.GetChildAtIndex(5, lldb.eNoDynamicValues, True).
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/python_api/value_var_update/Makefile b/packages/Python/lldbsuite/test/python_api/value_var_update/Makefile
new file mode 100644
index 000000000000..4b0e5814e3e3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/value_var_update/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+CFLAGS_EXTRAS += -std=c99
+# See TestHelloWorld.py, which specifies the executable name with a dictionary.
+EXE := hello_world
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/value_var_update/TestValueVarUpdate.py b/packages/Python/lldbsuite/test/python_api/value_var_update/TestValueVarUpdate.py
new file mode 100644
index 000000000000..251bbcf4b24d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/value_var_update/TestValueVarUpdate.py
@@ -0,0 +1,59 @@
+"""Test SBValue::GetValueDidChange"""
+
+from __future__ import print_function
+
+
+
+import os, sys, time
+import lldb
+import time
+from lldbsuite.test.lldbtest import *
+
+class HelloWorldTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Get the full path to our executable to be attached/debugged.
+ self.exe = os.path.join(os.getcwd(), self.testMethodName)
+ self.d = {'EXE': self.testMethodName}
+
+ @add_test_categories(['pyapi'])
+ def test_with_process_launch_api(self):
+ """Test SBValue::GetValueDidChange"""
+ self.build(dictionary=self.d)
+ self.setTearDownCleanup(dictionary=self.d)
+ target = self.dbg.CreateTarget(self.exe)
+
+ breakpoint = target.BreakpointCreateBySourceRegex("break here", lldb.SBFileSpec("main.c"))
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'stop reason = breakpoint'])
+
+ i = self.frame().FindVariable("i")
+ i_val = i.GetValueAsUnsigned(0)
+ c = self.frame().FindVariable("c")
+
+ # Update any values from the SBValue objects so we can ask them if they changed after a continue
+ i.GetValueDidChange()
+ c.GetChildAtIndex(1).GetValueDidChange()
+ c.GetChildAtIndex(0).GetChildAtIndex(0).GetValueDidChange()
+
+ if self.TraceOn(): self.runCmd("frame variable")
+
+ self.runCmd("continue")
+
+ if self.TraceOn(): self.runCmd("frame variable")
+
+ self.assertTrue(i_val != i.GetValueAsUnsigned(0), "GetValue() is saying a lie")
+ self.assertTrue(i.GetValueDidChange(), "GetValueDidChange() is saying a lie")
+
+ # Check complex type
+ self.assertTrue(c.GetChildAtIndex(0).GetChildAtIndex(0).GetValueDidChange() and
+ not c.GetChildAtIndex(1).GetValueDidChange(), "GetValueDidChange() is saying a lie")
diff --git a/packages/Python/lldbsuite/test/python_api/value_var_update/main.c b/packages/Python/lldbsuite/test/python_api/value_var_update/main.c
new file mode 100644
index 000000000000..9ffca5cbb9f8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/value_var_update/main.c
@@ -0,0 +1,15 @@
+struct complex_type {
+ struct { long l; } inner;
+ struct complex_type *complex_ptr;
+};
+
+int main() {
+ int i = 0;
+ struct complex_type c = { { 1L }, &c };
+ for (int j = 3; j < 20; j++)
+ {
+ c.inner.l += (i += j);
+ i = i - 1; // break here
+ }
+ return i;
+}
diff --git a/packages/Python/lldbsuite/test/python_api/watchpoint/Makefile b/packages/Python/lldbsuite/test/python_api/watchpoint/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/watchpoint/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/watchpoint/TestSetWatchpoint.py b/packages/Python/lldbsuite/test/python_api/watchpoint/TestSetWatchpoint.py
new file mode 100644
index 000000000000..264e21240dd9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/watchpoint/TestSetWatchpoint.py
@@ -0,0 +1,93 @@
+"""
+Use lldb Python SBValue API to create a watchpoint for read_write of 'globl' var.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class SetWatchpointAPITestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Our simple source filename.
+ self.source = 'main.c'
+ # Find the line number to break inside main().
+ self.line = line_number(self.source, '// Set break point at this line.')
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446") # WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows
+ def test_watch_val(self):
+ """Exercise SBValue.Watch() API to set a watchpoint."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create a breakpoint on main.c.
+ breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ # We should be stopped due to the breakpoint. Get frame #0.
+ process = target.GetProcess()
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ frame0 = thread.GetFrameAtIndex(0)
+
+ # Watch 'global' for read and write.
+ value = frame0.FindValue('global', lldb.eValueTypeVariableGlobal)
+ error = lldb.SBError();
+ watchpoint = value.Watch(True, True, True, error)
+ self.assertTrue(value and watchpoint,
+ "Successfully found the variable and set a watchpoint")
+ self.DebugSBValue(value)
+
+ # Hide stdout if not running with '-t' option.
+ if not self.TraceOn():
+ self.HideStdout()
+
+ print(watchpoint)
+
+ # Continue. Expect the program to stop due to the variable being written to.
+ process.Continue()
+
+ if (self.TraceOn()):
+ lldbutil.print_stacktraces(process)
+
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint)
+ self.assertTrue(thread, "The thread stopped due to watchpoint")
+ self.DebugSBValue(value)
+
+ # Continue. Expect the program to stop due to the variable being read from.
+ process.Continue()
+
+ if (self.TraceOn()):
+ lldbutil.print_stacktraces(process)
+
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint)
+ self.assertTrue(thread, "The thread stopped due to watchpoint")
+ self.DebugSBValue(value)
+
+ # Continue the process. We don't expect the program to be stopped again.
+ process.Continue()
+
+ # At this point, the inferior process should have exited.
+ self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED)
diff --git a/packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIgnoreCount.py b/packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIgnoreCount.py
new file mode 100644
index 000000000000..a15e73347030
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIgnoreCount.py
@@ -0,0 +1,89 @@
+"""
+Use lldb Python SBWatchpoint API to set the ignore count.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class WatchpointIgnoreCountTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Our simple source filename.
+ self.source = 'main.c'
+ # Find the line number to break inside main().
+ self.line = line_number(self.source, '// Set break point at this line.')
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446") # WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows
+ def test_set_watch_ignore_count(self):
+ """Test SBWatchpoint.SetIgnoreCount() API."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Create a breakpoint on main.c in order to set our watchpoint later.
+ breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ # We should be stopped due to the breakpoint. Get frame #0.
+ process = target.GetProcess()
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ frame0 = thread.GetFrameAtIndex(0)
+
+ # Watch 'global' for read and write.
+ value = frame0.FindValue('global', lldb.eValueTypeVariableGlobal)
+ error = lldb.SBError();
+ watchpoint = value.Watch(True, True, True, error)
+ self.assertTrue(value and watchpoint,
+ "Successfully found the variable and set a watchpoint")
+ self.DebugSBValue(value)
+
+ # Hide stdout if not running with '-t' option.
+ if not self.TraceOn():
+ self.HideStdout()
+
+ # There should be only 1 watchpoint location under the target.
+ self.assertTrue(target.GetNumWatchpoints() == 1)
+ watchpoint = target.GetWatchpointAtIndex(0)
+ self.assertTrue(watchpoint.IsEnabled())
+ self.assertTrue(watchpoint.GetIgnoreCount() == 0)
+ watch_id = watchpoint.GetID()
+ self.assertTrue(watch_id != 0)
+ print(watchpoint)
+
+ # Now immediately set the ignore count to 2. When we continue, expect the
+ # inferior to run to its completion without stopping due to watchpoint.
+ watchpoint.SetIgnoreCount(2)
+ print(watchpoint)
+ process.Continue()
+
+ # At this point, the inferior process should have exited.
+ self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED)
+
+ # Verify some vital statistics.
+ self.assertTrue(watchpoint)
+ self.assertTrue(watchpoint.GetWatchSize() == 4)
+ self.assertTrue(watchpoint.GetHitCount() == 2)
+ print(watchpoint)
diff --git a/packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIter.py b/packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIter.py
new file mode 100644
index 000000000000..315450280675
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/watchpoint/TestWatchpointIter.py
@@ -0,0 +1,115 @@
+"""
+Use lldb Python SBTarget API to iterate on the watchpoint(s) for the target.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class WatchpointIteratorTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Our simple source filename.
+ self.source = 'main.c'
+ # Find the line number to break inside main().
+ self.line = line_number(self.source, '// Set break point at this line.')
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446") # WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows
+ def test_watch_iter(self):
+ """Exercise SBTarget.watchpoint_iter() API to iterate on the available watchpoints."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Create a breakpoint on main.c in order to set our watchpoint later.
+ breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ # We should be stopped due to the breakpoint. Get frame #0.
+ process = target.GetProcess()
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ frame0 = thread.GetFrameAtIndex(0)
+
+ # Watch 'global' for read and write.
+ value = frame0.FindValue('global', lldb.eValueTypeVariableGlobal)
+ error = lldb.SBError();
+ watchpoint = value.Watch(True, True, True, error)
+ self.assertTrue(value and watchpoint,
+ "Successfully found the variable and set a watchpoint")
+ self.DebugSBValue(value)
+
+ # Hide stdout if not running with '-t' option.
+ if not self.TraceOn():
+ self.HideStdout()
+
+ # There should be only 1 watchpoint location under the target.
+ self.assertTrue(target.GetNumWatchpoints() == 1)
+ self.assertTrue(watchpoint.IsEnabled())
+ watch_id = watchpoint.GetID()
+ self.assertTrue(watch_id != 0)
+
+ # Continue. Expect the program to stop due to the variable being written to.
+ process.Continue()
+
+ # Hide stdout if not running with '-t' option.
+ if not self.TraceOn():
+ self.HideStdout()
+
+ # Print the stack traces.
+ lldbutil.print_stacktraces(process)
+
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint)
+ self.assertTrue(thread, "The thread stopped due to watchpoint")
+ self.DebugSBValue(value)
+
+ # We currently only support hardware watchpoint. Verify that we have a
+ # meaningful hardware index at this point. Exercise the printed repr of
+ # SBWatchpointLocation.
+ print(watchpoint)
+ self.assertTrue(watchpoint.GetHardwareIndex() != -1)
+
+ # SBWatchpoint.GetDescription() takes a description level arg.
+ print(lldbutil.get_description(watchpoint, lldb.eDescriptionLevelFull))
+
+ # Now disable the 'rw' watchpoint. The program won't stop when it reads
+ # 'global' next.
+ watchpoint.SetEnabled(False)
+ self.assertTrue(watchpoint.GetHardwareIndex() == -1)
+ self.assertFalse(watchpoint.IsEnabled())
+
+ # Continue. The program does not stop again when the variable is being
+ # read from because the watchpoint location has been disabled.
+ process.Continue()
+
+ # At this point, the inferior process should have exited.
+ self.assertTrue(process.GetState() == lldb.eStateExited, PROCESS_EXITED)
+
+ # Verify some vital statistics and exercise the iterator API.
+ for watchpoint in target.watchpoint_iter():
+ self.assertTrue(watchpoint)
+ self.assertTrue(watchpoint.GetWatchSize() == 4)
+ self.assertTrue(watchpoint.GetHitCount() == 1)
+ print(watchpoint)
+
diff --git a/packages/Python/lldbsuite/test/python_api/watchpoint/condition/Makefile b/packages/Python/lldbsuite/test/python_api/watchpoint/condition/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/watchpoint/condition/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/watchpoint/condition/TestWatchpointConditionAPI.py b/packages/Python/lldbsuite/test/python_api/watchpoint/condition/TestWatchpointConditionAPI.py
new file mode 100644
index 000000000000..f30bf856aa07
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/watchpoint/condition/TestWatchpointConditionAPI.py
@@ -0,0 +1,89 @@
+"""
+Test watchpoint condition API.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class WatchpointConditionAPITestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Our simple source filename.
+ self.source = 'main.cpp'
+ # Find the line number to break inside main().
+ self.line = line_number(self.source, '// Set break point at this line.')
+ # And the watchpoint variable declaration line number.
+ self.decl = line_number(self.source, '// Watchpoint variable declaration.')
+ # Build dictionary to have unique executable names for each test method.
+ self.exe_name = self.testMethodName
+ self.d = {'CXX_SOURCES': self.source, 'EXE': self.exe_name}
+
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @skipIfWindows # Watchpoints not supported on Windows, and this test hangs
+ def test_watchpoint_cond_api(self):
+ """Test watchpoint condition API."""
+ self.build(dictionary=self.d)
+ self.setTearDownCleanup(dictionary=self.d)
+ exe = os.path.join(os.getcwd(), self.exe_name)
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create a breakpoint on main.c.
+ breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ # We should be stopped due to the breakpoint. Get frame #0.
+ process = target.GetProcess()
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ frame0 = thread.GetFrameAtIndex(0)
+
+ # Watch 'global' for write.
+ value = frame0.FindValue('global', lldb.eValueTypeVariableGlobal)
+ error = lldb.SBError();
+ watchpoint = value.Watch(True, False, True, error)
+ self.assertTrue(value and watchpoint,
+ "Successfully found the variable and set a watchpoint")
+ self.DebugSBValue(value)
+
+ # Now set the condition as "global==5".
+ watchpoint.SetCondition('global==5')
+ self.expect(watchpoint.GetCondition(), exe=False,
+ startstr = 'global==5')
+
+ # Hide stdout if not running with '-t' option.
+ if not self.TraceOn():
+ self.HideStdout()
+
+ print(watchpoint)
+
+ # Continue. Expect the program to stop due to the variable being written to.
+ process.Continue()
+
+ if (self.TraceOn()):
+ lldbutil.print_stacktraces(process)
+
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint)
+ self.assertTrue(thread, "The thread stopped due to watchpoint")
+ self.DebugSBValue(value)
+
+ # Verify that the condition is met.
+ self.assertTrue(value.GetValueAsUnsigned() == 5)
diff --git a/packages/Python/lldbsuite/test/python_api/watchpoint/condition/main.cpp b/packages/Python/lldbsuite/test/python_api/watchpoint/condition/main.cpp
new file mode 100644
index 000000000000..f4c3527f8af2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/watchpoint/condition/main.cpp
@@ -0,0 +1,28 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+#include <stdint.h>
+
+int32_t global = 0; // Watchpoint variable declaration.
+
+static void modify(int32_t &var) {
+ ++var;
+}
+
+int main(int argc, char** argv) {
+ int local = 0;
+ printf("&global=%p\n", &global);
+ printf("about to write to 'global'...\n"); // Set break point at this line.
+ // When stopped, watch 'global',
+ // for the condition "global == 5".
+ for (int i = 0; i < 10; ++i)
+ modify(global);
+
+ printf("global=%d\n", global);
+}
diff --git a/packages/Python/lldbsuite/test/python_api/watchpoint/main.c b/packages/Python/lldbsuite/test/python_api/watchpoint/main.c
new file mode 100644
index 000000000000..4753edfba991
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/watchpoint/main.c
@@ -0,0 +1,24 @@
+//===-- main.c --------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+#include <stdio.h>
+#include <stdint.h>
+
+int32_t global = 10; // Watchpoint variable declaration.
+
+int main(int argc, char** argv) {
+ int local = 0;
+ printf("&global=%p\n", &global);
+ printf("about to write to 'global'...\n"); // Set break point at this line.
+ // When stopped, watch 'global' for read&write.
+ global = 20;
+ local += argc;
+ ++local;
+ printf("local: %d\n", local);
+ printf("global=%d\n", global);
+}
diff --git a/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/Makefile b/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/Makefile
new file mode 100644
index 000000000000..8817fff55e8c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/Makefile
@@ -0,0 +1,6 @@
+LEVEL = ../../../make
+
+ENABLE_THREADS := YES
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestSetWatchlocation.py b/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestSetWatchlocation.py
new file mode 100644
index 000000000000..5a4a464657d6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestSetWatchlocation.py
@@ -0,0 +1,90 @@
+"""
+Use lldb Python SBValue.WatchPointee() API to create a watchpoint for write of '*g_char_ptr'.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class SetWatchlocationAPITestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Our simple source filename.
+ self.source = 'main.cpp'
+ # Find the line number to break inside main().
+ self.line = line_number(self.source, '// Set break point at this line.')
+ # This is for verifying that watch location works.
+ self.violating_func = "do_bad_thing_with_location";
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446") # WINDOWS XFAIL TRIAGE - Watchpoints not supported on Windows
+ def test_watch_location(self):
+ """Exercise SBValue.WatchPointee() API to set a watchpoint."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create a breakpoint on main.c.
+ breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ # We should be stopped due to the breakpoint. Get frame #0.
+ process = target.GetProcess()
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ frame0 = thread.GetFrameAtIndex(0)
+
+ value = frame0.FindValue('g_char_ptr',
+ lldb.eValueTypeVariableGlobal)
+ pointee = value.CreateValueFromAddress("pointee",
+ value.GetValueAsUnsigned(0),
+ value.GetType().GetPointeeType())
+ # Watch for write to *g_char_ptr.
+ error = lldb.SBError();
+ watchpoint = value.WatchPointee(True, False, True, error)
+ self.assertTrue(value and watchpoint,
+ "Successfully found the pointer and set a watchpoint")
+ self.DebugSBValue(value)
+ self.DebugSBValue(pointee)
+
+ # Hide stdout if not running with '-t' option.
+ if not self.TraceOn():
+ self.HideStdout()
+
+ print(watchpoint)
+
+ # Continue. Expect the program to stop due to the variable being written to.
+ process.Continue()
+
+ if (self.TraceOn()):
+ lldbutil.print_stacktraces(process)
+
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint)
+ self.assertTrue(thread, "The thread stopped due to watchpoint")
+ self.DebugSBValue(value)
+ self.DebugSBValue(pointee)
+
+ self.expect(lldbutil.print_stacktrace(thread, string_buffer=True), exe=False,
+ substrs = [self.violating_func])
+
+ # This finishes our test.
diff --git a/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestTargetWatchAddress.py b/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestTargetWatchAddress.py
new file mode 100644
index 000000000000..6facbaa8f2e9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/TestTargetWatchAddress.py
@@ -0,0 +1,130 @@
+"""
+Use lldb Python SBtarget.WatchAddress() API to create a watchpoint for write of '*g_char_ptr'.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time
+import re
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+from lldbsuite.test.lldbtest import *
+
+class TargetWatchAddressAPITestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Our simple source filename.
+ self.source = 'main.cpp'
+ # Find the line number to break inside main().
+ self.line = line_number(self.source, '// Set break point at this line.')
+ # This is for verifying that watch location works.
+ self.violating_func = "do_bad_thing_with_location";
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @expectedFailureWindows("llvm.org/pr24446")
+ def test_watch_address(self):
+ """Exercise SBTarget.WatchAddress() API to set a watchpoint."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create a breakpoint on main.c.
+ breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ # We should be stopped due to the breakpoint. Get frame #0.
+ process = target.GetProcess()
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ frame0 = thread.GetFrameAtIndex(0)
+
+ value = frame0.FindValue('g_char_ptr',
+ lldb.eValueTypeVariableGlobal)
+ pointee = value.CreateValueFromAddress("pointee",
+ value.GetValueAsUnsigned(0),
+ value.GetType().GetPointeeType())
+ # Watch for write to *g_char_ptr.
+ error = lldb.SBError();
+ watchpoint = target.WatchAddress(value.GetValueAsUnsigned(), 1, False, True, error)
+ self.assertTrue(value and watchpoint,
+ "Successfully found the pointer and set a watchpoint")
+ self.DebugSBValue(value)
+ self.DebugSBValue(pointee)
+
+ # Hide stdout if not running with '-t' option.
+ if not self.TraceOn():
+ self.HideStdout()
+
+ print(watchpoint)
+
+ # Continue. Expect the program to stop due to the variable being written to.
+ process.Continue()
+
+ if (self.TraceOn()):
+ lldbutil.print_stacktraces(process)
+
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonWatchpoint)
+ self.assertTrue(thread, "The thread stopped due to watchpoint")
+ self.DebugSBValue(value)
+ self.DebugSBValue(pointee)
+
+ self.expect(lldbutil.print_stacktrace(thread, string_buffer=True), exe=False,
+ substrs = [self.violating_func])
+
+ # This finishes our test.
+
+ @add_test_categories(['pyapi'])
+ @expectedFailureAndroid(archs=['arm', 'aarch64']) # Watchpoints not supported
+ @skipIf(archs=['mips', 'mipsel', 'mips64', 'mips64el']) # No size constraint on MIPS for watches
+ def test_watch_address_with_invalid_watch_size(self):
+ """Exercise SBTarget.WatchAddress() API but pass an invalid watch_size."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+
+ # Create a target by the debugger.
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Now create a breakpoint on main.c.
+ breakpoint = target.BreakpointCreateByLocation(self.source, self.line)
+ self.assertTrue(breakpoint and
+ breakpoint.GetNumLocations() == 1,
+ VALID_BREAKPOINT)
+
+ # Now launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ # We should be stopped due to the breakpoint. Get frame #0.
+ process = target.GetProcess()
+ self.assertTrue(process.GetState() == lldb.eStateStopped,
+ PROCESS_STOPPED)
+ thread = lldbutil.get_stopped_thread(process, lldb.eStopReasonBreakpoint)
+ frame0 = thread.GetFrameAtIndex(0)
+
+ value = frame0.FindValue('g_char_ptr',
+ lldb.eValueTypeVariableGlobal)
+ pointee = value.CreateValueFromAddress("pointee",
+ value.GetValueAsUnsigned(0),
+ value.GetType().GetPointeeType())
+ # Watch for write to *g_char_ptr.
+ error = lldb.SBError();
+ watchpoint = target.WatchAddress(value.GetValueAsUnsigned(), 365, False, True, error)
+ self.assertFalse(watchpoint)
+ self.expect(error.GetCString(), exe=False,
+ substrs = ['watch size of %d is not supported' % 365])
diff --git a/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/main.cpp b/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/main.cpp
new file mode 100644
index 000000000000..a197a92a4814
--- /dev/null
+++ b/packages/Python/lldbsuite/test/python_api/watchpoint/watchlocation/main.cpp
@@ -0,0 +1,104 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <chrono>
+#include <condition_variable>
+#include <cstdio>
+#include <random>
+#include <thread>
+
+std::default_random_engine g_random_engine{std::random_device{}()};
+std::uniform_int_distribution<> g_distribution{0, 3000000};
+std::condition_variable g_condition_variable;
+std::mutex g_mutex;
+int g_count;
+
+char *g_char_ptr = nullptr;
+
+void
+barrier_wait()
+{
+ std::unique_lock<std::mutex> lock{g_mutex};
+ if (--g_count > 0)
+ g_condition_variable.wait(lock);
+ else
+ g_condition_variable.notify_all();
+}
+
+void
+do_bad_thing_with_location(char *char_ptr, char new_val)
+{
+ *char_ptr = new_val;
+}
+
+uint32_t
+access_pool (bool flag = false)
+{
+ static std::mutex g_access_mutex;
+ if (!flag)
+ g_access_mutex.lock();
+
+ char old_val = *g_char_ptr;
+ if (flag)
+ do_bad_thing_with_location(g_char_ptr, old_val + 1);
+
+ if (!flag)
+ g_access_mutex.unlock();
+ return *g_char_ptr;
+}
+
+void
+thread_func (uint32_t thread_index)
+{
+ printf ("%s (thread index = %u) startng...\n", __FUNCTION__, thread_index);
+
+ barrier_wait();
+
+ uint32_t count = 0;
+ uint32_t val;
+ while (count++ < 15)
+ {
+ // random micro second sleep from zero to 3 seconds
+ int usec = g_distribution(g_random_engine);
+ printf ("%s (thread = %u) doing a usleep (%d)...\n", __FUNCTION__, thread_index, usec);
+ std::this_thread::sleep_for(std::chrono::microseconds{usec});
+
+ if (count < 7)
+ val = access_pool ();
+ else
+ val = access_pool (true);
+
+ printf ("%s (thread = %u) after usleep access_pool returns %d (count=%d)...\n", __FUNCTION__, thread_index, val, count);
+ }
+ printf ("%s (thread index = %u) exiting...\n", __FUNCTION__, thread_index);
+}
+
+
+int main (int argc, char const *argv[])
+{
+ g_count = 4;
+ std::thread threads[3];
+
+ g_char_ptr = new char{};
+
+ // Create 3 threads
+ for (auto &thread : threads)
+ thread = std::thread{thread_func, std::distance(threads, &thread)};
+
+ printf ("Before turning all three threads loose...\n"); // Set break point at this line.
+ barrier_wait();
+
+ // Join all of our threads
+ for (auto &thread : threads)
+ thread.join();
+
+ delete g_char_ptr;
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/redo.py b/packages/Python/lldbsuite/test/redo.py
new file mode 100644
index 000000000000..e4eba8b27860
--- /dev/null
+++ b/packages/Python/lldbsuite/test/redo.py
@@ -0,0 +1,195 @@
+#!/usr/bin/env python
+
+"""
+A simple utility to redo the failed/errored tests.
+
+You need to specify the session directory in order for this script to locate the
+tests which need to be re-run.
+
+See also dotest.py, the test driver running the test suite.
+
+Type:
+
+./dotest.py -h
+
+for help.
+"""
+
+from __future__ import print_function
+
+import os, sys, datetime
+import re
+
+# If True, redo with no '-t' option for the test driver.
+no_trace = False
+
+# To be filled with the filterspecs found in the session logs.
+redo_specs = []
+
+# The filename components to match for. Only files with the contained component names
+# will be considered for re-run. Examples: ['X86_64', 'clang'].
+filename_components = []
+
+do_delay = False
+
+# There is a known bug with respect to comp_specs and arch_specs, in that if we
+# encountered "-C clang" and "-C gcc" when visiting the session files, both
+# compilers will end up in the invocation of the test driver when rerunning.
+# That is: ./dotest -v -C clang^gcc ... -f ...". Ditto for "-A" flags.
+
+# The "-C compiler" for comp_specs.
+comp_specs = set()
+# The "-A arch" for arch_specs.
+arch_specs = set()
+
+def usage():
+ print("""\
+Usage: redo.py [-F filename_component] [-n] [session_dir] [-d]
+where options:
+-F : only consider the test for re-run if the session filename contains the filename component
+ for example: -F x86_64
+-n : when running the tests, do not turn on trace mode, i.e, no '-t' option
+ is passed to the test driver (this will run the tests faster)
+-d : pass -d down to the test driver (introduces a delay so you can attach with a debugger)
+
+and session_dir specifies the session directory which contains previously
+recorded session infos for all the test cases which either failed or errored.
+
+If sessin_dir is left unspecified, this script uses the heuristic to find the
+possible session directories with names starting with %Y-%m-%d- (for example,
+2012-01-23-) and employs the one with the latest timestamp.""")
+ sys.exit(0)
+
+def where(session_dir, test_dir):
+ """Returns the full path to the session directory; None if non-existent."""
+ abspath = os.path.abspath(session_dir)
+ if os.path.isdir(abspath):
+ return abspath
+
+ session_dir_path = os.path.join(test_dir, session_dir)
+ if os.path.isdir(session_dir_path):
+ return session_dir_path
+
+ return None
+
+# This is the pattern for the line from the log file to redo a test.
+# We want the filter spec.
+filter_pattern = re.compile("^\./dotest\.py.*-f (.*)$")
+comp_pattern = re.compile(" -C ([^ ]+) ")
+arch_pattern = re.compile(" -A ([^ ]+) ")
+def redo(suffix, dir, names):
+ """Visitor function for os.path.walk(path, visit, arg)."""
+ global redo_specs
+ global comp_specs
+ global arch_specs
+ global filter_pattern
+ global comp_pattern
+ global arch_pattern
+ global filename_components
+ global do_delay
+
+ for name in names:
+ if name.endswith(suffix):
+ #print("Find a log file:", name)
+ if name.startswith("Error") or name.startswith("Failure"):
+ if filename_components:
+ if not all([comp in name for comp in filename_components]):
+ continue
+ with open(os.path.join(dir, name), 'r') as log:
+ content = log.read()
+ for line in content.splitlines():
+ match = filter_pattern.match(line)
+ if match:
+ filterspec = match.group(1)
+ print("adding filterspec:", filterspec)
+ redo_specs.append(filterspec)
+ comp = comp_pattern.search(line)
+ if comp:
+ comp_specs.add(comp.group(1))
+ arch = arch_pattern.search(line)
+ if arch:
+ arch_specs.add(arch.group(1))
+ else:
+ continue
+
+def main():
+ """Read the session directory and run the failed test cases one by one."""
+ global no_trace
+ global redo_specs
+ global filename_components
+ global do_delay
+
+ test_dir = sys.path[0]
+ if not test_dir:
+ test_dir = os.getcwd()
+ if not test_dir.endswith('test'):
+ print("This script expects to reside in lldb's test directory.")
+ sys.exit(-1)
+
+ index = 1
+ while index < len(sys.argv):
+ if sys.argv[index].startswith('-h') or sys.argv[index].startswith('--help'):
+ usage()
+
+ if sys.argv[index].startswith('-'):
+ # We should continue processing...
+ pass
+ else:
+ # End of option processing.
+ break
+
+ if sys.argv[index] == '-F':
+ # Increment by 1 to fetch the filename component spec.
+ index += 1
+ if index >= len(sys.argv) or sys.argv[index].startswith('-'):
+ usage()
+ filename_components.append(sys.argv[index])
+ elif sys.argv[index] == '-n':
+ no_trace = True
+ elif sys.argv[index] == '-d':
+ do_delay = True
+
+ index += 1
+
+ if index < len(sys.argv):
+ # Get the specified session directory.
+ session_dir = sys.argv[index]
+ else:
+ # Use heuristic to find the latest session directory.
+ name = datetime.datetime.now().strftime("%Y-%m-%d-")
+ dirs = [d for d in os.listdir(os.getcwd()) if d.startswith(name)]
+ if len(dirs) == 0:
+ print("No default session directory found, please specify it explicitly.")
+ usage()
+ session_dir = max(dirs, key=os.path.getmtime)
+ if not session_dir or not os.path.exists(session_dir):
+ print("No default session directory found, please specify it explicitly.")
+ usage()
+
+ #print("The test directory:", test_dir)
+ session_dir_path = where(session_dir, test_dir)
+
+ print("Using session dir path:", session_dir_path)
+ os.chdir(test_dir)
+ os.path.walk(session_dir_path, redo, ".log")
+
+ if not redo_specs:
+ print("No failures/errors recorded within the session directory, please specify a different session directory.\n")
+ usage()
+
+ filters = " -f ".join(redo_specs)
+ compilers = ''
+ for comp in comp_specs:
+ compilers += " -C %s" % (comp)
+ archs = ''
+ for arch in arch_specs:
+ archs += "--arch %s " % (arch)
+
+ command = "./dotest.py %s %s -v %s %s -f " % (compilers, archs, "" if no_trace else "-t", "-d" if do_delay else "")
+
+
+ print("Running %s" % (command + filters))
+ os.system(command + filters)
+
+if __name__ == '__main__':
+ main()
diff --git a/packages/Python/lldbsuite/test/result_formatter.py b/packages/Python/lldbsuite/test/result_formatter.py
new file mode 100644
index 000000000000..44474918895e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/result_formatter.py
@@ -0,0 +1,1304 @@
+"""
+ The LLVM Compiler Infrastructure
+
+This file is distributed under the University of Illinois Open Source
+License. See LICENSE.TXT for details.
+
+Provides classes used by the test results reporting infrastructure
+within the LLDB test suite.
+"""
+
+from __future__ import print_function
+from __future__ import absolute_import
+
+# System modules
+import argparse
+import importlib
+import inspect
+import os
+import pprint
+import socket
+import sys
+import threading
+import time
+import traceback
+
+# Third-party modules
+import six
+from six.moves import cPickle
+
+# LLDB modules
+from . import configuration
+
+import lldbsuite
+
+
+# Ignore method count on DTOs.
+# pylint: disable=too-few-public-methods
+class FormatterConfig(object):
+ """Provides formatter configuration info to create_results_formatter()."""
+ def __init__(self):
+ self.filename = None
+ self.port = None
+ self.formatter_name = None
+ self.formatter_options = None
+
+
+# Ignore method count on DTOs.
+# pylint: disable=too-few-public-methods
+class CreatedFormatter(object):
+ """Provides transfer object for returns from create_results_formatter()."""
+ def __init__(self, formatter, cleanup_func):
+ self.formatter = formatter
+ self.cleanup_func = cleanup_func
+
+
+def create_results_formatter(config):
+ """Sets up a test results formatter.
+
+ @param config an instance of FormatterConfig
+ that indicates how to setup the ResultsFormatter.
+
+ @return an instance of CreatedFormatter.
+ """
+ def create_socket(port):
+ """Creates a socket to the localhost on the given port.
+
+ @param port the port number of the listenering port on
+ the localhost.
+
+ @return (socket object, socket closing function)
+ """
+ def socket_closer(open_sock):
+ """Close down an opened socket properly."""
+ open_sock.shutdown(socket.SHUT_RDWR)
+ open_sock.close()
+
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ sock.connect(("localhost", port))
+ return (sock, lambda: socket_closer(sock))
+
+ default_formatter_name = None
+ results_file_object = None
+ cleanup_func = None
+
+ if config.filename:
+ # Open the results file for writing.
+ if config.filename == 'stdout':
+ results_file_object = sys.stdout
+ cleanup_func = None
+ elif config.filename == 'stderr':
+ results_file_object = sys.stderr
+ cleanup_func = None
+ else:
+ results_file_object = open(config.filename, "w")
+ cleanup_func = results_file_object.close
+ default_formatter_name = (
+ "lldbsuite.test.xunit_formatter.XunitFormatter")
+ elif config.port:
+ # Connect to the specified localhost port.
+ results_file_object, cleanup_func = create_socket(config.port)
+ default_formatter_name = (
+ "lldbsuite.test.result_formatter.RawPickledFormatter")
+
+ # If we have a results formatter name specified and we didn't specify
+ # a results file, we should use stdout.
+ if config.formatter_name is not None and results_file_object is None:
+ # Use stdout.
+ results_file_object = sys.stdout
+ cleanup_func = None
+
+ if results_file_object:
+ # We care about the formatter. Choose user-specified or, if
+ # none specified, use the default for the output type.
+ if config.formatter_name:
+ formatter_name = config.formatter_name
+ else:
+ formatter_name = default_formatter_name
+
+ # Create an instance of the class.
+ # First figure out the package/module.
+ components = formatter_name.split(".")
+ module = importlib.import_module(".".join(components[:-1]))
+
+ # Create the class name we need to load.
+ cls = getattr(module, components[-1])
+
+ # Handle formatter options for the results formatter class.
+ formatter_arg_parser = cls.arg_parser()
+ if config.formatter_options and len(config.formatter_options) > 0:
+ command_line_options = config.formatter_options
+ else:
+ command_line_options = []
+
+ formatter_options = formatter_arg_parser.parse_args(
+ command_line_options)
+
+ # Create the TestResultsFormatter given the processed options.
+ results_formatter_object = cls(results_file_object, formatter_options)
+
+ def shutdown_formatter():
+ """Shuts down the formatter when it is no longer needed."""
+ # Tell the formatter to write out anything it may have
+ # been saving until the very end (e.g. xUnit results
+ # can't complete its output until this point).
+ results_formatter_object.send_terminate_as_needed()
+
+ # And now close out the output file-like object.
+ if cleanup_func is not None:
+ cleanup_func()
+
+ return CreatedFormatter(
+ results_formatter_object,
+ shutdown_formatter)
+ else:
+ return None
+
+
+class EventBuilder(object):
+ """Helper class to build test result event dictionaries."""
+
+ BASE_DICTIONARY = None
+
+ # Test Event Types
+ TYPE_JOB_RESULT = "job_result"
+ TYPE_TEST_RESULT = "test_result"
+ TYPE_TEST_START = "test_start"
+ TYPE_MARK_TEST_RERUN_ELIGIBLE = "test_eligible_for_rerun"
+ TYPE_MARK_TEST_EXPECTED_FAILURE = "test_expected_failure"
+ TYPE_SESSION_TERMINATE = "terminate"
+
+ RESULT_TYPES = set([
+ TYPE_JOB_RESULT,
+ TYPE_TEST_RESULT
+ ])
+
+ # Test/Job Status Tags
+ STATUS_EXCEPTIONAL_EXIT = "exceptional_exit"
+ STATUS_SUCCESS = "success"
+ STATUS_FAILURE = "failure"
+ STATUS_EXPECTED_FAILURE = "expected_failure"
+ STATUS_EXPECTED_TIMEOUT = "expected_timeout"
+ STATUS_UNEXPECTED_SUCCESS = "unexpected_success"
+ STATUS_SKIP = "skip"
+ STATUS_ERROR = "error"
+ STATUS_TIMEOUT = "timeout"
+
+ """Test methods or jobs with a status matching any of these
+ status values will cause a testrun failure, unless
+ the test methods rerun and do not trigger an issue when rerun."""
+ TESTRUN_ERROR_STATUS_VALUES = set([
+ STATUS_ERROR,
+ STATUS_EXCEPTIONAL_EXIT,
+ STATUS_FAILURE,
+ STATUS_TIMEOUT
+ ])
+
+ @staticmethod
+ def _get_test_name_info(test):
+ """Returns (test-class-name, test-method-name) from a test case instance.
+
+ @param test a unittest.TestCase instance.
+
+ @return tuple containing (test class name, test method name)
+ """
+ test_class_components = test.id().split(".")
+ test_class_name = ".".join(test_class_components[:-1])
+ test_name = test_class_components[-1]
+ return (test_class_name, test_name)
+
+ @staticmethod
+ def bare_event(event_type):
+ """Creates an event with default additions, event type and timestamp.
+
+ @param event_type the value set for the "event" key, used
+ to distinguish events.
+
+ @returns an event dictionary with all default additions, the "event"
+ key set to the passed in event_type, and the event_time value set to
+ time.time().
+ """
+ if EventBuilder.BASE_DICTIONARY is not None:
+ # Start with a copy of the "always include" entries.
+ event = dict(EventBuilder.BASE_DICTIONARY)
+ else:
+ event = {}
+
+ event.update({
+ "event": event_type,
+ "event_time": time.time()
+ })
+ return event
+
+ @staticmethod
+ def _event_dictionary_common(test, event_type):
+ """Returns an event dictionary setup with values for the given event type.
+
+ @param test the unittest.TestCase instance
+
+ @param event_type the name of the event type (string).
+
+ @return event dictionary with common event fields set.
+ """
+ test_class_name, test_name = EventBuilder._get_test_name_info(test)
+
+ # Determine the filename for the test case. If there is an attribute
+ # for it, use it. Otherwise, determine from the TestCase class path.
+ if hasattr(test, "test_filename"):
+ test_filename = test.test_filename
+ else:
+ test_filename = inspect.getfile(test.__class__)
+
+ event = EventBuilder.bare_event(event_type)
+ event.update({
+ "test_class": test_class_name,
+ "test_name": test_name,
+ "test_filename": test_filename
+ })
+
+ return event
+
+ @staticmethod
+ def _error_tuple_class(error_tuple):
+ """Returns the unittest error tuple's error class as a string.
+
+ @param error_tuple the error tuple provided by the test framework.
+
+ @return the error type (typically an exception) raised by the
+ test framework.
+ """
+ type_var = error_tuple[0]
+ module = inspect.getmodule(type_var)
+ if module:
+ return "{}.{}".format(module.__name__, type_var.__name__)
+ else:
+ return type_var.__name__
+
+ @staticmethod
+ def _error_tuple_message(error_tuple):
+ """Returns the unittest error tuple's error message.
+
+ @param error_tuple the error tuple provided by the test framework.
+
+ @return the error message provided by the test framework.
+ """
+ return str(error_tuple[1])
+
+ @staticmethod
+ def _error_tuple_traceback(error_tuple):
+ """Returns the unittest error tuple's error message.
+
+ @param error_tuple the error tuple provided by the test framework.
+
+ @return the error message provided by the test framework.
+ """
+ return error_tuple[2]
+
+ @staticmethod
+ def _event_dictionary_test_result(test, status):
+ """Returns an event dictionary with common test result fields set.
+
+ @param test a unittest.TestCase instance.
+
+ @param status the status/result of the test
+ (e.g. "success", "failure", etc.)
+
+ @return the event dictionary
+ """
+ event = EventBuilder._event_dictionary_common(
+ test, EventBuilder.TYPE_TEST_RESULT)
+ event["status"] = status
+ return event
+
+ @staticmethod
+ def _event_dictionary_issue(test, status, error_tuple):
+ """Returns an event dictionary with common issue-containing test result
+ fields set.
+
+ @param test a unittest.TestCase instance.
+
+ @param status the status/result of the test
+ (e.g. "success", "failure", etc.)
+
+ @param error_tuple the error tuple as reported by the test runner.
+ This is of the form (type<error>, error).
+
+ @return the event dictionary
+ """
+ event = EventBuilder._event_dictionary_test_result(test, status)
+ event["issue_class"] = EventBuilder._error_tuple_class(error_tuple)
+ event["issue_message"] = EventBuilder._error_tuple_message(error_tuple)
+ backtrace = EventBuilder._error_tuple_traceback(error_tuple)
+ if backtrace is not None:
+ event["issue_backtrace"] = traceback.format_tb(backtrace)
+ return event
+
+ @staticmethod
+ def event_for_start(test):
+ """Returns an event dictionary for the test start event.
+
+ @param test a unittest.TestCase instance.
+
+ @return the event dictionary
+ """
+ return EventBuilder._event_dictionary_common(
+ test, EventBuilder.TYPE_TEST_START)
+
+ @staticmethod
+ def event_for_success(test):
+ """Returns an event dictionary for a successful test.
+
+ @param test a unittest.TestCase instance.
+
+ @return the event dictionary
+ """
+ return EventBuilder._event_dictionary_test_result(
+ test, EventBuilder.STATUS_SUCCESS)
+
+ @staticmethod
+ def event_for_unexpected_success(test, bugnumber):
+ """Returns an event dictionary for a test that succeeded but was
+ expected to fail.
+
+ @param test a unittest.TestCase instance.
+
+ @param bugnumber the issue identifier for the bug tracking the
+ fix request for the test expected to fail (but is in fact
+ passing here).
+
+ @return the event dictionary
+
+ """
+ event = EventBuilder._event_dictionary_test_result(
+ test, EventBuilder.STATUS_UNEXPECTED_SUCCESS)
+ if bugnumber:
+ event["bugnumber"] = str(bugnumber)
+ return event
+
+ @staticmethod
+ def event_for_failure(test, error_tuple):
+ """Returns an event dictionary for a test that failed.
+
+ @param test a unittest.TestCase instance.
+
+ @param error_tuple the error tuple as reported by the test runner.
+ This is of the form (type<error>, error).
+
+ @return the event dictionary
+ """
+ return EventBuilder._event_dictionary_issue(
+ test, EventBuilder.STATUS_FAILURE, error_tuple)
+
+ @staticmethod
+ def event_for_expected_failure(test, error_tuple, bugnumber):
+ """Returns an event dictionary for a test that failed as expected.
+
+ @param test a unittest.TestCase instance.
+
+ @param error_tuple the error tuple as reported by the test runner.
+ This is of the form (type<error>, error).
+
+ @param bugnumber the issue identifier for the bug tracking the
+ fix request for the test expected to fail.
+
+ @return the event dictionary
+
+ """
+ event = EventBuilder._event_dictionary_issue(
+ test, EventBuilder.STATUS_EXPECTED_FAILURE, error_tuple)
+ if bugnumber:
+ event["bugnumber"] = str(bugnumber)
+ return event
+
+ @staticmethod
+ def event_for_skip(test, reason):
+ """Returns an event dictionary for a test that was skipped.
+
+ @param test a unittest.TestCase instance.
+
+ @param reason the reason why the test is being skipped.
+
+ @return the event dictionary
+ """
+ event = EventBuilder._event_dictionary_test_result(
+ test, EventBuilder.STATUS_SKIP)
+ event["skip_reason"] = reason
+ return event
+
+ @staticmethod
+ def event_for_error(test, error_tuple):
+ """Returns an event dictionary for a test that hit a test execution error.
+
+ @param test a unittest.TestCase instance.
+
+ @param error_tuple the error tuple as reported by the test runner.
+ This is of the form (type<error>, error).
+
+ @return the event dictionary
+ """
+ return EventBuilder._event_dictionary_issue(
+ test, EventBuilder.STATUS_ERROR, error_tuple)
+
+ @staticmethod
+ def event_for_cleanup_error(test, error_tuple):
+ """Returns an event dictionary for a test that hit a test execution error
+ during the test cleanup phase.
+
+ @param test a unittest.TestCase instance.
+
+ @param error_tuple the error tuple as reported by the test runner.
+ This is of the form (type<error>, error).
+
+ @return the event dictionary
+ """
+ event = EventBuilder._event_dictionary_issue(
+ test, EventBuilder.STATUS_ERROR, error_tuple)
+ event["issue_phase"] = "cleanup"
+ return event
+
+ @staticmethod
+ def event_for_job_exceptional_exit(
+ pid, worker_index, exception_code, exception_description,
+ test_filename, command_line):
+ """Creates an event for a job (i.e. process) exit due to signal.
+
+ @param pid the process id for the job that failed
+ @param worker_index optional id for the job queue running the process
+ @param exception_code optional code
+ (e.g. SIGTERM integer signal number)
+ @param exception_description optional string containing symbolic
+ representation of the issue (e.g. "SIGTERM")
+ @param test_filename the path to the test filename that exited
+ in some exceptional way.
+ @param command_line the Popen-style list provided as the command line
+ for the process that timed out.
+
+ @return an event dictionary coding the job completion description.
+ """
+ event = EventBuilder.bare_event(EventBuilder.TYPE_JOB_RESULT)
+ event["status"] = EventBuilder.STATUS_EXCEPTIONAL_EXIT
+ if pid is not None:
+ event["pid"] = pid
+ if worker_index is not None:
+ event["worker_index"] = int(worker_index)
+ if exception_code is not None:
+ event["exception_code"] = exception_code
+ if exception_description is not None:
+ event["exception_description"] = exception_description
+ if test_filename is not None:
+ event["test_filename"] = test_filename
+ if command_line is not None:
+ event["command_line"] = command_line
+ return event
+
+ @staticmethod
+ def event_for_job_timeout(pid, worker_index, test_filename, command_line):
+ """Creates an event for a job (i.e. process) timeout.
+
+ @param pid the process id for the job that timed out
+ @param worker_index optional id for the job queue running the process
+ @param test_filename the path to the test filename that timed out.
+ @param command_line the Popen-style list provided as the command line
+ for the process that timed out.
+
+ @return an event dictionary coding the job completion description.
+ """
+ event = EventBuilder.bare_event(EventBuilder.TYPE_JOB_RESULT)
+ event["status"] = "timeout"
+ if pid is not None:
+ event["pid"] = pid
+ if worker_index is not None:
+ event["worker_index"] = int(worker_index)
+ if test_filename is not None:
+ event["test_filename"] = test_filename
+ if command_line is not None:
+ event["command_line"] = command_line
+ return event
+
+ @staticmethod
+ def event_for_mark_test_rerun_eligible(test):
+ """Creates an event that indicates the specified test is explicitly
+ eligible for rerun.
+
+ Note there is a mode that will enable test rerun eligibility at the
+ global level. These markings for explicit rerun eligibility are
+ intended for the mode of running where only explicitly rerunnable
+ tests are rerun upon hitting an issue.
+
+ @param test the TestCase instance to which this pertains.
+
+ @return an event that specifies the given test as being eligible to
+ be rerun.
+ """
+ event = EventBuilder._event_dictionary_common(
+ test,
+ EventBuilder.TYPE_MARK_TEST_RERUN_ELIGIBLE)
+ return event
+
+ @staticmethod
+ def event_for_mark_test_expected_failure(test):
+ """Creates an event that indicates the specified test is expected
+ to fail.
+
+ @param test the TestCase instance to which this pertains.
+
+ @return an event that specifies the given test is expected to fail.
+ """
+ event = EventBuilder._event_dictionary_common(
+ test,
+ EventBuilder.TYPE_MARK_TEST_EXPECTED_FAILURE)
+ return event
+
+ @staticmethod
+ def add_entries_to_all_events(entries_dict):
+ """Specifies a dictionary of entries to add to all test events.
+
+ This provides a mechanism for, say, a parallel test runner to
+ indicate to each inferior dotest.py that it should add a
+ worker index to each.
+
+ Calling this method replaces all previous entries added
+ by a prior call to this.
+
+ Event build methods will overwrite any entries that collide.
+ Thus, the passed in dictionary is the base, which gets merged
+ over by event building when keys collide.
+
+ @param entries_dict a dictionary containing key and value
+ pairs that should be merged into all events created by the
+ event generator. May be None to clear out any extra entries.
+ """
+ EventBuilder.BASE_DICTIONARY = dict(entries_dict)
+
+
+class ResultsFormatter(object):
+ """Provides interface to formatting test results out to a file-like object.
+
+ This class allows the LLDB test framework's raw test-realted
+ events to be processed and formatted in any manner desired.
+ Test events are represented by python dictionaries, formatted
+ as in the EventBuilder class above.
+
+ ResultFormatter instances are given a file-like object in which
+ to write their results.
+
+ ResultFormatter lifetime looks like the following:
+
+ # The result formatter is created.
+ # The argparse options dictionary is generated from calling
+ # the SomeResultFormatter.arg_parser() with the options data
+ # passed to dotest.py via the "--results-formatter-options"
+ # argument. See the help on that for syntactic requirements
+ # on getting that parsed correctly.
+ formatter = SomeResultFormatter(file_like_object, argpared_options_dict)
+
+ # Single call to session start, before parsing any events.
+ formatter.begin_session()
+
+ formatter.handle_event({"event":"initialize",...})
+
+ # Zero or more calls specified for events recorded during the test session.
+ # The parallel test runner manages getting results from all the inferior
+ # dotest processes, so from a new format perspective, don't worry about
+ # that. The formatter will be presented with a single stream of events
+ # sandwiched between a single begin_session()/end_session() pair in the
+ # parallel test runner process/thread.
+ for event in zero_or_more_test_events():
+ formatter.handle_event(event)
+
+ # Single call to terminate/wrap-up. Formatters that need all the
+ # data before they can print a correct result (e.g. xUnit/JUnit),
+ # this is where the final report can be generated.
+ formatter.handle_event({"event":"terminate",...})
+
+ It is not the formatter's responsibility to close the file_like_object.
+ (i.e. do not close it).
+
+ The lldb test framework passes these test events in real time, so they
+ arrive as they come in.
+
+ In the case of the parallel test runner, the dotest inferiors
+ add a 'pid' field to the dictionary that indicates which inferior
+ pid generated the event.
+
+ Note more events may be added in the future to support richer test
+ reporting functionality. One example: creating a true flaky test
+ result category so that unexpected successes really mean the test
+ is marked incorrectly (either should be marked flaky, or is indeed
+ passing consistently now and should have the xfail marker
+ removed). In this case, a flaky_success and flaky_fail event
+ likely will be added to capture these and support reporting things
+ like percentages of flaky test passing so we can see if we're
+ making some things worse/better with regards to failure rates.
+
+ Another example: announcing all the test methods that are planned
+ to be run, so we can better support redo operations of various kinds
+ (redo all non-run tests, redo non-run tests except the one that
+ was running [perhaps crashed], etc.)
+
+ Implementers are expected to override all the public methods
+ provided in this class. See each method's docstring to see
+ expectations about when the call should be chained.
+
+ """
+ @classmethod
+ def arg_parser(cls):
+ """@return arg parser used to parse formatter-specific options."""
+ parser = argparse.ArgumentParser(
+ description='{} options'.format(cls.__name__),
+ usage=('dotest.py --results-formatter-options='
+ '"--option1 value1 [--option2 value2 [...]]"'))
+ parser.add_argument(
+ "--dump-results",
+ action="store_true",
+ help=('dump the raw results data after printing '
+ 'the summary output.'))
+ return parser
+
+ def __init__(self, out_file, options):
+ super(ResultsFormatter, self).__init__()
+ self.out_file = out_file
+ self.options = options
+ self.using_terminal = False
+ if not self.out_file:
+ raise Exception("ResultsFormatter created with no file object")
+ self.start_time_by_test = {}
+ self.terminate_called = False
+
+ # Store counts of test_result events by status.
+ self.result_status_counts = {
+ EventBuilder.STATUS_SUCCESS: 0,
+ EventBuilder.STATUS_EXPECTED_FAILURE: 0,
+ EventBuilder.STATUS_EXPECTED_TIMEOUT: 0,
+ EventBuilder.STATUS_SKIP: 0,
+ EventBuilder.STATUS_UNEXPECTED_SUCCESS: 0,
+ EventBuilder.STATUS_FAILURE: 0,
+ EventBuilder.STATUS_ERROR: 0,
+ EventBuilder.STATUS_TIMEOUT: 0,
+ EventBuilder.STATUS_EXCEPTIONAL_EXIT: 0
+ }
+
+ # Track the most recent test start event by worker index.
+ # We'll use this to assign TIMEOUT and exceptional
+ # exits to the most recent test started on a given
+ # worker index.
+ self.started_tests_by_worker = {}
+
+ # Store the most recent test_method/job status.
+ self.result_events = {}
+
+ # Track the number of test method reruns.
+ self.test_method_rerun_count = 0
+
+ # Lock that we use while mutating inner state, like the
+ # total test count and the elements. We minimize how
+ # long we hold the lock just to keep inner state safe, not
+ # entirely consistent from the outside.
+ self.lock = threading.RLock()
+
+ # Keeps track of the test base filenames for tests that
+ # are expected to timeout. If a timeout occurs in any test
+ # basename that matches this list, that result should be
+ # converted into a non-issue. We'll create an expected
+ # timeout test status for this.
+ self.expected_timeouts_by_basename = set()
+
+ # Tests which have reported that they are expecting to fail. These will
+ # be marked as expected failures even if they return a failing status,
+ # probably because they crashed or deadlocked.
+ self.expected_failures = set()
+
+ # Keep track of rerun-eligible tests.
+ # This is a set that contains tests saved as:
+ # {test_filename}:{test_class}:{test_name}
+ self.rerun_eligible_tests = set()
+
+ # A dictionary of test files that had a failing
+ # test, in the format of:
+ # key = test path, value = array of test methods that need rerun
+ self.tests_for_rerun = {}
+
+ @classmethod
+ def _make_key(cls, result_event):
+ """Creates a key from a test or job result event.
+
+ This key attempts to be as unique as possible. For
+ test result events, it will be unique per test method.
+ For job events (ones not promoted to a test result event),
+ it will be unique per test case file.
+
+ @return a string-based key of the form
+ {test_filename}:{test_class}.{test_name}
+ """
+ if result_event is None:
+ return None
+ component_count = 0
+ if "test_filename" in result_event:
+ key = result_event["test_filename"]
+ component_count += 1
+ if "test_class" in result_event:
+ if component_count > 0:
+ key += ":"
+ key += result_event["test_class"]
+ component_count += 1
+ if "test_name" in result_event:
+ if component_count > 0:
+ key += "."
+ key += result_event["test_name"]
+ component_count += 1
+ return key
+
+ def _mark_test_as_expected_failure(self, test_result_event):
+ key = self._make_key(test_result_event)
+ if key is not None:
+ self.expected_failures.add(key)
+ else:
+ sys.stderr.write(
+ "\nerror: test marked as expected failure but "
+ "failed to create key.\n")
+
+ def _mark_test_for_rerun_eligibility(self, test_result_event):
+ key = self._make_key(test_result_event)
+ if key is not None:
+ self.rerun_eligible_tests.add(key)
+ else:
+ sys.stderr.write(
+ "\nerror: test marked for re-run eligibility but "
+ "failed to create key.\n")
+
+ def _maybe_add_test_to_rerun_list(self, result_event):
+ key = self._make_key(result_event)
+ if key is not None:
+ if (key in self.rerun_eligible_tests or
+ configuration.rerun_all_issues):
+ test_filename = result_event.get("test_filename", None)
+ if test_filename is not None:
+ test_name = result_event.get("test_name", None)
+ if test_filename not in self.tests_for_rerun:
+ self.tests_for_rerun[test_filename] = []
+ if test_name is not None:
+ self.tests_for_rerun[test_filename].append(test_name)
+ else:
+ sys.stderr.write(
+ "\nerror: couldn't add testrun-failing test to rerun "
+ "list because no eligibility key could be created.\n")
+
+ def _maybe_remap_job_result_event(self, test_event):
+ """Remaps timeout/exceptional exit job results to last test method running.
+
+ @param test_event the job_result test event. This is an in/out
+ parameter. It will be modified if it can be mapped to a test_result
+ of the same status, using details from the last-running test method
+ known to be most recently started on the same worker index.
+ """
+ test_start = None
+
+ job_status = test_event["status"]
+ if job_status in [
+ EventBuilder.STATUS_TIMEOUT,
+ EventBuilder.STATUS_EXCEPTIONAL_EXIT]:
+ worker_index = test_event.get("worker_index", None)
+ if worker_index is not None:
+ test_start = self.started_tests_by_worker.get(
+ worker_index, None)
+
+ # If we have a test start to remap, do it here.
+ if test_start is not None:
+ test_event["event"] = EventBuilder.TYPE_TEST_RESULT
+
+ # Fill in all fields from test start not present in
+ # job status message.
+ for (start_key, start_value) in test_start.items():
+ if start_key not in test_event:
+ test_event[start_key] = start_value
+
+ def _maybe_remap_expected_timeout(self, event):
+ if event is None:
+ return
+
+ status = event.get("status", None)
+ if status is None or status != EventBuilder.STATUS_TIMEOUT:
+ return
+
+ # Check if the timeout test's basename is in the expected timeout
+ # list. If so, convert to an expected timeout.
+ basename = os.path.basename(event.get("test_filename", ""))
+ if basename in self.expected_timeouts_by_basename:
+ # Convert to an expected timeout.
+ event["status"] = EventBuilder.STATUS_EXPECTED_TIMEOUT
+
+ def _maybe_remap_expected_failure(self, event):
+ if event is None:
+ return
+
+ key = self._make_key(event)
+ if key not in self.expected_failures:
+ return
+
+ status = event.get("status", None)
+ if status in EventBuilder.TESTRUN_ERROR_STATUS_VALUES:
+ event["status"] = EventBuilder.STATUS_EXPECTED_FAILURE
+ elif status == EventBuilder.STATUS_SUCCESS:
+ event["status"] = EventBuilder.STATUS_UNEXPECTED_SUCCESS
+
+ def handle_event(self, test_event):
+ """Handles the test event for collection into the formatter output.
+
+ Derived classes may override this but should call down to this
+ implementation first.
+
+ @param test_event the test event as formatted by one of the
+ event_for_* calls.
+ """
+ with self.lock:
+ # Keep track of whether terminate was received. We do this so
+ # that a process can call the 'terminate' event on its own, to
+ # close down a formatter at the appropriate time. Then the
+ # atexit() cleanup can call the "terminate if it hasn't been
+ # called yet".
+ if test_event is not None:
+ event_type = test_event.get("event", "")
+ # We intentionally allow event_type to be checked anew
+ # after this check below since this check may rewrite
+ # the event type
+ if event_type == EventBuilder.TYPE_JOB_RESULT:
+ # Possibly convert the job status (timeout, exceptional exit)
+ # to an appropriate test_result event.
+ self._maybe_remap_job_result_event(test_event)
+ event_type = test_event.get("event", "")
+
+ # Remap timeouts to expected timeouts.
+ if event_type in EventBuilder.RESULT_TYPES:
+ self._maybe_remap_expected_timeout(test_event)
+ self._maybe_remap_expected_failure(test_event)
+ event_type = test_event.get("event", "")
+
+ if event_type == "terminate":
+ self.terminate_called = True
+ elif event_type in EventBuilder.RESULT_TYPES:
+ # Keep track of event counts per test/job result status type.
+ # The only job (i.e. inferior process) results that make it
+ # here are ones that cannot be remapped to the most recently
+ # started test for the given worker index.
+ status = test_event["status"]
+ self.result_status_counts[status] += 1
+ # Clear the most recently started test for the related worker.
+ worker_index = test_event.get("worker_index", None)
+ if worker_index is not None:
+ self.started_tests_by_worker.pop(worker_index, None)
+
+ if status in EventBuilder.TESTRUN_ERROR_STATUS_VALUES:
+ # A test/job status value in any of those status values
+ # causes a testrun failure. If such a test fails, check
+ # whether it can be rerun. If it can be rerun, add it
+ # to the rerun job.
+ self._maybe_add_test_to_rerun_list(test_event)
+
+ # Build the test key.
+ test_key = self._make_key(test_event)
+ if test_key is None:
+ raise Exception(
+ "failed to find test filename for "
+ "test event {}".format(test_event))
+
+ # Save the most recent test event for the test key.
+ # This allows a second test phase to overwrite the most
+ # recent result for the test key (unique per method).
+ # We do final reporting at the end, so we'll report based
+ # on final results.
+ # We do this so that a re-run caused by, perhaps, the need
+ # to run a low-load, single-worker test run can have the final
+ # run's results to always be used.
+ if test_key in self.result_events:
+ # We are replacing the result of something that was
+ # already counted by the base class. Remove the double
+ # counting by reducing by one the count for the test
+ # result status.
+ old_status = self.result_events[test_key]["status"]
+ self.result_status_counts[old_status] -= 1
+ self.test_method_rerun_count += 1
+ self.result_events[test_key] = test_event
+ elif event_type == EventBuilder.TYPE_TEST_START:
+ # Track the start time for the test method.
+ self.track_start_time(
+ test_event["test_class"],
+ test_event["test_name"],
+ test_event["event_time"])
+ # Track of the most recent test method start event
+ # for the related worker. This allows us to figure
+ # out whether a process timeout or exceptional exit
+ # can be charged (i.e. assigned) to a test method.
+ worker_index = test_event.get("worker_index", None)
+ if worker_index is not None:
+ self.started_tests_by_worker[worker_index] = test_event
+
+ elif event_type == EventBuilder.TYPE_MARK_TEST_RERUN_ELIGIBLE:
+ self._mark_test_for_rerun_eligibility(test_event)
+ elif event_type == EventBuilder.TYPE_MARK_TEST_EXPECTED_FAILURE:
+ self._mark_test_as_expected_failure(test_event)
+
+ def set_expected_timeouts_by_basename(self, basenames):
+ """Specifies a list of test file basenames that are allowed to timeout
+ without being called out as a timeout issue.
+
+ These fall into a new status category called STATUS_EXPECTED_TIMEOUT.
+ """
+ if basenames is not None:
+ for basename in basenames:
+ self.expected_timeouts_by_basename.add(basename)
+
+ def track_start_time(self, test_class, test_name, start_time):
+ """tracks the start time of a test so elapsed time can be computed.
+
+ this alleviates the need for test results to be processed serially
+ by test. it will save the start time for the test so that
+ elapsed_time_for_test() can compute the elapsed time properly.
+ """
+ if test_class is None or test_name is None:
+ return
+
+ test_key = "{}.{}".format(test_class, test_name)
+ self.start_time_by_test[test_key] = start_time
+
+ def elapsed_time_for_test(self, test_class, test_name, end_time):
+ """returns the elapsed time for a test.
+
+ this function can only be called once per test and requires that
+ the track_start_time() method be called sometime prior to calling
+ this method.
+ """
+ if test_class is None or test_name is None:
+ return -2.0
+
+ test_key = "{}.{}".format(test_class, test_name)
+ if test_key not in self.start_time_by_test:
+ return -1.0
+ else:
+ start_time = self.start_time_by_test[test_key]
+ del self.start_time_by_test[test_key]
+ return end_time - start_time
+
+ def is_using_terminal(self):
+ """returns true if this results formatter is using the terminal and
+ output should be avoided."""
+ return self.using_terminal
+
+ def send_terminate_as_needed(self):
+ """sends the terminate event if it hasn't been received yet."""
+ if not self.terminate_called:
+ terminate_event = EventBuilder.bare_event("terminate")
+ self.handle_event(terminate_event)
+
+ # Derived classes may require self access
+ # pylint: disable=no-self-use
+ def replaces_summary(self):
+ """Returns whether the results formatter includes a summary
+ suitable to replace the old lldb test run results.
+
+ @return True if the lldb test runner can skip its summary
+ generation when using this results formatter; False otherwise.
+ """
+ return False
+
+ def counts_by_test_result_status(self, status):
+ """Returns number of test method results for the given status.
+
+ @status_result a test result status (e.g. success, fail, skip)
+ as defined by the EventBuilder.STATUS_* class members.
+
+ @return an integer returning the number of test methods matching
+ the given test result status.
+ """
+ return self.result_status_counts[status]
+
+ @classmethod
+ def _event_sort_key(cls, event):
+ """Returns the sort key to be used for a test event.
+
+ This method papers over the differences in a test method result vs. a
+ job (i.e. inferior process) result.
+
+ @param event a test result or job result event.
+ @return a key useful for sorting events by name (test name preferably,
+ then by test filename).
+ """
+ if "test_name" in event:
+ return event["test_name"]
+ else:
+ return event.get("test_filename", None)
+
+ def _partition_results_by_status(self, categories):
+ """Partitions the captured test results by event status.
+
+ This permits processing test results by the category ids.
+
+ @param categories the list of categories on which to partition.
+ Follows the format described in _report_category_details().
+
+ @return a dictionary where each key is the test result status,
+ and each entry is a list containing all the test result events
+ that matched that test result status. Result status IDs with
+ no matching entries will have a zero-length list.
+ """
+ partitioned_events = {}
+ for category in categories:
+ result_status_id = category[0]
+ matching_events = [
+ [key, event] for (key, event) in self.result_events.items()
+ if event.get("status", "") == result_status_id]
+ partitioned_events[result_status_id] = sorted(
+ matching_events,
+ key=lambda x: self._event_sort_key(x[1]))
+ return partitioned_events
+
+ def _print_banner(self, out_file, banner_text):
+ """Prints an ASCII banner around given text.
+
+ Output goes to the out file for the results formatter.
+
+ @param out_file a file-like object where output will be written.
+ @param banner_text the text to display, with a banner
+ of '=' around the line above and line below.
+ """
+ banner_separator = "".ljust(len(banner_text), "=")
+
+ out_file.write("\n{}\n{}\n{}\n".format(
+ banner_separator,
+ banner_text,
+ banner_separator))
+
+ def _print_summary_counts(
+ self, out_file, categories, result_events_by_status, extra_rows):
+ """Prints summary counts for all categories.
+
+ @param out_file a file-like object used to print output.
+
+ @param categories the list of categories on which to partition.
+ Follows the format described in _report_category_details().
+
+ @param result_events_by_status the partitioned list of test
+ result events in a dictionary, with the key set to the test
+ result status id and the value set to the list of test method
+ results that match the status id.
+ """
+
+ # Get max length for category printed name
+ category_with_max_printed_name = max(
+ categories, key=lambda x: len(x[1]))
+ max_category_name_length = len(category_with_max_printed_name[1])
+
+ # If we are provided with extra rows, consider these row name lengths.
+ if extra_rows is not None:
+ for row in extra_rows:
+ name_length = len(row[0])
+ if name_length > max_category_name_length:
+ max_category_name_length = name_length
+
+ self._print_banner(out_file, "Test Result Summary")
+
+ # Prepend extra rows
+ if extra_rows is not None:
+ for row in extra_rows:
+ extra_label = "{}:".format(row[0]).ljust(
+ max_category_name_length + 1)
+ out_file.write("{} {:4}\n".format(extra_label, row[1]))
+
+ for category in categories:
+ result_status_id = category[0]
+ result_label = "{}:".format(category[1]).ljust(
+ max_category_name_length + 1)
+ count = len(result_events_by_status[result_status_id])
+ out_file.write("{} {:4}\n".format(
+ result_label,
+ count))
+
+ @classmethod
+ def _has_printable_details(cls, categories, result_events_by_status):
+ """Returns whether there are any test result details that need to be printed.
+
+ This will spin through the results and see if any result in a category
+ that is printable has any results to print.
+
+ @param categories the list of categories on which to partition.
+ Follows the format described in _report_category_details().
+
+ @param result_events_by_status the partitioned list of test
+ result events in a dictionary, with the key set to the test
+ result status id and the value set to the list of test method
+ results that match the status id.
+
+ @return True if there are any details (i.e. test results
+ for failures, errors, unexpected successes); False otherwise.
+ """
+ for category in categories:
+ result_status_id = category[0]
+ print_matching_tests = category[2]
+ if print_matching_tests:
+ if len(result_events_by_status[result_status_id]) > 0:
+ # We found a printable details test result status
+ # that has details to print.
+ return True
+ # We didn't find any test result category with printable
+ # details.
+ return False
+
+ def _report_category_details(self, out_file, category, result_events_by_status):
+ """Reports all test results matching the given category spec.
+
+ @param out_file a file-like object used to print output.
+
+ @param category a category spec of the format [test_event_name,
+ printed_category_name, print_matching_entries?]
+
+ @param result_events_by_status the partitioned list of test
+ result events in a dictionary, with the key set to the test
+ result status id and the value set to the list of test method
+ results that match the status id.
+ """
+ result_status_id = category[0]
+ print_matching_tests = category[2]
+ detail_label = category[3]
+
+ if print_matching_tests:
+ # Sort by test name
+ for (_, event) in result_events_by_status[result_status_id]:
+ # Convert full test path into test-root-relative.
+ test_relative_path = os.path.relpath(
+ os.path.realpath(event["test_filename"]),
+ lldbsuite.lldb_test_root)
+
+ # Create extra info component (used for exceptional exit info)
+ if result_status_id == EventBuilder.STATUS_EXCEPTIONAL_EXIT:
+ extra_info = "[EXCEPTIONAL EXIT {} ({})] ".format(
+ event["exception_code"],
+ event["exception_description"])
+ else:
+ extra_info = ""
+
+ # Figure out the identity we will use for this test.
+ if configuration.verbose and ("test_class" in event):
+ test_id = "{}.{}".format(
+ event["test_class"], event["test_name"])
+ elif "test_name" in event:
+ test_id = event["test_name"]
+ else:
+ test_id = "<no_running_test_method>"
+
+ # Display the info.
+ out_file.write("{}: {}{} ({})\n".format(
+ detail_label,
+ extra_info,
+ test_id,
+ test_relative_path))
+
+ def print_results(self, out_file):
+ """Writes the test result report to the output file.
+
+ @param out_file a file-like object used for printing summary
+ results. This is different than self.out_file, which might
+ be something else for non-summary data.
+ """
+ extra_results = [
+ # Total test methods processed, excluding reruns.
+ ["Test Methods", len(self.result_events)],
+ ["Reruns", self.test_method_rerun_count]]
+
+ # Output each of the test result entries.
+ categories = [
+ # result id, printed name, print matching tests?, detail label
+ [EventBuilder.STATUS_SUCCESS,
+ "Success", False, None],
+ [EventBuilder.STATUS_EXPECTED_FAILURE,
+ "Expected Failure", False, None],
+ [EventBuilder.STATUS_FAILURE,
+ "Failure", True, "FAIL"],
+ [EventBuilder.STATUS_ERROR,
+ "Error", True, "ERROR"],
+ [EventBuilder.STATUS_EXCEPTIONAL_EXIT,
+ "Exceptional Exit", True, "ERROR"],
+ [EventBuilder.STATUS_UNEXPECTED_SUCCESS,
+ "Unexpected Success", True, "UNEXPECTED SUCCESS"],
+ [EventBuilder.STATUS_SKIP, "Skip", False, None],
+ [EventBuilder.STATUS_TIMEOUT,
+ "Timeout", True, "TIMEOUT"],
+ [EventBuilder.STATUS_EXPECTED_TIMEOUT,
+ # Intentionally using the unusual hyphenation in TIME-OUT to
+ # prevent buildbots from thinking it is an issue when scanning
+ # for TIMEOUT.
+ "Expected Timeout", True, "EXPECTED TIME-OUT"]
+ ]
+
+ # Partition all the events by test result status
+ result_events_by_status = self._partition_results_by_status(
+ categories)
+
+ # Print the details
+ have_details = self._has_printable_details(
+ categories, result_events_by_status)
+ if have_details:
+ self._print_banner(out_file, "Issue Details")
+ for category in categories:
+ self._report_category_details(
+ out_file, category, result_events_by_status)
+
+ # Print the summary
+ self._print_summary_counts(
+ out_file, categories, result_events_by_status, extra_results)
+
+ if self.options.dump_results:
+ # Debug dump of the key/result info for all categories.
+ self._print_banner("Results Dump")
+ for status, events_by_key in result_events_by_status.items():
+ out_file.write("\nSTATUS: {}\n".format(status))
+ for key, event in events_by_key:
+ out_file.write("key: {}\n".format(key))
+ out_file.write("event: {}\n".format(event))
+
+
+class RawPickledFormatter(ResultsFormatter):
+ """Formats events as a pickled stream.
+
+ The parallel test runner has inferiors pickle their results and send them
+ over a socket back to the parallel test. The parallel test runner then
+ aggregates them into the final results formatter (e.g. xUnit).
+ """
+
+ @classmethod
+ def arg_parser(cls):
+ """@return arg parser used to parse formatter-specific options."""
+ parser = super(RawPickledFormatter, cls).arg_parser()
+ return parser
+
+ def __init__(self, out_file, options):
+ super(RawPickledFormatter, self).__init__(out_file, options)
+ self.pid = os.getpid()
+
+ def handle_event(self, test_event):
+ super(RawPickledFormatter, self).handle_event(test_event)
+
+ # Convert initialize/terminate events into job_begin/job_end events.
+ event_type = test_event["event"]
+ if event_type is None:
+ return
+
+ if event_type == "initialize":
+ test_event["event"] = "job_begin"
+ elif event_type == "terminate":
+ test_event["event"] = "job_end"
+
+ # Tack on the pid.
+ test_event["pid"] = self.pid
+
+ # Send it as {serialized_length_of_serialized_bytes}{serialized_bytes}
+ import struct
+ msg = cPickle.dumps(test_event)
+ packet = struct.pack("!I%ds" % len(msg), len(msg), msg)
+ self.out_file.send(packet)
+
+
+class DumpFormatter(ResultsFormatter):
+ """Formats events to the file as their raw python dictionary format."""
+
+ def handle_event(self, test_event):
+ super(DumpFormatter, self).handle_event(test_event)
+ self.out_file.write("\n" + pprint.pformat(test_event) + "\n")
diff --git a/packages/Python/lldbsuite/test/settings/Makefile b/packages/Python/lldbsuite/test/settings/Makefile
new file mode 100644
index 000000000000..d4bc9c689043
--- /dev/null
+++ b/packages/Python/lldbsuite/test/settings/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/settings/TestSettings.py b/packages/Python/lldbsuite/test/settings/TestSettings.py
new file mode 100644
index 000000000000..1d1912495551
--- /dev/null
+++ b/packages/Python/lldbsuite/test/settings/TestSettings.py
@@ -0,0 +1,495 @@
+"""
+Test lldb settings command.
+"""
+
+from __future__ import print_function
+
+
+
+import os, time, re
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class SettingsCommandTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @classmethod
+ def classCleanup(cls):
+ """Cleanup the test byproducts."""
+ cls.RemoveTempFile("output1.txt")
+ cls.RemoveTempFile("output2.txt")
+ cls.RemoveTempFile("stderr.txt")
+ cls.RemoveTempFile("stdout.txt")
+
+ @no_debug_info_test
+ def test_apropos_should_also_search_settings_description(self):
+ """Test that 'apropos' command should also search descriptions for the settings variables."""
+
+ self.expect("apropos 'environment variable'",
+ substrs = ["target.env-vars",
+ "environment variables",
+ "executable's environment"])
+
+ @no_debug_info_test
+ def test_append_target_env_vars(self):
+ """Test that 'append target.run-args' works."""
+ # Append the env-vars.
+ self.runCmd('settings append target.env-vars MY_ENV_VAR=YES')
+ # And add hooks to restore the settings during tearDown().
+ self.addTearDownHook(
+ lambda: self.runCmd("settings clear target.env-vars"))
+
+ # Check it immediately!
+ self.expect('settings show target.env-vars',
+ substrs = ['MY_ENV_VAR=YES'])
+
+ @no_debug_info_test
+ def test_insert_before_and_after_target_run_args(self):
+ """Test that 'insert-before/after target.run-args' works."""
+ # Set the run-args first.
+ self.runCmd('settings set target.run-args a b c')
+ # And add hooks to restore the settings during tearDown().
+ self.addTearDownHook(
+ lambda: self.runCmd("settings clear target.run-args"))
+
+ # Now insert-before the index-0 element with '__a__'.
+ self.runCmd('settings insert-before target.run-args 0 __a__')
+ # And insert-after the index-1 element with '__A__'.
+ self.runCmd('settings insert-after target.run-args 1 __A__')
+ # Check it immediately!
+ self.expect('settings show target.run-args',
+ substrs = ['target.run-args',
+ '[0]: "__a__"',
+ '[1]: "a"',
+ '[2]: "__A__"',
+ '[3]: "b"',
+ '[4]: "c"'])
+
+ @no_debug_info_test
+ def test_replace_target_run_args(self):
+ """Test that 'replace target.run-args' works."""
+ # Set the run-args and then replace the index-0 element.
+ self.runCmd('settings set target.run-args a b c')
+ # And add hooks to restore the settings during tearDown().
+ self.addTearDownHook(
+ lambda: self.runCmd("settings clear target.run-args"))
+
+ # Now replace the index-0 element with 'A', instead.
+ self.runCmd('settings replace target.run-args 0 A')
+ # Check it immediately!
+ self.expect('settings show target.run-args',
+ substrs = ['target.run-args (arguments) =',
+ '[0]: "A"',
+ '[1]: "b"',
+ '[2]: "c"'])
+
+ @no_debug_info_test
+ def test_set_prompt(self):
+ """Test that 'set prompt' actually changes the prompt."""
+
+ # Set prompt to 'lldb2'.
+ self.runCmd("settings set prompt 'lldb2 '")
+
+ # Immediately test the setting.
+ self.expect("settings show prompt", SETTING_MSG("prompt"),
+ startstr = 'prompt (string) = "lldb2 "')
+
+ # The overall display should also reflect the new setting.
+ self.expect("settings show", SETTING_MSG("prompt"),
+ substrs = ['prompt (string) = "lldb2 "'])
+
+ # Use '-r' option to reset to the original default prompt.
+ self.runCmd("settings clear prompt")
+
+ @no_debug_info_test
+ def test_set_term_width(self):
+ """Test that 'set term-width' actually changes the term-width."""
+
+ self.runCmd("settings set term-width 70")
+
+ # Immediately test the setting.
+ self.expect("settings show term-width", SETTING_MSG("term-width"),
+ startstr = "term-width (int) = 70")
+
+ # The overall display should also reflect the new setting.
+ self.expect("settings show", SETTING_MSG("term-width"),
+ substrs = ["term-width (int) = 70"])
+
+ #rdar://problem/10712130
+ def test_set_frame_format(self):
+ """Test that 'set frame-format' with a backtick char in the format string works as well as fullpath."""
+ self.build()
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ def cleanup():
+ self.runCmd("settings set frame-format %s" % self.format_string, check=False)
+
+ # Execute the cleanup function during test case tear down.
+ self.addTearDownHook(cleanup)
+
+ self.runCmd("settings show frame-format")
+ m = re.match(
+ '^frame-format \(format-string\) = "(.*)\"$',
+ self.res.GetOutput())
+ self.assertTrue(m, "Bad settings string")
+ self.format_string = m.group(1)
+
+ # Change the default format to print function.name rather than function.name-with-args
+ format_string = "frame #${frame.index}: ${frame.pc}{ ${module.file.basename}`${function.name}{${function.pc-offset}}}{ at ${line.file.fullpath}:${line.number}}{, lang=${language}}\n"
+ self.runCmd("settings set frame-format %s" % format_string)
+
+ # Immediately test the setting.
+ self.expect("settings show frame-format", SETTING_MSG("frame-format"),
+ substrs = [format_string])
+
+ self.runCmd("breakpoint set -n main")
+ self.runCmd("run")
+ self.expect("thread backtrace",
+ substrs = ["`main", os.getcwd()])
+
+ def test_set_auto_confirm(self):
+ """Test that after 'set auto-confirm true', manual confirmation should not kick in."""
+ self.build()
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ self.runCmd("settings set auto-confirm true")
+
+ # Immediately test the setting.
+ self.expect("settings show auto-confirm", SETTING_MSG("auto-confirm"),
+ startstr = "auto-confirm (boolean) = true")
+
+ # Now 'breakpoint delete' should just work fine without confirmation
+ # prompt from the command interpreter.
+ self.runCmd("breakpoint set -n main")
+ self.expect("breakpoint delete",
+ startstr = "All breakpoints removed")
+
+ # Restore the original setting of auto-confirm.
+ self.runCmd("settings clear auto-confirm")
+ self.expect("settings show auto-confirm", SETTING_MSG("auto-confirm"),
+ startstr = "auto-confirm (boolean) = false")
+
+ @skipUnlessArch(['x86_64', 'i386', 'i686'])
+ def test_disassembler_settings(self):
+ """Test that user options for the disassembler take effect."""
+ self.build()
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # AT&T syntax
+ self.runCmd("settings set target.x86-disassembly-flavor att")
+ self.runCmd("settings set target.use-hex-immediates false")
+ self.expect("disassemble -n numberfn",
+ substrs = ["$90"])
+ self.runCmd("settings set target.use-hex-immediates true")
+ self.runCmd("settings set target.hex-immediate-style c")
+ self.expect("disassemble -n numberfn",
+ substrs = ["$0x5a"])
+ self.runCmd("settings set target.hex-immediate-style asm")
+ self.expect("disassemble -n numberfn",
+ substrs = ["$5ah"])
+
+ # Intel syntax
+ self.runCmd("settings set target.x86-disassembly-flavor intel")
+ self.runCmd("settings set target.use-hex-immediates false")
+ self.expect("disassemble -n numberfn",
+ substrs = ["90"])
+ self.runCmd("settings set target.use-hex-immediates true")
+ self.runCmd("settings set target.hex-immediate-style c")
+ self.expect("disassemble -n numberfn",
+ substrs = ["0x5a"])
+ self.runCmd("settings set target.hex-immediate-style asm")
+ self.expect("disassemble -n numberfn",
+ substrs = ["5ah"])
+
+ @expectedFailureWindows("llvm.org/pr24579")
+ def test_run_args_and_env_vars(self):
+ """Test that run-args and env-vars are passed to the launched process."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Set the run-args and the env-vars.
+ # And add hooks to restore the settings during tearDown().
+ self.runCmd('settings set target.run-args A B C')
+ self.addTearDownHook(
+ lambda: self.runCmd("settings clear target.run-args"))
+ self.runCmd('settings set target.env-vars ["MY_ENV_VAR"]=YES')
+ self.addTearDownHook(
+ lambda: self.runCmd("settings clear target.env-vars"))
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Read the output file produced by running the program.
+ if lldb.remote_platform:
+ self.runCmd('platform get-file "output2.txt" "output2.txt"')
+ with open('output2.txt', 'r') as f:
+ output = f.read()
+
+ self.expect(output, exe=False,
+ substrs = ["argv[1] matches",
+ "argv[2] matches",
+ "argv[3] matches",
+ "Environment variable 'MY_ENV_VAR' successfully passed."])
+
+ @skipIfRemote # it doesn't make sense to send host env to remote target
+ def test_pass_host_env_vars(self):
+ """Test that the host env vars are passed to the launched process."""
+ self.build()
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # By default, inherit-env is 'true'.
+ self.expect('settings show target.inherit-env', "Default inherit-env is 'true'",
+ startstr = "target.inherit-env (boolean) = true")
+
+ # Set some host environment variables now.
+ os.environ["MY_HOST_ENV_VAR1"] = "VAR1"
+ os.environ["MY_HOST_ENV_VAR2"] = "VAR2"
+
+ # This is the function to unset the two env variables set above.
+ def unset_env_variables():
+ os.environ.pop("MY_HOST_ENV_VAR1")
+ os.environ.pop("MY_HOST_ENV_VAR2")
+
+ self.addTearDownHook(unset_env_variables)
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # Read the output file produced by running the program.
+ if lldb.remote_platform:
+ self.runCmd('platform get-file "output1.txt" "output1.txt"')
+ with open('output1.txt', 'r') as f:
+ output = f.read()
+
+ self.expect(output, exe=False,
+ substrs = ["The host environment variable 'MY_HOST_ENV_VAR1' successfully passed.",
+ "The host environment variable 'MY_HOST_ENV_VAR2' successfully passed."])
+
+ def test_set_error_output_path(self):
+ """Test that setting target.error/output-path for the launched process works."""
+ self.build()
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Set the error-path and output-path and verify both are set.
+ self.runCmd("settings set target.error-path stderr.txt")
+ self.runCmd("settings set target.output-path stdout.txt")
+ # And add hooks to restore the original settings during tearDown().
+ self.addTearDownHook(
+ lambda: self.runCmd("settings clear target.output-path"))
+ self.addTearDownHook(
+ lambda: self.runCmd("settings clear target.error-path"))
+
+ self.expect("settings show target.error-path",
+ SETTING_MSG("target.error-path"),
+ substrs = ['target.error-path (file) = "stderr.txt"'])
+
+ self.expect("settings show target.output-path",
+ SETTING_MSG("target.output-path"),
+ substrs = ['target.output-path (file) = "stdout.txt"'])
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ if lldb.remote_platform:
+ self.runCmd('platform get-file "stderr.txt" "stderr.txt"')
+ self.runCmd('platform get-file "stdout.txt" "stdout.txt"')
+
+
+ # The 'stderr.txt' file should now exist.
+ self.assertTrue(os.path.isfile("stderr.txt"),
+ "'stderr.txt' exists due to target.error-path.")
+
+ # Read the output file produced by running the program.
+ with open('stderr.txt', 'r') as f:
+ output = f.read()
+
+ self.expect(output, exe=False,
+ startstr = "This message should go to standard error.")
+
+ # The 'stdout.txt' file should now exist.
+ self.assertTrue(os.path.isfile("stdout.txt"),
+ "'stdout.txt' exists due to target.output-path.")
+
+ # Read the output file produced by running the program.
+ with open('stdout.txt', 'r') as f:
+ output = f.read()
+
+ self.expect(output, exe=False,
+ startstr = "This message should go to standard out.")
+
+ @no_debug_info_test
+ def test_print_dictionary_setting(self):
+ self.runCmd ("settings clear target.env-vars")
+ self.runCmd ("settings set target.env-vars [\"MY_VAR\"]=some-value")
+ self.expect ("settings show target.env-vars",
+ substrs = [ "MY_VAR=some-value" ])
+ self.runCmd ("settings clear target.env-vars")
+
+ @no_debug_info_test
+ def test_print_array_setting(self):
+ self.runCmd ("settings clear target.run-args")
+ self.runCmd ("settings set target.run-args gobbledy-gook")
+ self.expect ("settings show target.run-args",
+ substrs = [ '[0]: "gobbledy-gook"' ])
+ self.runCmd ("settings clear target.run-args")
+
+ @no_debug_info_test
+ def test_settings_with_quotes (self):
+ self.runCmd ("settings clear target.run-args")
+ self.runCmd ("settings set target.run-args a b c")
+ self.expect ("settings show target.run-args",
+ substrs = [ '[0]: "a"',
+ '[1]: "b"',
+ '[2]: "c"' ])
+ self.runCmd ("settings set target.run-args 'a b c'")
+ self.expect ("settings show target.run-args",
+ substrs = [ '[0]: "a b c"' ])
+ self.runCmd ("settings clear target.run-args")
+ self.runCmd ("settings clear target.env-vars")
+ self.runCmd ('settings set target.env-vars ["MY_FILE"]="this is a file name with spaces.txt"')
+ self.expect ("settings show target.env-vars",
+ substrs = [ 'MY_FILE=this is a file name with spaces.txt' ])
+ self.runCmd ("settings clear target.env-vars")
+ # Test and make sure that setting "format-string" settings obeys quotes if they are provided
+ self.runCmd ("settings set thread-format 'abc def' ")
+ self.expect ("settings show thread-format", 'thread-format (format-string) = "abc def"')
+ self.runCmd ('settings set thread-format "abc def" ')
+ self.expect ("settings show thread-format", 'thread-format (format-string) = "abc def"')
+ # Make sure when no quotes are provided that we maintain any trailing spaces
+ self.runCmd ('settings set thread-format abc def ')
+ self.expect ("settings show thread-format", 'thread-format (format-string) = "abc def "')
+ self.runCmd ('settings clear thread-format')
+
+ @no_debug_info_test
+ def test_settings_with_trailing_whitespace (self):
+
+ # boolean
+ self.runCmd ("settings set target.skip-prologue true") # Set to known value
+ self.runCmd ("settings set target.skip-prologue false ") # Set to new value with trailing whitespace
+ # Make sure the setting was correctly set to "false"
+ self.expect ("settings show target.skip-prologue", SETTING_MSG("target.skip-prologue"),
+ startstr = "target.skip-prologue (boolean) = false")
+ self.runCmd("settings clear target.skip-prologue", check=False)
+ # integer
+ self.runCmd ("settings set term-width 70") # Set to known value
+ self.runCmd ("settings set term-width 60 \t") # Set to new value with trailing whitespaces
+ self.expect ("settings show term-width", SETTING_MSG("term-width"),
+ startstr = "term-width (int) = 60")
+ self.runCmd("settings clear term-width", check=False)
+ # string
+ self.runCmd ("settings set target.arg0 abc") # Set to known value
+ self.runCmd ("settings set target.arg0 cde\t ") # Set to new value with trailing whitespaces
+ self.expect ("settings show target.arg0", SETTING_MSG("target.arg0"),
+ startstr = 'target.arg0 (string) = "cde"')
+ self.runCmd("settings clear target.arg0", check=False)
+ # file
+ path1 = os.path.join(os.getcwd(), "path1.txt")
+ path2 = os.path.join(os.getcwd(), "path2.txt")
+ self.runCmd ("settings set target.output-path %s" % path1) # Set to known value
+ self.expect ("settings show target.output-path", SETTING_MSG("target.output-path"),
+ startstr = 'target.output-path (file) = ', substrs=[path1])
+ self.runCmd ("settings set target.output-path %s " % path2) # Set to new value with trailing whitespaces
+ self.expect ("settings show target.output-path", SETTING_MSG("target.output-path"),
+ startstr = 'target.output-path (file) = ', substrs=[path2])
+ self.runCmd("settings clear target.output-path", check=False)
+ # enum
+ self.runCmd ("settings set stop-disassembly-display never") # Set to known value
+ self.runCmd ("settings set stop-disassembly-display always ") # Set to new value with trailing whitespaces
+ self.expect ("settings show stop-disassembly-display", SETTING_MSG("stop-disassembly-display"),
+ startstr = 'stop-disassembly-display (enum) = always')
+ self.runCmd("settings clear stop-disassembly-display", check=False)
+ # language
+ self.runCmd ("settings set target.language c89") # Set to known value
+ self.runCmd ("settings set target.language go ") # Set to new value with trailing whitespace
+ self.expect ("settings show target.language", SETTING_MSG("target.language"),
+ startstr = "target.language (language) = go")
+ self.runCmd("settings clear target.language", check=False)
+ # arguments
+ self.runCmd ("settings set target.run-args 1 2 3") # Set to known value
+ self.runCmd ("settings set target.run-args 3 4 5 ") # Set to new value with trailing whitespaces
+ self.expect ("settings show target.run-args", SETTING_MSG("target.run-args"),
+ substrs = [ 'target.run-args (arguments) =',
+ '[0]: "3"',
+ '[1]: "4"',
+ '[2]: "5"' ])
+ self.runCmd ("settings set target.run-args 1 2 3") # Set to known value
+ self.runCmd ("settings set target.run-args 3 \ \ ") # Set to new value with trailing whitespaces
+ self.expect ("settings show target.run-args", SETTING_MSG("target.run-args"),
+ substrs = [ 'target.run-args (arguments) =',
+ '[0]: "3"',
+ '[1]: " "',
+ '[2]: " "' ])
+ self.runCmd("settings clear target.run-args", check=False)
+ # dictionaries
+ self.runCmd ("settings clear target.env-vars") # Set to known value
+ self.runCmd ("settings set target.env-vars A=B C=D\t ") # Set to new value with trailing whitespaces
+ self.expect ("settings show target.env-vars", SETTING_MSG("target.env-vars"),
+ substrs = [ 'target.env-vars (dictionary of strings) =',
+ 'A=B',
+ 'C=D'])
+ self.runCmd("settings clear target.env-vars", check=False)
+ # regex
+ self.runCmd ("settings clear target.process.thread.step-avoid-regexp") # Set to known value
+ self.runCmd ("settings set target.process.thread.step-avoid-regexp foo\\ ") # Set to new value with trailing whitespaces
+ self.expect ("settings show target.process.thread.step-avoid-regexp",
+ SETTING_MSG("target.process.thread.step-avoid-regexp"),
+ substrs = [ 'target.process.thread.step-avoid-regexp (regex) = foo\\ '])
+ self.runCmd("settings clear target.process.thread.step-avoid-regexp", check=False)
+ # format-string
+ self.runCmd ("settings clear disassembly-format") # Set to known value
+ self.runCmd ("settings set disassembly-format foo ") # Set to new value with trailing whitespaces
+ self.expect ("settings show disassembly-format",
+ SETTING_MSG("disassembly-format"),
+ substrs = [ 'disassembly-format (format-string) = "foo "'])
+ self.runCmd("settings clear disassembly-format", check=False)
+
+ @no_debug_info_test
+ def test_all_settings_exist (self):
+ self.expect ("settings show",
+ substrs = [ "auto-confirm",
+ "frame-format",
+ "notify-void",
+ "prompt",
+ "script-lang",
+ "stop-disassembly-count",
+ "stop-disassembly-display",
+ "stop-line-count-after",
+ "stop-line-count-before",
+ "term-width",
+ "thread-format",
+ "use-external-editor",
+ "target.default-arch",
+ "target.move-to-nearest-code",
+ "target.expr-prefix",
+ "target.language",
+ "target.prefer-dynamic-value",
+ "target.enable-synthetic-value",
+ "target.skip-prologue",
+ "target.source-map",
+ "target.exec-search-paths",
+ "target.max-children-count",
+ "target.max-string-summary-length",
+ "target.breakpoints-use-platform-avoid-list",
+ "target.run-args",
+ "target.env-vars",
+ "target.inherit-env",
+ "target.input-path",
+ "target.output-path",
+ "target.error-path",
+ "target.disable-aslr",
+ "target.disable-stdio",
+ "target.x86-disassembly-flavor",
+ "target.use-hex-immediates",
+ "target.hex-immediate-style",
+ "target.process.disable-memory-cache",
+ "target.process.extra-startup-command",
+ "target.process.thread.step-avoid-regexp",
+ "target.process.thread.trace-thread"])
diff --git a/packages/Python/lldbsuite/test/settings/main.cpp b/packages/Python/lldbsuite/test/settings/main.cpp
new file mode 100644
index 000000000000..cf2b16b0089b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/settings/main.cpp
@@ -0,0 +1,75 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <cstdlib>
+#include <string>
+#include <fstream>
+#include <iostream>
+
+int numberfn()
+{
+ return 0x5a;
+}
+
+int
+main(int argc, char const *argv[])
+{
+ // The program writes its output to the following file:
+ //
+ // o "output1.txt" for test_pass_host_env_vars() test case
+ // o "output2.txt" for test_run_args_and_env_vars_with_dsym() test case
+ // o "output2.txt" for test_run_args_and_env_vars_with_dwarf() test case
+ std::ofstream outfile;
+ if (argc == 1)
+ outfile.open("output1.txt");
+ else
+ outfile.open("output2.txt");
+
+ for (unsigned i = 0; i < argc; ++i) {
+ std::string theArg(argv[i]);
+ if (i == 1 && "A" == theArg)
+ outfile << "argv[1] matches\n";
+
+ if (i == 2 && "B" == theArg)
+ outfile << "argv[2] matches\n";
+
+ if (i == 3 && "C" == theArg)
+ outfile << "argv[3] matches\n";
+ }
+
+ // For passing environment vars from the debugger to the launched process.
+ if (::getenv("MY_ENV_VAR")) {
+ std::string MY_ENV_VAR(getenv("MY_ENV_VAR"));
+ if ("YES" == MY_ENV_VAR) {
+ outfile << "Environment variable 'MY_ENV_VAR' successfully passed.\n";
+ }
+ }
+
+
+ // For passing host environment vars to the launched process.
+ if (::getenv("MY_HOST_ENV_VAR1")) {
+ std::string MY_HOST_ENV_VAR1(getenv("MY_HOST_ENV_VAR1"));
+ if ("VAR1" == MY_HOST_ENV_VAR1) {
+ outfile << "The host environment variable 'MY_HOST_ENV_VAR1' successfully passed.\n";
+ }
+ }
+
+ if (::getenv("MY_HOST_ENV_VAR2")) {
+ std::string MY_HOST_ENV_VAR2(getenv("MY_HOST_ENV_VAR2"));
+ if ("VAR2" == MY_HOST_ENV_VAR2) {
+ outfile << "The host environment variable 'MY_HOST_ENV_VAR2' successfully passed.\n";
+ }
+ }
+
+ std::cerr << "This message should go to standard error.\n";
+ std::cout << "This message should go to standard out.\n";
+
+ outfile.close();
+ return numberfn();
+}
diff --git a/packages/Python/lldbsuite/test/settings/quoting/Makefile b/packages/Python/lldbsuite/test/settings/quoting/Makefile
new file mode 100644
index 000000000000..0d70f2595019
--- /dev/null
+++ b/packages/Python/lldbsuite/test/settings/quoting/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/settings/quoting/TestQuoting.py b/packages/Python/lldbsuite/test/settings/quoting/TestQuoting.py
new file mode 100644
index 000000000000..878fc8a50675
--- /dev/null
+++ b/packages/Python/lldbsuite/test/settings/quoting/TestQuoting.py
@@ -0,0 +1,92 @@
+"""
+Test quoting of arguments to lldb commands
+"""
+
+from __future__ import print_function
+
+
+
+import os, time, re
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class SettingsCommandTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @classmethod
+ def classCleanup(cls):
+ """Cleanup the test byproducts."""
+ cls.RemoveTempFile("stdout.txt")
+
+ @no_debug_info_test
+ def test_no_quote(self):
+ self.do_test_args("a b c", "a\0b\0c\0")
+
+ @expectedFailureWindows("http://llvm.org/pr24557")
+ @no_debug_info_test
+ def test_single_quote(self):
+ self.do_test_args("'a b c'", "a b c\0")
+
+ @no_debug_info_test
+ def test_double_quote(self):
+ self.do_test_args('"a b c"', "a b c\0")
+
+ @expectedFailureWindows("http://llvm.org/pr24557")
+ @no_debug_info_test
+ def test_single_quote_escape(self):
+ self.do_test_args("'a b\\' c", "a b\\\0c\0")
+
+ @expectedFailureWindows("http://llvm.org/pr24557")
+ @no_debug_info_test
+ def test_double_quote_escape(self):
+ self.do_test_args('"a b\\" c"', 'a b" c\0')
+
+ @expectedFailureWindows("http://llvm.org/pr24557")
+ @no_debug_info_test
+ def test_double_quote_escape2(self):
+ self.do_test_args('"a b\\\\" c', 'a b\\\0c\0')
+
+ @no_debug_info_test
+ def test_single_in_double(self):
+ self.do_test_args('"a\'b"', "a'b\0")
+
+ @expectedFailureWindows("http://llvm.org/pr24557")
+ @no_debug_info_test
+ def test_double_in_single(self):
+ self.do_test_args("'a\"b'", 'a"b\0')
+
+ @no_debug_info_test
+ def test_combined(self):
+ self.do_test_args('"a b"c\'d e\'', 'a bcd e\0')
+
+ @no_debug_info_test
+ def test_bare_single(self):
+ self.do_test_args("a\\'b", "a'b\0")
+
+ @expectedFailureWindows("http://llvm.org/pr24557")
+ @no_debug_info_test
+ def test_bare_double(self):
+ self.do_test_args('a\\"b', 'a"b\0')
+
+ def do_test_args(self, args_in, args_out):
+ """Test argument parsing. Run the program with args_in. The program dumps its arguments
+ to stdout. Compare the stdout with args_out."""
+ self.buildDefault()
+
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ self.runCmd("process launch -o stdout.txt -- " + args_in)
+
+ if lldb.remote_platform:
+ src_file_spec = lldb.SBFileSpec('stdout.txt', False)
+ dst_file_spec = lldb.SBFileSpec('stdout.txt', True)
+ lldb.remote_platform.Get(src_file_spec, dst_file_spec)
+
+ with open('stdout.txt', 'r') as f:
+ output = f.read()
+
+ self.RemoveTempFile("stdout.txt")
+
+ self.assertEqual(output, args_out)
diff --git a/packages/Python/lldbsuite/test/settings/quoting/main.c b/packages/Python/lldbsuite/test/settings/quoting/main.c
new file mode 100644
index 000000000000..6e01c2d1cd87
--- /dev/null
+++ b/packages/Python/lldbsuite/test/settings/quoting/main.c
@@ -0,0 +1,13 @@
+#include <stdio.h>
+#include <string.h>
+
+/* This program writes its arguments (separated by '\0') to stdout. */
+int
+main(int argc, char const *argv[])
+{
+ int i;
+ for (i = 1; i < argc; ++i)
+ fwrite(argv[i], strlen(argv[i])+1, 1, stdout);
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/source-manager/Makefile b/packages/Python/lldbsuite/test/source-manager/Makefile
new file mode 100644
index 000000000000..d6cd0db0506f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/source-manager/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../make
+
+C_SOURCES := main.c
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/source-manager/TestSourceManager.py b/packages/Python/lldbsuite/test/source-manager/TestSourceManager.py
new file mode 100644
index 000000000000..b4e7541a709a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/source-manager/TestSourceManager.py
@@ -0,0 +1,172 @@
+"""
+Test lldb core component: SourceManager.
+
+Test cases:
+
+o test_display_source_python:
+ Test display of source using the SBSourceManager API.
+o test_modify_source_file_while_debugging:
+ Test the caching mechanism of the source manager.
+"""
+
+from __future__ import print_function
+
+
+
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class SourceManagerTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # Find the line number to break inside main().
+ self.line = line_number('main.c', '// Set break point at this line.')
+
+ @add_test_categories(['pyapi'])
+ def test_display_source_python(self):
+ """Test display of source using the SBSourceManager API."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ target = self.dbg.CreateTarget(exe)
+ self.assertTrue(target, VALID_TARGET)
+
+ # Launch the process, and do not stop at the entry point.
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+
+ #
+ # Exercise Python APIs to display source lines.
+ #
+
+ # Create the filespec for 'main.c'.
+ filespec = lldb.SBFileSpec('main.c', False)
+ source_mgr = self.dbg.GetSourceManager()
+ # Use a string stream as the destination.
+ stream = lldb.SBStream()
+ source_mgr.DisplaySourceLinesWithLineNumbers(filespec,
+ self.line,
+ 2, # context before
+ 2, # context after
+ "=>", # prefix for current line
+ stream)
+
+ # 2
+ # 3 int main(int argc, char const *argv[]) {
+ # => 4 printf("Hello world.\n"); // Set break point at this line.
+ # 5 return 0;
+ # 6 }
+ self.expect(stream.GetData(), "Source code displayed correctly",
+ exe=False,
+ patterns = ['=> %d.*Hello world' % self.line])
+
+ # Boundary condition testings for SBStream(). LLDB should not crash!
+ stream.Print(None)
+ stream.RedirectToFile(None, True)
+
+ def test_move_and_then_display_source(self):
+ """Test that target.source-map settings work by moving main.c to hidden/main.c."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ # Move main.c to hidden/main.c.
+ main_c = "main.c"
+ main_c_hidden = os.path.join("hidden", main_c)
+ os.rename(main_c, main_c_hidden)
+
+ if self.TraceOn():
+ system([["ls"]])
+ system([["ls", "hidden"]])
+
+ # Restore main.c after the test.
+ self.addTearDownHook(lambda: os.rename(main_c_hidden, main_c))
+
+ # Set target.source-map settings.
+ self.runCmd("settings set target.source-map %s %s" % (os.getcwd(), os.path.join(os.getcwd(), "hidden")))
+ # And verify that the settings work.
+ self.expect("settings show target.source-map",
+ substrs = [os.getcwd(), os.path.join(os.getcwd(), "hidden")])
+
+ # Display main() and verify that the source mapping has been kicked in.
+ self.expect("source list -n main", SOURCE_DISPLAYED_CORRECTLY,
+ substrs = ['Hello world'])
+
+ def test_modify_source_file_while_debugging(self):
+ """Modify a source file while debugging the executable."""
+ self.build()
+ exe = os.path.join(os.getcwd(), "a.out")
+ self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "main.c", self.line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ # The stop reason of the thread should be breakpoint.
+ self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = ['stopped',
+ 'main.c:%d' % self.line,
+ 'stop reason = breakpoint'])
+
+ # Display some source code.
+ self.expect("source list -f main.c -l %d" % self.line, SOURCE_DISPLAYED_CORRECTLY,
+ substrs = ['Hello world'])
+
+ # The '-b' option shows the line table locations from the debug information
+ # that indicates valid places to set source level breakpoints.
+
+ # The file to display is implicit in this case.
+ self.runCmd("source list -l %d -c 3 -b" % self.line)
+ output = self.res.GetOutput().splitlines()[0]
+
+ # If the breakpoint set command succeeded, we should expect a positive number
+ # of breakpoints for the current line, i.e., self.line.
+ import re
+ m = re.search('^\[(\d+)\].*// Set break point at this line.', output)
+ if not m:
+ self.fail("Fail to display source level breakpoints")
+ self.assertTrue(int(m.group(1)) > 0)
+
+ # Read the main.c file content.
+ with open('main.c', 'r') as f:
+ original_content = f.read()
+ if self.TraceOn():
+ print("original content:", original_content)
+
+ # Modify the in-memory copy of the original source code.
+ new_content = original_content.replace('Hello world', 'Hello lldb', 1)
+
+ # This is the function to restore the original content.
+ def restore_file():
+ #print("os.path.getmtime() before restore:", os.path.getmtime('main.c'))
+ time.sleep(1)
+ with open('main.c', 'wb') as f:
+ f.write(original_content)
+ if self.TraceOn():
+ with open('main.c', 'r') as f:
+ print("content restored to:", f.read())
+ # Touch the file just to be sure.
+ os.utime('main.c', None)
+ if self.TraceOn():
+ print("os.path.getmtime() after restore:", os.path.getmtime('main.c'))
+
+
+
+ # Modify the source code file.
+ with open('main.c', 'wb') as f:
+ time.sleep(1)
+ f.write(new_content)
+ if self.TraceOn():
+ print("new content:", new_content)
+ print("os.path.getmtime() after writing new content:", os.path.getmtime('main.c'))
+ # Add teardown hook to restore the file to the original content.
+ self.addTearDownHook(restore_file)
+
+ # Display the source code again. We should see the updated line.
+ self.expect("source list -f main.c -l %d" % self.line, SOURCE_DISPLAYED_CORRECTLY,
+ substrs = ['Hello lldb'])
diff --git a/packages/Python/lldbsuite/test/source-manager/hidden/.keep b/packages/Python/lldbsuite/test/source-manager/hidden/.keep
new file mode 100644
index 000000000000..e69de29bb2d1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/source-manager/hidden/.keep
diff --git a/packages/Python/lldbsuite/test/source-manager/main.c b/packages/Python/lldbsuite/test/source-manager/main.c
new file mode 100644
index 000000000000..9f62166357ce
--- /dev/null
+++ b/packages/Python/lldbsuite/test/source-manager/main.c
@@ -0,0 +1,6 @@
+#include <stdio.h>
+
+int main(int argc, char const *argv[]) {
+ printf("Hello world.\n"); // Set break point at this line.
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/terminal/TestSTTYBeforeAndAfter.py b/packages/Python/lldbsuite/test/terminal/TestSTTYBeforeAndAfter.py
new file mode 100644
index 000000000000..335042737d44
--- /dev/null
+++ b/packages/Python/lldbsuite/test/terminal/TestSTTYBeforeAndAfter.py
@@ -0,0 +1,121 @@
+"""
+Test that 'stty -a' displays the same output before and after running the lldb command.
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+
+class TestSTTYBeforeAndAfter(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @classmethod
+ def classCleanup(cls):
+ """Cleanup the test byproducts."""
+ cls.RemoveTempFile("child_send1.txt")
+ cls.RemoveTempFile("child_read1.txt")
+ cls.RemoveTempFile("child_send2.txt")
+ cls.RemoveTempFile("child_read2.txt")
+
+ @expectedFailureHostWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ @no_debug_info_test
+ def test_stty_dash_a_before_and_afetr_invoking_lldb_command(self):
+ """Test that 'stty -a' displays the same output before and after running the lldb command."""
+ import pexpect
+ if not which('expect'):
+ self.skipTest("The 'expect' program cannot be located, skip the test")
+
+ # The expect prompt.
+ expect_prompt = "expect[0-9.]+> "
+ # The default lldb prompt.
+ lldb_prompt = "(lldb) "
+
+ # So that the child gets torn down after the test.
+ self.child = pexpect.spawn('expect')
+ child = self.child
+
+ child.expect(expect_prompt)
+ child.setecho(True)
+ if self.TraceOn():
+ child.logfile = sys.stdout
+
+ if self.platformIsDarwin():
+ child.sendline('set env(TERM) xterm')
+ else:
+ child.sendline('set env(TERM) vt100')
+ child.expect(expect_prompt)
+ child.sendline('puts $env(TERM)')
+ child.expect(expect_prompt)
+
+ # Turn on loggings for input/output to/from the child.
+ with open('child_send1.txt', 'w') as f_send1:
+ with open('child_read1.txt', 'w') as f_read1:
+ child.logfile_send = f_send1
+ child.logfile_read = f_read1
+
+ child.sendline('stty -a')
+ child.expect(expect_prompt)
+
+ # Now that the stage1 logging is done, restore logfile to None to
+ # stop further logging.
+ child.logfile_send = None
+ child.logfile_read = None
+
+ # Invoke the lldb command.
+ child.sendline('%s %s' % (lldbtest_config.lldbExec, self.lldbOption))
+ child.expect_exact(lldb_prompt)
+
+ # Immediately quit.
+ child.sendline('quit')
+ child.expect(expect_prompt)
+
+ with open('child_send2.txt', 'w') as f_send2:
+ with open('child_read2.txt', 'w') as f_read2:
+ child.logfile_send = f_send2
+ child.logfile_read = f_read2
+
+ child.sendline('stty -a')
+ child.expect(expect_prompt)
+
+ child.sendline('exit')
+
+ # Now that the stage2 logging is done, restore logfile to None to
+ # stop further logging.
+ child.logfile_send = None
+ child.logfile_read = None
+
+ with open('child_send1.txt', 'r') as fs:
+ if self.TraceOn():
+ print("\n\nContents of child_send1.txt:")
+ print(fs.read())
+ with open('child_read1.txt', 'r') as fr:
+ from_child1 = fr.read()
+ if self.TraceOn():
+ print("\n\nContents of child_read1.txt:")
+ print(from_child1)
+
+ with open('child_send2.txt', 'r') as fs:
+ if self.TraceOn():
+ print("\n\nContents of child_send2.txt:")
+ print(fs.read())
+ with open('child_read2.txt', 'r') as fr:
+ from_child2 = fr.read()
+ if self.TraceOn():
+ print("\n\nContents of child_read2.txt:")
+ print(from_child2)
+
+ stty_output1_lines = from_child1.splitlines()
+ stty_output2_lines = from_child2.splitlines()
+ zipped = list(zip(stty_output1_lines, stty_output2_lines))
+ for tuple in zipped:
+ if self.TraceOn():
+ print("tuple->%s" % str(tuple))
+ # Every line should compare equal until the first blank line.
+ if len(tuple[0]) == 0:
+ break
+ self.assertTrue(tuple[0] == tuple[1])
diff --git a/packages/Python/lldbsuite/test/test_categories.py b/packages/Python/lldbsuite/test/test_categories.py
new file mode 100644
index 000000000000..e3e446091050
--- /dev/null
+++ b/packages/Python/lldbsuite/test/test_categories.py
@@ -0,0 +1,70 @@
+"""
+Provides definitions for various lldb test categories
+"""
+
+from __future__ import absolute_import
+from __future__ import print_function
+
+# System modules
+import sys
+
+# Third-party modules
+
+# LLDB modules
+
+debug_info_categories = [
+ 'dwarf', 'dwo', 'dsym'
+]
+
+all_categories = {
+ 'dataformatters': 'Tests related to the type command and the data formatters subsystem',
+ 'dwarf' : 'Tests that can be run with DWARF debug information',
+ 'dwo' : 'Tests that can be run with DWO debug information',
+ 'dsym' : 'Tests that can be run with DSYM debug information',
+ 'expression' : 'Tests related to the expression parser',
+ 'objc' : 'Tests related to the Objective-C programming language support',
+ 'pyapi' : 'Tests related to the Python API',
+ 'basic_process' : 'Basic process execution sniff tests.',
+ 'cmdline' : 'Tests related to the LLDB command-line interface',
+ 'dyntype' : 'Tests related to dynamic type support',
+ 'stresstest' : 'Tests related to stressing lldb limits',
+ 'flakey' : 'Flakey test cases, i.e. tests that do not reliably pass at each execution',
+ 'lldb-mi' : 'lldb-mi tests'
+}
+
+def unique_string_match(yourentry, list):
+ candidate = None
+ for item in list:
+ if not item.startswith(yourentry):
+ continue
+ if candidate:
+ return None
+ candidate = item
+ return candidate
+
+def is_supported_on_platform(category, platform):
+ if category == "dwo":
+ return platform in ["linux", "freebsd", "windows"]
+ elif category == "dsym":
+ return platform in ["darwin", "macosx", "ios"]
+ return True
+
+def validate(categories, exact_match):
+ """
+ For each category in categories, ensure that it's a valid category (if exact_match is false,
+ unique prefixes are also accepted). If a category is invalid, print a message and quit.
+ If all categories are valid, return the list of categories. Prefixes are expanded in the
+ returned list.
+ """
+ result = []
+ for category in categories:
+ origCategory = category
+ if category not in all_categories and not exact_match:
+ category = unique_string_match(category, all_categories)
+ if (category not in all_categories) or category == None:
+ print("fatal error: category '" + origCategory + "' is not a valid category")
+ print("if you have added a new category, please edit test_categories.py, adding your new category to all_categories")
+ print("else, please specify one or more of the following: " + str(list(all_categories.keys())))
+ sys.exit(1)
+ result.append(category)
+ return result
diff --git a/packages/Python/lldbsuite/test/test_result.py b/packages/Python/lldbsuite/test/test_result.py
new file mode 100644
index 000000000000..9665d672a79a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/test_result.py
@@ -0,0 +1,224 @@
+"""
+ The LLVM Compiler Infrastructure
+
+This file is distributed under the University of Illinois Open Source
+License. See LICENSE.TXT for details.
+
+Provides the LLDBTestResult class, which holds information about progress
+and results of a single test run.
+"""
+
+from __future__ import absolute_import
+from __future__ import print_function
+
+# System modules
+import inspect
+
+# Third-party modules
+import unittest2
+
+# LLDB Modules
+import lldbsuite
+from . import configuration
+from .result_formatter import EventBuilder
+
+
+class LLDBTestResult(unittest2.TextTestResult):
+ """
+ Enforce a singleton pattern to allow introspection of test progress.
+
+ Overwrite addError(), addFailure(), and addExpectedFailure() methods
+ to enable each test instance to track its failure/error status. It
+ is used in the LLDB test framework to emit detailed trace messages
+ to a log file for easier human inspection of test failures/errors.
+ """
+ __singleton__ = None
+ __ignore_singleton__ = False
+
+ @staticmethod
+ def getTerminalSize():
+ import os
+ env = os.environ
+ def ioctl_GWINSZ(fd):
+ try:
+ import fcntl, termios, struct, os
+ cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,
+ '1234'))
+ except:
+ return
+ return cr
+ cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
+ if not cr:
+ try:
+ fd = os.open(os.ctermid(), os.O_RDONLY)
+ cr = ioctl_GWINSZ(fd)
+ os.close(fd)
+ except:
+ pass
+ if not cr:
+ cr = (env.get('LINES', 25), env.get('COLUMNS', 80))
+ return int(cr[1]), int(cr[0])
+
+ def __init__(self, *args):
+ if not LLDBTestResult.__ignore_singleton__ and LLDBTestResult.__singleton__:
+ raise Exception("LLDBTestResult instantiated more than once")
+ super(LLDBTestResult, self).__init__(*args)
+ LLDBTestResult.__singleton__ = self
+ # Now put this singleton into the lldb module namespace.
+ configuration.test_result = self
+ # Computes the format string for displaying the counter.
+ counterWidth = len(str(configuration.suite.countTestCases()))
+ self.fmt = "%" + str(counterWidth) + "d: "
+ self.indentation = ' ' * (counterWidth + 2)
+ # This counts from 1 .. suite.countTestCases().
+ self.counter = 0
+ (width, height) = LLDBTestResult.getTerminalSize()
+ self.results_formatter = configuration.results_formatter_object
+
+ def _config_string(self, test):
+ compiler = getattr(test, "getCompiler", None)
+ arch = getattr(test, "getArchitecture", None)
+ return "%s-%s" % (compiler() if compiler else "", arch() if arch else "")
+
+ def _exc_info_to_string(self, err, test):
+ """Overrides superclass TestResult's method in order to append
+ our test config info string to the exception info string."""
+ if hasattr(test, "getArchitecture") and hasattr(test, "getCompiler"):
+ return '%sConfig=%s-%s' % (super(LLDBTestResult, self)._exc_info_to_string(err, test),
+ test.getArchitecture(),
+ test.getCompiler())
+ else:
+ return super(LLDBTestResult, self)._exc_info_to_string(err, test)
+
+ def getDescription(self, test):
+ doc_first_line = test.shortDescription()
+ if self.descriptions and doc_first_line:
+ return '\n'.join((str(test), self.indentation + doc_first_line))
+ else:
+ return str(test)
+
+ def getCategoriesForTest(self, test):
+ """
+ Gets all the categories for the currently running test method in test case
+ """
+ test_categories = []
+ test_method = getattr(test, test._testMethodName)
+ if test_method != None and hasattr(test_method, "categories"):
+ test_categories.extend(test_method.categories)
+
+ test_categories.extend(test.getCategories())
+
+ return test_categories
+
+ def hardMarkAsSkipped(self,test):
+ getattr(test, test._testMethodName).__func__.__unittest_skip__ = True
+ getattr(test, test._testMethodName).__func__.__unittest_skip_why__ = "test case does not fall in any category of interest for this run"
+ test.__class__.__unittest_skip__ = True
+ test.__class__.__unittest_skip_why__ = "test case does not fall in any category of interest for this run"
+
+ def startTest(self, test):
+ if configuration.shouldSkipBecauseOfCategories(self.getCategoriesForTest(test)):
+ self.hardMarkAsSkipped(test)
+ configuration.setCrashInfoHook("%s at %s" % (str(test),inspect.getfile(test.__class__)))
+ self.counter += 1
+ #if self.counter == 4:
+ # import crashinfo
+ # crashinfo.testCrashReporterDescription(None)
+ test.test_number = self.counter
+ if self.showAll:
+ self.stream.write(self.fmt % self.counter)
+ super(LLDBTestResult, self).startTest(test)
+ if self.results_formatter:
+ self.results_formatter.handle_event(
+ EventBuilder.event_for_start(test))
+
+ def addSuccess(self, test):
+ super(LLDBTestResult, self).addSuccess(test)
+ if configuration.parsable:
+ self.stream.write("PASS: LLDB (%s) :: %s\n" % (self._config_string(test), str(test)))
+ if self.results_formatter:
+ self.results_formatter.handle_event(
+ EventBuilder.event_for_success(test))
+
+ def addError(self, test, err):
+ configuration.sdir_has_content = True
+ super(LLDBTestResult, self).addError(test, err)
+ method = getattr(test, "markError", None)
+ if method:
+ method()
+ if configuration.parsable:
+ self.stream.write("FAIL: LLDB (%s) :: %s\n" % (self._config_string(test), str(test)))
+ if self.results_formatter:
+ self.results_formatter.handle_event(
+ EventBuilder.event_for_error(test, err))
+
+ def addCleanupError(self, test, err):
+ configuration.sdir_has_content = True
+ super(LLDBTestResult, self).addCleanupError(test, err)
+ method = getattr(test, "markCleanupError", None)
+ if method:
+ method()
+ if configuration.parsable:
+ self.stream.write("CLEANUP ERROR: LLDB (%s) :: %s\n" % (self._config_string(test), str(test)))
+ if self.results_formatter:
+ self.results_formatter.handle_event(
+ EventBuilder.event_for_cleanup_error(
+ test, err))
+
+ def addFailure(self, test, err):
+ configuration.sdir_has_content = True
+ super(LLDBTestResult, self).addFailure(test, err)
+ method = getattr(test, "markFailure", None)
+ if method:
+ method()
+ if configuration.parsable:
+ self.stream.write("FAIL: LLDB (%s) :: %s\n" % (self._config_string(test), str(test)))
+ if configuration.useCategories:
+ test_categories = self.getCategoriesForTest(test)
+ for category in test_categories:
+ if category in configuration.failuresPerCategory:
+ configuration.failuresPerCategory[category] = configuration.failuresPerCategory[category] + 1
+ else:
+ configuration.failuresPerCategory[category] = 1
+ if self.results_formatter:
+ self.results_formatter.handle_event(
+ EventBuilder.event_for_failure(test, err))
+
+
+ def addExpectedFailure(self, test, err, bugnumber):
+ configuration.sdir_has_content = True
+ super(LLDBTestResult, self).addExpectedFailure(test, err, bugnumber)
+ method = getattr(test, "markExpectedFailure", None)
+ if method:
+ method(err, bugnumber)
+ if configuration.parsable:
+ self.stream.write("XFAIL: LLDB (%s) :: %s\n" % (self._config_string(test), str(test)))
+ if self.results_formatter:
+ self.results_formatter.handle_event(
+ EventBuilder.event_for_expected_failure(
+ test, err, bugnumber))
+
+ def addSkip(self, test, reason):
+ configuration.sdir_has_content = True
+ super(LLDBTestResult, self).addSkip(test, reason)
+ method = getattr(test, "markSkippedTest", None)
+ if method:
+ method()
+ if configuration.parsable:
+ self.stream.write("UNSUPPORTED: LLDB (%s) :: %s (%s) \n" % (self._config_string(test), str(test), reason))
+ if self.results_formatter:
+ self.results_formatter.handle_event(
+ EventBuilder.event_for_skip(test, reason))
+
+ def addUnexpectedSuccess(self, test, bugnumber):
+ configuration.sdir_has_content = True
+ super(LLDBTestResult, self).addUnexpectedSuccess(test, bugnumber)
+ method = getattr(test, "markUnexpectedSuccess", None)
+ if method:
+ method(bugnumber)
+ if configuration.parsable:
+ self.stream.write("XPASS: LLDB (%s) :: %s\n" % (self._config_string(test), str(test)))
+ if self.results_formatter:
+ self.results_formatter.handle_event(
+ EventBuilder.event_for_unexpected_success(
+ test, bugnumber))
diff --git a/packages/Python/lldbsuite/test/test_runner/README.txt b/packages/Python/lldbsuite/test/test_runner/README.txt
new file mode 100644
index 000000000000..bb40870e7965
--- /dev/null
+++ b/packages/Python/lldbsuite/test/test_runner/README.txt
@@ -0,0 +1,5 @@
+This directory contains source and tests for the lldb test runner
+architecture. This directory is not for lldb python tests. It
+is the test runner. The tests under this diretory are test-runner
+tests (i.e. tests that verify the test runner itself runs properly).
+
diff --git a/packages/Python/lldbsuite/test/test_runner/lib/lldb_utils.py b/packages/Python/lldbsuite/test/test_runner/lib/lldb_utils.py
new file mode 100644
index 000000000000..e469bbf12207
--- /dev/null
+++ b/packages/Python/lldbsuite/test/test_runner/lib/lldb_utils.py
@@ -0,0 +1,66 @@
+"""
+The LLVM Compiler Infrastructure
+
+This file is distributed under the University of Illinois Open Source
+License. See LICENSE.TXT for details.
+
+Provides classes used by the test results reporting infrastructure
+within the LLDB test suite.
+
+
+This module contains utilities used by the lldb test framwork.
+"""
+
+
+class OptionalWith(object):
+ # pylint: disable=too-few-public-methods
+ # This is a wrapper - it is not meant to provide any extra methods.
+ """Provides a wrapper for objects supporting "with", allowing None.
+
+ This lets a user use the "with object" syntax for resource usage
+ (e.g. locks) even when the wrapped with object is None.
+
+ e.g.
+
+ wrapped_lock = OptionalWith(thread.Lock())
+ with wrapped_lock:
+ # Do something while the lock is obtained.
+ pass
+
+ might_be_none = None
+ wrapped_none = OptionalWith(might_be_none)
+ with wrapped_none:
+ # This code here still works.
+ pass
+
+ This prevents having to write code like this when
+ a lock is optional:
+
+ if lock:
+ lock.acquire()
+
+ try:
+ code_fragament_always_run()
+ finally:
+ if lock:
+ lock.release()
+
+ And I'd posit it is safer, as it becomes impossible to
+ forget the try/finally using OptionalWith(), since
+ the with syntax can be used.
+ """
+ def __init__(self, wrapped_object):
+ self.wrapped_object = wrapped_object
+
+ def __enter__(self):
+ if self.wrapped_object is not None:
+ return self.wrapped_object.__enter__()
+ else:
+ return self
+
+ def __exit__(self, the_type, value, traceback):
+ if self.wrapped_object is not None:
+ return self.wrapped_object.__exit__(the_type, value, traceback)
+ else:
+ # Don't suppress any exceptions
+ return False
diff --git a/packages/Python/lldbsuite/test/test_runner/lib/process_control.py b/packages/Python/lldbsuite/test/test_runner/lib/process_control.py
new file mode 100644
index 000000000000..a7e639e4b8b6
--- /dev/null
+++ b/packages/Python/lldbsuite/test/test_runner/lib/process_control.py
@@ -0,0 +1,705 @@
+"""
+The LLVM Compiler Infrastructure
+
+This file is distributed under the University of Illinois Open Source
+License. See LICENSE.TXT for details.
+
+Provides classes used by the test results reporting infrastructure
+within the LLDB test suite.
+
+
+This module provides process-management support for the LLDB test
+running infrasructure.
+"""
+
+# System imports
+import os
+import re
+import signal
+import subprocess
+import sys
+import threading
+
+
+class CommunicatorThread(threading.Thread):
+ """Provides a thread class that communicates with a subprocess."""
+ def __init__(self, process, event, output_file):
+ super(CommunicatorThread, self).__init__()
+ # Don't let this thread prevent shutdown.
+ self.daemon = True
+ self.process = process
+ self.pid = process.pid
+ self.event = event
+ self.output_file = output_file
+ self.output = None
+
+ def run(self):
+ try:
+ # Communicate with the child process.
+ # This will not complete until the child process terminates.
+ self.output = self.process.communicate()
+ except Exception as exception: # pylint: disable=broad-except
+ if self.output_file:
+ self.output_file.write(
+ "exception while using communicate() for pid: {}\n".format(
+ exception))
+ finally:
+ # Signal that the thread's run is complete.
+ self.event.set()
+
+
+# Provides a regular expression for matching gtimeout-based durations.
+TIMEOUT_REGEX = re.compile(r"(^\d+)([smhd])?$")
+
+
+def timeout_to_seconds(timeout):
+ """Converts timeout/gtimeout timeout values into seconds.
+
+ @param timeout a timeout in the form of xm representing x minutes.
+
+ @return None if timeout is None, or the number of seconds as a float
+ if a valid timeout format was specified.
+ """
+ if timeout is None:
+ return None
+ else:
+ match = TIMEOUT_REGEX.match(timeout)
+ if match:
+ value = float(match.group(1))
+ units = match.group(2)
+ if units is None:
+ # default is seconds. No conversion necessary.
+ return value
+ elif units == 's':
+ # Seconds. No conversion necessary.
+ return value
+ elif units == 'm':
+ # Value is in minutes.
+ return 60.0 * value
+ elif units == 'h':
+ # Value is in hours.
+ return (60.0 * 60.0) * value
+ elif units == 'd':
+ # Value is in days.
+ return 24 * (60.0 * 60.0) * value
+ else:
+ raise Exception("unexpected units value '{}'".format(units))
+ else:
+ raise Exception("could not parse TIMEOUT spec '{}'".format(
+ timeout))
+
+
+class ProcessHelper(object):
+ """Provides an interface for accessing process-related functionality.
+
+ This class provides a factory method that gives the caller a
+ platform-specific implementation instance of the class.
+
+ Clients of the class should stick to the methods provided in this
+ base class.
+
+ @see ProcessHelper.process_helper()
+ """
+ def __init__(self):
+ super(ProcessHelper, self).__init__()
+
+ @classmethod
+ def process_helper(cls):
+ """Returns a platform-specific ProcessHelper instance.
+ @return a ProcessHelper instance that does the right thing for
+ the current platform.
+ """
+
+ # If you add a new platform, create an instance here and
+ # return it.
+ if os.name == "nt":
+ return WindowsProcessHelper()
+ else:
+ # For all POSIX-like systems.
+ return UnixProcessHelper()
+
+ def create_piped_process(self, command, new_process_group=True):
+ # pylint: disable=no-self-use,unused-argument
+ # As expected. We want derived classes to implement this.
+ """Creates a subprocess.Popen-based class with I/O piped to the parent.
+
+ @param command the command line list as would be passed to
+ subprocess.Popen(). Use the list form rather than the string form.
+
+ @param new_process_group indicates if the caller wants the
+ process to be created in its own process group. Each OS handles
+ this concept differently. It provides a level of isolation and
+ can simplify or enable terminating the process tree properly.
+
+ @return a subprocess.Popen-like object.
+ """
+ raise Exception("derived class must implement")
+
+ def supports_soft_terminate(self):
+ # pylint: disable=no-self-use
+ # As expected. We want derived classes to implement this.
+ """Indicates if the platform supports soft termination.
+
+ Soft termination is the concept of a terminate mechanism that
+ allows the target process to shut down nicely, but with the
+ catch that the process might choose to ignore it.
+
+ Platform supporter note: only mark soft terminate as supported
+ if the target process has some way to evade the soft terminate
+ request; otherwise, just support the hard terminate method.
+
+ @return True if the platform supports a soft terminate mechanism.
+ """
+ # By default, we do not support a soft terminate mechanism.
+ return False
+
+ def soft_terminate(self, popen_process, log_file=None, want_core=True):
+ # pylint: disable=no-self-use,unused-argument
+ # As expected. We want derived classes to implement this.
+ """Attempts to terminate the process in a polite way.
+
+ This terminate method is intended to give the child process a
+ chance to clean up and exit on its own, possibly with a request
+ to drop a core file or equivalent (i.e. [mini-]crashdump, crashlog,
+ etc.) If new_process_group was set in the process creation method
+ and the platform supports it, this terminate call will attempt to
+ kill the whole process tree rooted in this child process.
+
+ @param popen_process the subprocess.Popen-like object returned
+ by one of the process-creation methods of this class.
+
+ @param log_file file-like object used to emit error-related
+ logging info. May be None if no error-related info is desired.
+
+ @param want_core True if the caller would like to get a core
+ dump (or the analogous crash report) from the terminated process.
+ """
+ popen_process.terminate()
+
+ def hard_terminate(self, popen_process, log_file=None):
+ # pylint: disable=no-self-use,unused-argument
+ # As expected. We want derived classes to implement this.
+ """Attempts to terminate the process immediately.
+
+ This terminate method is intended to kill child process in
+ a manner in which the child process has no ability to block,
+ and also has no ability to clean up properly. If new_process_group
+ was specified when creating the process, and if the platform
+ implementation supports it, this will attempt to kill the
+ whole process tree rooted in the child process.
+
+ @param popen_process the subprocess.Popen-like object returned
+ by one of the process-creation methods of this class.
+
+ @param log_file file-like object used to emit error-related
+ logging info. May be None if no error-related info is desired.
+ """
+ popen_process.kill()
+
+ def was_soft_terminate(self, returncode, with_core):
+ # pylint: disable=no-self-use,unused-argument
+ # As expected. We want derived classes to implement this.
+ """Returns if Popen-like object returncode matches soft terminate.
+
+ @param returncode the returncode from the Popen-like object that
+ terminated with a given return code.
+
+ @param with_core indicates whether the returncode should match
+ a core-generating return signal.
+
+ @return True when the returncode represents what the system would
+ issue when a soft_terminate() with the given with_core arg occurred;
+ False otherwise.
+ """
+ if not self.supports_soft_terminate():
+ # If we don't support soft termination on this platform,
+ # then this should always be False.
+ return False
+ else:
+ # Once a platform claims to support soft terminate, it
+ # needs to be able to identify it by overriding this method.
+ raise Exception("platform needs to implement")
+
+ def was_hard_terminate(self, returncode):
+ # pylint: disable=no-self-use,unused-argument
+ # As expected. We want derived classes to implement this.
+ """Returns if Popen-like object returncode matches that of a hard
+ terminate attempt.
+
+ @param returncode the returncode from the Popen-like object that
+ terminated with a given return code.
+
+ @return True when the returncode represents what the system would
+ issue when a hard_terminate() occurred; False
+ otherwise.
+ """
+ raise Exception("platform needs to implement")
+
+ def soft_terminate_signals(self):
+ # pylint: disable=no-self-use
+ """Retrieve signal numbers that can be sent to soft terminate.
+ @return a list of signal numbers that can be sent to soft terminate
+ a process, or None if not applicable.
+ """
+ return None
+
+ def is_exceptional_exit(self, popen_status):
+ """Returns whether the program exit status is exceptional.
+
+ Returns whether the return code from a Popen process is exceptional
+ (e.g. signals on POSIX systems).
+
+ Derived classes should override this if they can detect exceptional
+ program exit.
+
+ @return True if the given popen_status represents an exceptional
+ program exit; False otherwise.
+ """
+ return False
+
+ def exceptional_exit_details(self, popen_status):
+ """Returns the normalized exceptional exit code and a description.
+
+ Given an exceptional exit code, returns the integral value of the
+ exception (e.g. signal number for POSIX) and a description (e.g.
+ signal name on POSIX) for the result.
+
+ Derived classes should override this if they can detect exceptional
+ program exit.
+
+ It is fine to not implement this so long as is_exceptional_exit()
+ always returns False.
+
+ @return (normalized exception code, symbolic exception description)
+ """
+ raise Exception("exception_exit_details() called on unsupported class")
+
+
+class UnixProcessHelper(ProcessHelper):
+ """Provides a ProcessHelper for Unix-like operating systems.
+
+ This implementation supports anything that looks Posix-y
+ (e.g. Darwin, Linux, *BSD, etc.)
+ """
+ def __init__(self):
+ super(UnixProcessHelper, self).__init__()
+
+ @classmethod
+ def _create_new_process_group(cls):
+ """Creates a new process group for the calling process."""
+ os.setpgid(os.getpid(), os.getpid())
+
+ def create_piped_process(self, command, new_process_group=True):
+ # Determine what to run after the fork but before the exec.
+ if new_process_group:
+ preexec_func = self._create_new_process_group
+ else:
+ preexec_func = None
+
+ # Create the process.
+ process = subprocess.Popen(
+ command,
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ universal_newlines=True, # Elicits automatic byte -> string decoding in Py3
+ close_fds=True,
+ preexec_fn=preexec_func)
+
+ # Remember whether we're using process groups for this
+ # process.
+ process.using_process_groups = new_process_group
+ return process
+
+ def supports_soft_terminate(self):
+ # POSIX does support a soft terminate via:
+ # * SIGTERM (no core requested)
+ # * SIGQUIT (core requested if enabled, see ulimit -c)
+ return True
+
+ @classmethod
+ def _validate_pre_terminate(cls, popen_process, log_file):
+ # Validate args.
+ if popen_process is None:
+ raise ValueError("popen_process is None")
+
+ # Ensure we have something that looks like a valid process.
+ if popen_process.pid < 1:
+ if log_file:
+ log_file.write("skipping soft_terminate(): no process id")
+ return False
+
+ # We only do the process liveness check if we're not using
+ # process groups. With process groups, checking if the main
+ # inferior process is dead and short circuiting here is no
+ # good - children of it in the process group could still be
+ # alive, and they should be killed during a timeout.
+ if not popen_process.using_process_groups:
+ # Don't kill if it's already dead.
+ popen_process.poll()
+ if popen_process.returncode is not None:
+ # It has a returncode. It has already stopped.
+ if log_file:
+ log_file.write(
+ "requested to terminate pid {} but it has already "
+ "terminated, returncode {}".format(
+ popen_process.pid, popen_process.returncode))
+ # Move along...
+ return False
+
+ # Good to go.
+ return True
+
+ def _kill_with_signal(self, popen_process, log_file, signum):
+ # Validate we're ready to terminate this.
+ if not self._validate_pre_terminate(popen_process, log_file):
+ return
+
+ # Choose kill mechanism based on whether we're targeting
+ # a process group or just a process.
+ if popen_process.using_process_groups:
+ # if log_file:
+ # log_file.write(
+ # "sending signum {} to process group {} now\n".format(
+ # signum, popen_process.pid))
+ os.killpg(popen_process.pid, signum)
+ else:
+ # if log_file:
+ # log_file.write(
+ # "sending signum {} to process {} now\n".format(
+ # signum, popen_process.pid))
+ os.kill(popen_process.pid, signum)
+
+ def soft_terminate(self, popen_process, log_file=None, want_core=True):
+ # Choose signal based on desire for core file.
+ if want_core:
+ # SIGQUIT will generate core by default. Can be caught.
+ signum = signal.SIGQUIT
+ else:
+ # SIGTERM is the traditional nice way to kill a process.
+ # Can be caught, doesn't generate a core.
+ signum = signal.SIGTERM
+
+ self._kill_with_signal(popen_process, log_file, signum)
+
+ def hard_terminate(self, popen_process, log_file=None):
+ self._kill_with_signal(popen_process, log_file, signal.SIGKILL)
+
+ def was_soft_terminate(self, returncode, with_core):
+ if with_core:
+ return returncode == -signal.SIGQUIT
+ else:
+ return returncode == -signal.SIGTERM
+
+ def was_hard_terminate(self, returncode):
+ return returncode == -signal.SIGKILL
+
+ def soft_terminate_signals(self):
+ return [signal.SIGQUIT, signal.SIGTERM]
+
+ def is_exceptional_exit(self, popen_status):
+ return popen_status < 0
+
+ @classmethod
+ def _signal_names_by_number(cls):
+ return dict(
+ (k, v) for v, k in reversed(sorted(signal.__dict__.items()))
+ if v.startswith('SIG') and not v.startswith('SIG_'))
+
+ def exceptional_exit_details(self, popen_status):
+ signo = -popen_status
+ signal_names_by_number = self._signal_names_by_number()
+ signal_name = signal_names_by_number.get(signo, "")
+ return (signo, signal_name)
+
+class WindowsProcessHelper(ProcessHelper):
+ """Provides a Windows implementation of the ProcessHelper class."""
+ def __init__(self):
+ super(WindowsProcessHelper, self).__init__()
+
+ def create_piped_process(self, command, new_process_group=True):
+ if new_process_group:
+ # We need this flag if we want os.kill() to work on the subprocess.
+ creation_flags = subprocess.CREATE_NEW_PROCESS_GROUP
+ else:
+ creation_flags = 0
+
+ return subprocess.Popen(
+ command,
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ universal_newlines=True, # Elicits automatic byte -> string decoding in Py3
+ creationflags=creation_flags)
+
+ def was_hard_terminate(self, returncode):
+ return returncode != 0
+
+
+class ProcessDriver(object):
+ """Drives a child process, notifies on important events, and can timeout.
+
+ Clients are expected to derive from this class and override the
+ on_process_started and on_process_exited methods if they want to
+ hook either of those.
+
+ This class supports timing out the child process in a platform-agnostic
+ way. The on_process_exited method is informed if the exit was natural
+ or if it was due to a timeout.
+ """
+ def __init__(self, soft_terminate_timeout=10.0):
+ super(ProcessDriver, self).__init__()
+ self.process_helper = ProcessHelper.process_helper()
+ self.pid = None
+ # Create the synchronization event for notifying when the
+ # inferior dotest process is complete.
+ self.done_event = threading.Event()
+ self.io_thread = None
+ self.process = None
+ # Number of seconds to wait for the soft terminate to
+ # wrap up, before moving to more drastic measures.
+ # Might want this longer if core dumps are generated and
+ # take a long time to write out.
+ self.soft_terminate_timeout = soft_terminate_timeout
+ # Number of seconds to wait for the hard terminate to
+ # wrap up, before giving up on the io thread. This should
+ # be fast.
+ self.hard_terminate_timeout = 5.0
+ self.returncode = None
+
+ # =============================================
+ # Methods for subclasses to override if desired.
+ # =============================================
+
+ def on_process_started(self):
+ pass
+
+ def on_process_exited(self, command, output, was_timeout, exit_status):
+ pass
+
+ def write(self, content):
+ # pylint: disable=no-self-use
+ # Intended - we want derived classes to be able to override
+ # this and use any self state they may contain.
+ sys.stdout.write(content)
+
+ # ==============================================================
+ # Operations used to drive processes. Clients will want to call
+ # one of these.
+ # ==============================================================
+
+ def run_command(self, command):
+ # Start up the child process and the thread that does the
+ # communication pump.
+ self._start_process_and_io_thread(command)
+
+ # Wait indefinitely for the child process to finish
+ # communicating. This indicates it has closed stdout/stderr
+ # pipes and is done.
+ self.io_thread.join()
+ self.returncode = self.process.wait()
+ if self.returncode is None:
+ raise Exception(
+ "no exit status available for pid {} after the "
+ " inferior dotest.py should have completed".format(
+ self.process.pid))
+
+ # Notify of non-timeout exit.
+ self.on_process_exited(
+ command,
+ self.io_thread.output,
+ False,
+ self.returncode)
+
+ def run_command_with_timeout(self, command, timeout, want_core):
+ # Figure out how many seconds our timeout description is requesting.
+ timeout_seconds = timeout_to_seconds(timeout)
+
+ # Start up the child process and the thread that does the
+ # communication pump.
+ self._start_process_and_io_thread(command)
+
+ self._wait_with_timeout(timeout_seconds, command, want_core)
+
+ # ================
+ # Internal details.
+ # ================
+
+ def _start_process_and_io_thread(self, command):
+ # Create the process.
+ self.process = self.process_helper.create_piped_process(command)
+ self.pid = self.process.pid
+ self.on_process_started()
+
+ # Ensure the event is cleared that is used for signaling
+ # from the communication() thread when communication is
+ # complete (i.e. the inferior process has finished).
+ self.done_event.clear()
+
+ self.io_thread = CommunicatorThread(
+ self.process, self.done_event, self.write)
+ self.io_thread.start()
+
+ def _attempt_soft_kill(self, want_core):
+ # The inferior dotest timed out. Attempt to clean it
+ # with a non-drastic method (so it can clean up properly
+ # and/or generate a core dump). Often the OS can't guarantee
+ # that the process will really terminate after this.
+ self.process_helper.soft_terminate(
+ self.process,
+ want_core=want_core,
+ log_file=self)
+
+ # Now wait up to a certain timeout period for the io thread
+ # to say that the communication ended. If that wraps up
+ # within our soft terminate timeout, we're all done here.
+ self.io_thread.join(self.soft_terminate_timeout)
+ if not self.io_thread.is_alive():
+ # stdout/stderr were closed on the child process side. We
+ # should be able to wait and reap the child process here.
+ self.returncode = self.process.wait()
+ # We terminated, and the done_trying result is n/a
+ terminated = True
+ done_trying = None
+ else:
+ self.write("soft kill attempt of process {} timed out "
+ "after {} seconds\n".format(
+ self.process.pid, self.soft_terminate_timeout))
+ terminated = False
+ done_trying = False
+ return terminated, done_trying
+
+ def _attempt_hard_kill(self):
+ # Instruct the process to terminate and really force it to
+ # happen. Don't give the process a chance to ignore.
+ self.process_helper.hard_terminate(
+ self.process,
+ log_file=self)
+
+ # Reap the child process. This should not hang as the
+ # hard_kill() mechanism is supposed to really kill it.
+ # Improvement option:
+ # If this does ever hang, convert to a self.process.poll()
+ # loop checking on self.process.returncode until it is not
+ # None or the timeout occurs.
+ self.returncode = self.process.wait()
+
+ # Wait a few moments for the io thread to finish...
+ self.io_thread.join(self.hard_terminate_timeout)
+ if self.io_thread.is_alive():
+ # ... but this is not critical if it doesn't end for some
+ # reason.
+ self.write(
+ "hard kill of process {} timed out after {} seconds waiting "
+ "for the io thread (ignoring)\n".format(
+ self.process.pid, self.hard_terminate_timeout))
+
+ # Set if it terminated. (Set up for optional improvement above).
+ terminated = self.returncode is not None
+ # Nothing else to try.
+ done_trying = True
+
+ return terminated, done_trying
+
+ def _attempt_termination(self, attempt_count, want_core):
+ if self.process_helper.supports_soft_terminate():
+ # When soft termination is supported, we first try to stop
+ # the process with a soft terminate. Failing that, we try
+ # the hard terminate option.
+ if attempt_count == 1:
+ return self._attempt_soft_kill(want_core)
+ elif attempt_count == 2:
+ return self._attempt_hard_kill()
+ else:
+ # We don't have anything else to try.
+ terminated = self.returncode is not None
+ done_trying = True
+ return terminated, done_trying
+ else:
+ # We only try the hard terminate option when there
+ # is no soft terminate available.
+ if attempt_count == 1:
+ return self._attempt_hard_kill()
+ else:
+ # We don't have anything else to try.
+ terminated = self.returncode is not None
+ done_trying = True
+ return terminated, done_trying
+
+ def _wait_with_timeout(self, timeout_seconds, command, want_core):
+ # Allow up to timeout seconds for the io thread to wrap up.
+ # If that completes, the child process should be done.
+ completed_normally = self.done_event.wait(timeout_seconds)
+ if completed_normally:
+ # Reap the child process here.
+ self.returncode = self.process.wait()
+ else:
+ # Prepare to stop the process
+ process_terminated = completed_normally
+ terminate_attempt_count = 0
+
+ # Try as many attempts as we support for trying to shut down
+ # the child process if it's not already shut down.
+ while not process_terminated:
+ terminate_attempt_count += 1
+ # Attempt to terminate.
+ process_terminated, done_trying = self._attempt_termination(
+ terminate_attempt_count, want_core)
+ # Check if there's nothing more to try.
+ if done_trying:
+ # Break out of our termination attempt loop.
+ break
+
+ # At this point, we're calling it good. The process
+ # finished gracefully, was shut down after one or more
+ # attempts, or we failed but gave it our best effort.
+ self.on_process_exited(
+ command,
+ self.io_thread.output,
+ not completed_normally,
+ self.returncode)
+
+
+def patched_init(self, *args, **kwargs):
+ self.original_init(*args, **kwargs)
+ # Initialize our condition variable that protects wait()/poll().
+ self.wait_condition = threading.Condition()
+
+
+def patched_wait(self, *args, **kwargs):
+ self.wait_condition.acquire()
+ try:
+ result = self.original_wait(*args, **kwargs)
+ # The process finished. Signal the condition.
+ self.wait_condition.notify_all()
+ return result
+ finally:
+ self.wait_condition.release()
+
+
+def patched_poll(self, *args, **kwargs):
+ self.wait_condition.acquire()
+ try:
+ result = self.original_poll(*args, **kwargs)
+ if self.returncode is not None:
+ # We did complete, and we have the return value.
+ # Signal the event to indicate we're done.
+ self.wait_condition.notify_all()
+ return result
+ finally:
+ self.wait_condition.release()
+
+
+def patch_up_subprocess_popen():
+ subprocess.Popen.original_init = subprocess.Popen.__init__
+ subprocess.Popen.__init__ = patched_init
+
+ subprocess.Popen.original_wait = subprocess.Popen.wait
+ subprocess.Popen.wait = patched_wait
+
+ subprocess.Popen.original_poll = subprocess.Popen.poll
+ subprocess.Popen.poll = patched_poll
+
+# Replace key subprocess.Popen() threading-unprotected methods with
+# threading-protected versions.
+patch_up_subprocess_popen()
diff --git a/packages/Python/lldbsuite/test/test_runner/test/inferior.py b/packages/Python/lldbsuite/test/test_runner/test/inferior.py
new file mode 100755
index 000000000000..4207bac300fd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/test_runner/test/inferior.py
@@ -0,0 +1,146 @@
+#!/usr/bin/env python
+"""Inferior program used by process control tests."""
+
+from __future__ import print_function
+
+import argparse
+import datetime
+import signal
+import subprocess
+import sys
+import time
+
+
+def parse_args(command_line):
+ """Parses the command line arguments given to it.
+
+ @param command_line a list of command line arguments to be parsed.
+
+ @return the argparse options dictionary.
+ """
+ parser = argparse.ArgumentParser()
+ parser.add_argument(
+ "--ignore-signal",
+ "-i",
+ dest="ignore_signals",
+ metavar="SIGNUM",
+ action="append",
+ type=int,
+ default=[],
+ help="ignore the given signal number (if possible)")
+ parser.add_argument(
+ "--launch-child-share-handles",
+ action="store_true",
+ help=("launch a child inferior.py that shares stdout/stderr/stdio and "
+ "never returns"))
+ parser.add_argument(
+ "--never-return",
+ action="store_true",
+ help="run in an infinite loop, never return")
+ parser.add_argument(
+ "--return-code",
+ "-r",
+ type=int,
+ default=0,
+ help="specify the return code for the inferior upon exit")
+ parser.add_argument(
+ "--sleep",
+ "-s",
+ metavar="SECONDS",
+ dest="sleep_seconds",
+ type=float,
+ help="sleep for SECONDS seconds before returning")
+ parser.add_argument(
+ "--verbose", "-v", action="store_true",
+ help="log verbose operation details to stdout")
+ return parser.parse_args(command_line)
+
+
+def handle_ignore_signals(options, signals):
+ """Ignores any signals provided to it.
+
+ @param options the command line options parsed by the program.
+ General used to check flags for things like verbosity.
+
+ @param signals the list of signals to ignore. Can be None or zero-length.
+ Entries should be type int.
+ """
+ if signals is None:
+ return
+
+ for signum in signals:
+ if options.verbose:
+ print("disabling signum {}".format(signum))
+ signal.signal(signum, signal.SIG_IGN)
+
+
+def handle_sleep(options, sleep_seconds):
+ """Sleeps the number of seconds specified, restarting as needed.
+
+ @param options the command line options parsed by the program.
+ General used to check flags for things like verbosity.
+
+ @param sleep_seconds the number of seconds to sleep. If None
+ or <= 0, no sleeping will occur.
+ """
+ if sleep_seconds is None:
+ return
+
+ if sleep_seconds <= 0:
+ return
+
+ end_time = datetime.datetime.now() + datetime.timedelta(0, sleep_seconds)
+ if options.verbose:
+ print("sleep end time: {}".format(end_time))
+
+ # Do sleep in a loop: signals can interrupt.
+ while datetime.datetime.now() < end_time:
+ # We'll wrap this in a try/catch so we don't encounter
+ # a race if a signal (ignored) knocks us out of this
+ # loop and causes us to return.
+ try:
+ sleep_interval = end_time - datetime.datetime.now()
+ sleep_seconds = sleep_interval.total_seconds()
+ if sleep_seconds > 0:
+ time.sleep(sleep_seconds)
+ except: # pylint: disable=bare-except
+ pass
+
+
+def handle_launch_children(options):
+ if options.launch_child_share_handles:
+ # Launch the child, share our file handles.
+ # We won't bother reaping it since it will likely outlive us.
+ subprocess.Popen([sys.executable, __file__, "--never-return"])
+
+
+def handle_never_return(options):
+ if not options.never_return:
+ return
+
+ # Loop forever.
+ while True:
+ try:
+ time.sleep(10)
+ except: # pylint: disable=bare-except
+ # Ignore
+ pass
+
+
+def main(command_line):
+ """Drives the main operation of the inferior test program.
+
+ @param command_line the command line options to process.
+
+ @return the exit value (program return code) for the process.
+ """
+ options = parse_args(command_line)
+ handle_ignore_signals(options, options.ignore_signals)
+ handle_launch_children(options)
+ handle_sleep(options, options.sleep_seconds)
+ handle_never_return(options)
+
+ return options.return_code
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/packages/Python/lldbsuite/test/test_runner/test/process_control_tests.py b/packages/Python/lldbsuite/test/test_runner/test/process_control_tests.py
new file mode 100755
index 000000000000..354506d65812
--- /dev/null
+++ b/packages/Python/lldbsuite/test/test_runner/test/process_control_tests.py
@@ -0,0 +1,235 @@
+#!/usr/bin/env python
+"""
+The LLVM Compiler Infrastructure
+
+This file is distributed under the University of Illinois Open Source
+License. See LICENSE.TXT for details.
+
+Provides classes used by the test results reporting infrastructure
+within the LLDB test suite.
+
+
+Tests the process_control module.
+"""
+
+# System imports.
+import os
+import platform
+import unittest
+import sys
+import threading
+
+# Add lib dir to pythonpath
+sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib'))
+
+# Our imports.
+import process_control
+
+
+class TestInferiorDriver(process_control.ProcessDriver):
+ def __init__(self, soft_terminate_timeout=None):
+ super(TestInferiorDriver, self).__init__(
+ soft_terminate_timeout=soft_terminate_timeout)
+ self.started_event = threading.Event()
+ self.started_event.clear()
+
+ self.completed_event = threading.Event()
+ self.completed_event.clear()
+
+ self.was_timeout = False
+ self.returncode = None
+ self.output = None
+
+ def write(self, content):
+ # We'll swallow this to keep tests non-noisy.
+ # Uncomment the following line if you want to see it.
+ # sys.stdout.write(content)
+ pass
+
+ def on_process_started(self):
+ self.started_event.set()
+
+ def on_process_exited(self, command, output, was_timeout, exit_status):
+ self.returncode = exit_status
+ self.was_timeout = was_timeout
+ self.output = output
+ self.returncode = exit_status
+ self.completed_event.set()
+
+
+class ProcessControlTests(unittest.TestCase):
+ @classmethod
+ def _suppress_soft_terminate(cls, command):
+ # Do the right thing for your platform here.
+ # Right now only POSIX-y systems are reporting
+ # soft terminate support, so this is set up for
+ # those.
+ helper = process_control.ProcessHelper.process_helper()
+ signals = helper.soft_terminate_signals()
+ if signals is not None:
+ for signum in helper.soft_terminate_signals():
+ command.extend(["--ignore-signal", str(signum)])
+
+ @classmethod
+ def inferior_command(
+ cls,
+ ignore_soft_terminate=False,
+ options=None):
+
+ # Base command.
+ command = ([sys.executable, "inferior.py"])
+
+ if ignore_soft_terminate:
+ cls._suppress_soft_terminate(command)
+
+ # Handle options as string or list.
+ if isinstance(options, str):
+ command.extend(options.split())
+ elif isinstance(options, list):
+ command.extend(options)
+
+ # Return full command.
+ return command
+
+
+class ProcessControlNoTimeoutTests(ProcessControlTests):
+ """Tests the process_control module."""
+ def test_run_completes(self):
+ """Test that running completes and gets expected stdout/stderr."""
+ driver = TestInferiorDriver()
+ driver.run_command(self.inferior_command())
+ self.assertTrue(
+ driver.completed_event.wait(5), "process failed to complete")
+ self.assertEqual(driver.returncode, 0, "return code does not match")
+
+ def test_run_completes_with_code(self):
+ """Test that running completes and gets expected stdout/stderr."""
+ driver = TestInferiorDriver()
+ driver.run_command(self.inferior_command(options="-r10"))
+ self.assertTrue(
+ driver.completed_event.wait(5), "process failed to complete")
+ self.assertEqual(driver.returncode, 10, "return code does not match")
+
+
+class ProcessControlTimeoutTests(ProcessControlTests):
+ def test_run_completes(self):
+ """Test that running completes and gets expected return code."""
+ driver = TestInferiorDriver()
+ timeout_seconds = 5
+ driver.run_command_with_timeout(
+ self.inferior_command(),
+ "{}s".format(timeout_seconds),
+ False)
+ self.assertTrue(
+ driver.completed_event.wait(2*timeout_seconds),
+ "process failed to complete")
+ self.assertEqual(driver.returncode, 0)
+
+ def _soft_terminate_works(self, with_core):
+ # Skip this test if the platform doesn't support soft ti
+ helper = process_control.ProcessHelper.process_helper()
+ if not helper.supports_soft_terminate():
+ self.skipTest("soft terminate not supported by platform")
+
+ driver = TestInferiorDriver()
+ timeout_seconds = 5
+
+ driver.run_command_with_timeout(
+ # Sleep twice as long as the timeout interval. This
+ # should force a timeout.
+ self.inferior_command(
+ options="--sleep {}".format(timeout_seconds*2)),
+ "{}s".format(timeout_seconds),
+ with_core)
+
+ # We should complete, albeit with a timeout.
+ self.assertTrue(
+ driver.completed_event.wait(2*timeout_seconds),
+ "process failed to complete")
+
+ # Ensure we received a timeout.
+ self.assertTrue(driver.was_timeout, "expected to end with a timeout")
+
+ self.assertTrue(
+ helper.was_soft_terminate(driver.returncode, with_core),
+ ("timeout didn't return expected returncode "
+ "for soft terminate with core: {}").format(driver.returncode))
+
+ def test_soft_terminate_works_core(self):
+ """Driver uses soft terminate (with core request) when process times out.
+ """
+ self._soft_terminate_works(True)
+
+ def test_soft_terminate_works_no_core(self):
+ """Driver uses soft terminate (no core request) when process times out.
+ """
+ self._soft_terminate_works(False)
+
+ def test_hard_terminate_works(self):
+ """Driver falls back to hard terminate when soft terminate is ignored.
+ """
+
+ driver = TestInferiorDriver(soft_terminate_timeout=2.0)
+ timeout_seconds = 1
+
+ driver.run_command_with_timeout(
+ # Sleep much longer than the timeout interval,forcing a
+ # timeout. Do whatever is needed to have the inferior
+ # ignore soft terminate calls.
+ self.inferior_command(
+ ignore_soft_terminate=True,
+ options="--never-return"),
+ "{}s".format(timeout_seconds),
+ True)
+
+ # We should complete, albeit with a timeout.
+ self.assertTrue(
+ driver.completed_event.wait(60),
+ "process failed to complete")
+
+ # Ensure we received a timeout.
+ self.assertTrue(driver.was_timeout, "expected to end with a timeout")
+
+ helper = process_control.ProcessHelper.process_helper()
+ self.assertTrue(
+ helper.was_hard_terminate(driver.returncode),
+ ("timeout didn't return expected returncode "
+ "for hard teriminate: {} ({})").format(
+ driver.returncode,
+ driver.output))
+
+ def test_inferior_exits_with_live_child_shared_handles(self):
+ """inferior exit detected when inferior children are live with shared
+ stdout/stderr handles.
+ """
+ # Requires review D13362 or equivalent to be implemented.
+ self.skipTest("http://reviews.llvm.org/D13362")
+
+ driver = TestInferiorDriver()
+
+ # Create the inferior (I1), and instruct it to create a child (C1)
+ # that shares the stdout/stderr handles with the inferior.
+ # C1 will then loop forever.
+ driver.run_command_with_timeout(
+ self.inferior_command(
+ options="--launch-child-share-handles --return-code 3"),
+ "5s",
+ False)
+
+ # We should complete without a timetout. I1 should end
+ # immediately after launching C1.
+ self.assertTrue(
+ driver.completed_event.wait(5),
+ "process failed to complete")
+
+ # Ensure we didn't receive a timeout.
+ self.assertFalse(
+ driver.was_timeout, "inferior should have completed normally")
+
+ self.assertEqual(
+ driver.returncode, 3,
+ "expected inferior process to end with expected returncode")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/Makefile b/packages/Python/lldbsuite/test/tools/lldb-mi/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiExit.py b/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiExit.py
new file mode 100644
index 000000000000..86a0a65b05a7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiExit.py
@@ -0,0 +1,84 @@
+"""
+Test that the lldb-mi driver exits properly.
+"""
+
+from __future__ import print_function
+
+
+
+import lldbmi_testcase
+from lldbsuite.test.lldbtest import *
+
+class MiExitTestCase(lldbmi_testcase.MiTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_gdb_exit(self):
+ """Test that '-gdb-exit' terminates local debug session and exits."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test -gdb-exit: try to exit and check that program is finished
+ self.runCmd("-gdb-exit")
+ self.expect("\^exit")
+ import pexpect
+ self.expect(pexpect.EOF)
+
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_quit(self):
+ """Test that 'quit' exits immediately."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test quit: try to exit and check that program is finished
+ self.runCmd("quit")
+ import pexpect
+ self.expect(pexpect.EOF)
+
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_q(self):
+ """Test that 'q' exits immediately."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test q: try to exit and check that program is finished
+ self.runCmd("q")
+ import pexpect
+ self.expect(pexpect.EOF)
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiFile.py b/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiFile.py
new file mode 100644
index 000000000000..8b4eac156362
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiFile.py
@@ -0,0 +1,77 @@
+"""
+Test lldb-mi -file-xxx commands.
+"""
+
+from __future__ import print_function
+
+
+
+import lldbmi_testcase
+from lldbsuite.test.lldbtest import *
+
+class MiFileTestCase(lldbmi_testcase.MiTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_file_exec_and_symbols_file(self):
+ """Test that 'lldb-mi --interpreter' works for -file-exec-and-symbols exe."""
+
+ self.spawnLldbMi(args = None)
+
+ # Test that -file-exec-and-symbols works for filename
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"exited-normally\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_file_exec_and_symbols_absolute_path(self):
+ """Test that 'lldb-mi --interpreter' works for -file-exec-and-symbols fullpath/exe."""
+
+ self.spawnLldbMi(args = None)
+
+ # Test that -file-exec-and-symbols works for absolute path
+ import os
+ path = os.path.join(os.getcwd(), self.myexe)
+ self.runCmd("-file-exec-and-symbols \"%s\"" % path)
+ self.expect("\^done")
+
+ # Run
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"exited-normally\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_file_exec_and_symbols_relative_path(self):
+ """Test that 'lldb-mi --interpreter' works for -file-exec-and-symbols relpath/exe."""
+
+ self.spawnLldbMi(args = None)
+
+ # Test that -file-exec-and-symbols works for relative path
+ path = "./%s" % self.myexe
+ self.runCmd("-file-exec-and-symbols %s" % path)
+ self.expect("\^done")
+
+ # Run
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"exited-normally\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_file_exec_and_symbols_unknown_path(self):
+ """Test that 'lldb-mi --interpreter' works for -file-exec-and-symbols badpath/exe."""
+
+ self.spawnLldbMi(args = None)
+
+ # Test that -file-exec-and-symbols fails on unknown path
+ path = "unknown_dir/%s" % self.myexe
+ self.runCmd("-file-exec-and-symbols %s" % path)
+ self.expect("\^error")
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiGdbSetShow.py b/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiGdbSetShow.py
new file mode 100644
index 000000000000..ab3eb1fb37de
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiGdbSetShow.py
@@ -0,0 +1,190 @@
+"""
+Test lldb-mi -gdb-set and -gdb-show commands.
+"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import lldbmi_testcase
+from lldbsuite.test.lldbtest import *
+
+class MiGdbSetShowTestCase(lldbmi_testcase.MiTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_gdb_set_target_async_default(self):
+ """Test that 'lldb-mi --interpreter' switches to async mode by default."""
+
+ self.spawnLldbMi(args = None)
+
+ # Switch to sync mode
+ self.runCmd("-gdb-set target-async off")
+ self.expect("\^done")
+ self.runCmd("-gdb-show target-async")
+ self.expect("\^done,value=\"off\"")
+
+ # Test that -gdb-set switches to async by default
+ self.runCmd("-gdb-set target-async")
+ self.expect("\^done")
+ self.runCmd("-gdb-show target-async")
+ self.expect("\^done,value=\"on\"")
+
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @expectedFlakeyLinux("llvm.org/pr26028") # Fails in ~1% of cases
+ def test_lldbmi_gdb_set_target_async_on(self):
+ """Test that 'lldb-mi --interpreter' can execute commands in async mode."""
+
+ self.spawnLldbMi(args = None)
+
+ # Switch to sync mode
+ self.runCmd("-gdb-set target-async off")
+ self.expect("\^done")
+ self.runCmd("-gdb-show target-async")
+ self.expect("\^done,value=\"off\"")
+
+ # Test that -gdb-set can switch to async mode
+ self.runCmd("-gdb-set target-async on")
+ self.expect("\^done")
+ self.runCmd("-gdb-show target-async")
+ self.expect("\^done,value=\"on\"")
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Test that program is executed in async mode
+ self.runCmd("-exec-run")
+ self.expect("\*running")
+ self.expect("@\"argc=1")
+
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @expectedFailureLinux # Failing in ~11/600 dosep runs (build 3120-3122)
+ def test_lldbmi_gdb_set_target_async_off(self):
+ """Test that 'lldb-mi --interpreter' can execute commands in sync mode."""
+
+ self.spawnLldbMi(args = None)
+
+ # Test that -gdb-set can switch to sync mode
+ self.runCmd("-gdb-set target-async off")
+ self.expect("\^done")
+ self.runCmd("-gdb-show target-async")
+ self.expect("\^done,value=\"off\"")
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Test that program is executed in async mode
+ self.runCmd("-exec-run")
+ unexpected = [ "\*running" ] # "\*running" is async notification
+ it = self.expect(unexpected + [ "@\"argc=1\\\\r\\\\n" ])
+ if it < len(unexpected):
+ self.fail("unexpected found: %s" % unexpected[it])
+
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_gdb_show_target_async(self):
+ """Test that 'lldb-mi --interpreter' in async mode by default."""
+
+ self.spawnLldbMi(args = None)
+
+ # Test that default target-async value is "on"
+ self.runCmd("-gdb-show target-async")
+ self.expect("\^done,value=\"on\"")
+
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_gdb_show_language(self):
+ """Test that 'lldb-mi --interpreter' can get current language."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that -gdb-show language gets current language
+ self.runCmd("-gdb-show language")
+ self.expect("\^done,value=\"c\+\+\"")
+
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ @unittest2.expectedFailure("-gdb-set ignores unknown properties")
+ def test_lldbmi_gdb_set_unknown(self):
+ """Test that 'lldb-mi --interpreter' fails when setting an unknown property."""
+
+ self.spawnLldbMi(args = None)
+
+ # Test that -gdb-set fails if property is unknown
+ self.runCmd("-gdb-set unknown some_value")
+ self.expect("\^error")
+
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ @unittest2.expectedFailure("-gdb-show ignores unknown properties")
+ def test_lldbmi_gdb_show_unknown(self):
+ """Test that 'lldb-mi --interpreter' fails when showing an unknown property."""
+
+ self.spawnLldbMi(args = None)
+
+ # Test that -gdb-show fails if property is unknown
+ self.runCmd("-gdb-show unknown")
+ self.expect("\^error")
+
+
+ @expectedFailureWindows("llvm.org/pr22274: need a pexpect replacement for windows")
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots
+ def test_lldbmi_gdb_set_ouptut_radix(self):
+ """Test that 'lldb-mi --interpreter' works for -gdb-set output-radix."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to BP_printf
+ line = line_number('main.cpp', '// BP_printf')
+ self.runCmd("-break-insert main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running");
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Setup variable
+ self.runCmd("-var-create var_a * a");
+ self.expect("\^done,name=\"var_a\",numchild=\"0\",value=\"10\",type=\"int\",thread-id=\"1\",has_more=\"0\"")
+
+ # Test default output
+ self.runCmd("-var-evaluate-expression var_a");
+ self.expect("\^done,value=\"10\"");
+
+ # Test hex output
+ self.runCmd("-gdb-set output-radix 16");
+ self.expect("\^done");
+ self.runCmd("-var-evaluate-expression var_a");
+ self.expect("\^done,value=\"0xa\"");
+
+ # Test octal output
+ self.runCmd("-gdb-set output-radix 8");
+ self.expect("\^done");
+ self.runCmd("-var-evaluate-expression var_a");
+ self.expect("\^done,value=\"012\"");
+
+ # Test decimal output
+ self.runCmd("-gdb-set output-radix 10");
+ self.expect("\^done");
+ self.runCmd("-var-evaluate-expression var_a");
+ self.expect("\^done,value=\"10\"");
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiLibraryLoaded.py b/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiLibraryLoaded.py
new file mode 100644
index 000000000000..4d9c935576df
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiLibraryLoaded.py
@@ -0,0 +1,33 @@
+"""
+Test lldb-mi =library-loaded notifications.
+"""
+
+from __future__ import print_function
+
+
+
+import lldbmi_testcase
+from lldbsuite.test.lldbtest import *
+
+class MiLibraryLoadedTestCase(lldbmi_testcase.MiTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_library_loaded(self):
+ """Test that 'lldb-mi --interpreter' shows the =library-loaded notifications."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Test =library-loaded
+ import os
+ path = os.path.join(os.getcwd(), self.myexe)
+ symbols_path = os.path.join(path + ".dSYM", "Contents", "Resources", "DWARF", self.myexe)
+ def add_slashes(x): return x.replace("\\", "\\\\").replace("\"", "\\\"").replace("\'", "\\\'").replace("\0", "\\\0")
+ self.expect([ "=library-loaded,id=\"%s\",target-name=\"%s\",host-name=\"%s\",symbols-loaded=\"1\",symbols-path=\"%s\",loaded_addr=\"-\",size=\"[0-9]+\"" % (add_slashes(path), add_slashes(path), add_slashes(path), add_slashes(symbols_path)),
+ "=library-loaded,id=\"%s\",target-name=\"%s\",host-name=\"%s\",symbols-loaded=\"0\",loaded_addr=\"-\",size=\"[0-9]+\"" % (add_slashes(path), add_slashes(path), add_slashes(path)) ])
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiPrompt.py b/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiPrompt.py
new file mode 100644
index 000000000000..d810267d9489
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/TestMiPrompt.py
@@ -0,0 +1,54 @@
+"""
+Test that the lldb-mi driver prints prompt properly.
+"""
+
+from __future__ import print_function
+
+
+
+import lldbmi_testcase
+from lldbsuite.test.lldbtest import *
+
+class MiPromptTestCase(lldbmi_testcase.MiTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_prompt(self):
+ """Test that 'lldb-mi --interpreter' echos '(gdb)' after commands and events."""
+
+ self.spawnLldbMi(args = None)
+
+ # Test that lldb-mi is ready after unknown command
+ self.runCmd("-unknown-command")
+ self.expect("\^error,msg=\"Driver\. Received command '-unknown-command'\. It was not handled\. Command 'unknown-command' not in Command Factory\"")
+ self.expect(self.child_prompt, exactly = True)
+
+ # Test that lldb-mi is ready after -file-exec-and-symbols
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+ self.expect(self.child_prompt, exactly = True)
+
+ # Test that lldb-mi is ready after -break-insert
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.expect(self.child_prompt, exactly = True)
+
+ # Test that lldb-mi is ready after -exec-run
+ self.runCmd("-exec-run")
+ self.expect("\*running")
+ self.expect(self.child_prompt, exactly = True)
+
+ # Test that lldb-mi is ready after BP hit
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+ self.expect(self.child_prompt, exactly = True)
+
+ # Test that lldb-mi is ready after -exec-continue
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect(self.child_prompt, exactly = True)
+
+ # Test that lldb-mi is ready after program exited
+ self.expect("\*stopped,reason=\"exited-normally\"")
+ self.expect(self.child_prompt, exactly = True)
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/breakpoint/Makefile b/packages/Python/lldbsuite/test/tools/lldb-mi/breakpoint/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/breakpoint/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/breakpoint/TestMiBreak.py b/packages/Python/lldbsuite/test/tools/lldb-mi/breakpoint/TestMiBreak.py
new file mode 100644
index 000000000000..020954ff9b41
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/breakpoint/TestMiBreak.py
@@ -0,0 +1,246 @@
+"""
+Test lldb-mi -break-xxx commands.
+"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import lldbmi_testcase
+from lldbsuite.test.lldbtest import *
+
+class MiBreakTestCase(lldbmi_testcase.MiTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_break_insert_function_pending(self):
+ """Test that 'lldb-mi --interpreter' works for pending function breakpoints."""
+
+ self.spawnLldbMi(args = None)
+
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ self.runCmd("-break-insert -f printf")
+ #FIXME function name is unknown on Darwin, fullname should be ??, line is -1
+ #self.expect("\^done,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"0xffffffffffffffff\",func=\"printf\",file=\"\?\?\",fullname=\"\?\?\",line=\"-1\",pending=\[\"printf\"\],times=\"0\",original-location=\"printf\"}")
+ self.expect("\^done,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"0xffffffffffffffff\",func=\"\?\?\",file=\"\?\?\",fullname=\"\?\?/\?\?\",line=\"0\",pending=\[\"printf\"\],times=\"0\",original-location=\"printf\"}")
+ #FIXME function name is unknown on Darwin, fullname should be ??, line -1
+ #self.expect("=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"0xffffffffffffffff\",func=\"printf\",file=\"\?\?\",fullname=\"\?\?\",line=\"-1\",pending=\[\"printf\"\],times=\"0\",original-location=\"printf\"}")
+ self.expect("=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"0xffffffffffffffff\",func=\"\?\?\",file=\"\?\?\",fullname=\"\?\?/\?\?\",line=\"0\",pending=\[\"printf\"\],times=\"0\",original-location=\"printf\"}")
+
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\".+?\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",pending=\[\"printf\"\],times=\"0\",original-location=\"printf\"}")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_break_insert_function(self):
+ """Test that 'lldb-mi --interpreter' works for function breakpoints."""
+
+ self.spawnLldbMi(args = None)
+
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",pending=\[\"main\"\],times=\"0\",original-location=\"main\"}")
+ self.expect("=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",pending=\[\"main\"\],times=\"0\",original-location=\"main\"}")
+
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\",pending=\[\"main\"\],times=\"0\",original-location=\"main\"}")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that -break-insert can set non-pending BP
+ self.runCmd("-break-insert printf")
+ #FIXME function name is unknown on Darwin
+ #self.expect("\^done,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"printf\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",times=\"0\",original-location=\"printf\"}")
+ self.expect("\^done,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\".+?\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",times=\"0\",original-location=\"printf\"}")
+ #FIXME function name is unknown on Darwin
+ #self.expect("=breakpoint-modified,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"printf\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",times=\"0\",original-location=\"printf\"}")
+ self.expect("=breakpoint-modified,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\".+?\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",times=\"0\",original-location=\"printf\"}")
+ # FIXME function name is unknown on Darwin
+ #self.expect("=breakpoint-modified,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"printf\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",times=\"0\",original-location=\"printf\"}")
+ self.expect("=breakpoint-modified,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\".+?\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\",times=\"0\",original-location=\"printf\"}")
+
+ # Test that -break-insert fails if non-pending BP can't be resolved
+ self.runCmd("-break-insert unknown_func")
+ self.expect("\^error,msg=\"Command 'break-insert'. Breakpoint location 'unknown_func' not found\"")
+
+ # Test that non-pending BP was set correctly
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\".*bkptno=\"2\"")
+
+ # Test that we can set a BP using the file:func syntax
+ self.runCmd("-break-insert main.cpp:main")
+ self.expect("\^done,bkpt={number=\"4\"")
+ self.runCmd("-break-insert main.cpp:ns::foo1")
+ self.expect("\^done,bkpt={number=\"5\"")
+ #FIXME: quotes on filenames aren't handled correctly in lldb-mi.
+ #self.runCmd("-break-insert \"main.cpp\":main")
+ #self.expect("\^done,bkpt={number=\"6\"")
+
+ # We should hit BP #5 on 'main.cpp:ns::foo1'
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\".*bkptno=\"5\"")
+
+ #FIXME: this test is disabled due to lldb bug llvm.org/pr24271.
+ # Test that we can set a BP using the global namespace token
+ #self.runCmd("-break-insert ::main")
+ #self.expect("\^done,bkpt={number=\"7\"")
+ #self.runCmd("-break-insert main.cpp:::main")
+ #self.expect("\^done,bkpt={number=\"8\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_break_insert_file_line_pending(self):
+ """Test that 'lldb-mi --interpreter' works for pending file:line breakpoints."""
+
+ self.spawnLldbMi(args = None)
+
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Find the line number to break inside main() and set
+ # pending BP
+ line = line_number('main.cpp', '// BP_return')
+ self.runCmd("-break-insert -f main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"%d\",pending=\[\"main.cpp:%d\"\],times=\"0\",original-location=\"main.cpp:%d\"}" % (line, line, line))
+ self.expect("=breakpoint-modified,bkpt={number=\"1\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"%d\",pending=\[\"main.cpp:%d\"\],times=\"0\",original-location=\"main.cpp:%d\"}" % (line, line, line))
+
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_break_insert_file_line(self):
+ """Test that 'lldb-mi --interpreter' works for file:line breakpoints."""
+
+ self.spawnLldbMi(args = None)
+
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that -break-insert can set non-pending BP
+ line = line_number('main.cpp', '// BP_return')
+ self.runCmd("-break-insert main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"%d\",times=\"0\",original-location=\"main.cpp:%d\"}" % (line, line))
+ self.expect("=breakpoint-modified,bkpt={number=\"2\",type=\"breakpoint\",disp=\"keep\",enabled=\"y\",addr=\"(?!0xffffffffffffffff)0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"%d\",times=\"0\",original-location=\"main.cpp:%d\"}" % (line, line))
+
+ # Test that -break-insert fails if non-pending BP can't be resolved
+ self.runCmd("-break-insert unknown_file:1")
+ self.expect("\^error,msg=\"Command 'break-insert'. Breakpoint location 'unknown_file:1' not found\"")
+
+ # Test that non-pending BP was set correctly
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @unittest2.expectedFailure("-break-insert doesn't work for absolute path")
+ def test_lldbmi_break_insert_file_line_absolute_path(self):
+ """Test that 'lldb-mi --interpreter' works for file:line breakpoints."""
+
+ self.spawnLldbMi(args = None)
+
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ import os
+ path = os.path.join(os.getcwd(), "main.cpp")
+ line = line_number('main.cpp', '// BP_return')
+ self.runCmd("-break-insert %s:%d" % (path, line))
+ self.expect("\^done,bkpt={number=\"2\"")
+
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_break_insert_settings(self):
+ """Test that 'lldb-mi --interpreter' can set breakpoints accoridng to global options."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Set target.move-to-nearest-code=off and try to set BP #1 that shouldn't be hit
+ self.runCmd("-interpreter-exec console \"settings set target.move-to-nearest-code off\"")
+ self.expect("\^done")
+ line = line_number('main.cpp', '// BP_before_main')
+ self.runCmd("-break-insert -f main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"1\"")
+
+ # Test that non-pending BP will not be set on non-existing line if target.move-to-nearest-code=off
+ # Note: this increases the BP number by 1 even though BP #2 is invalid.
+ self.runCmd("-break-insert main.cpp:%d" % line)
+ self.expect("\^error,msg=\"Command 'break-insert'. Breakpoint location 'main.cpp:%d' not found\"" % line)
+
+ # Set target.move-to-nearest-code=on and target.skip-prologue=on and set BP #3
+ self.runCmd("-interpreter-exec console \"settings set target.move-to-nearest-code on\"")
+ self.runCmd("-interpreter-exec console \"settings set target.skip-prologue on\"")
+ self.expect("\^done")
+ self.runCmd("-break-insert main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"3\"")
+
+ # Set target.skip-prologue=off and set BP #4
+ self.runCmd("-interpreter-exec console \"settings set target.skip-prologue off\"")
+ self.expect("\^done")
+ self.runCmd("-break-insert main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"4\"")
+
+ # Test that BP #4 is located before BP #3
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\",disp=\"del\",bkptno=\"4\"")
+
+ # Test that BP #3 is hit
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\",disp=\"del\",bkptno=\"3\"")
+
+ # Test that the target.language=pascal setting works and that BP #5 is NOT set
+ self.runCmd("-interpreter-exec console \"settings set target.language c\"")
+ self.expect("\^done")
+ self.runCmd("-break-insert ns.foo1")
+ self.expect("\^error")
+
+ # Test that the target.language=c++ setting works and that BP #6 is hit
+ self.runCmd("-interpreter-exec console \"settings set target.language c++\"")
+ self.expect("\^done")
+ self.runCmd("-break-insert ns::foo1")
+ self.expect("\^done,bkpt={number=\"6\"")
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\",disp=\"del\",bkptno=\"6\"")
+
+ # Test that BP #1 and #2 weren't set by running to program exit
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"exited-normally\"")
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/breakpoint/main.cpp b/packages/Python/lldbsuite/test/tools/lldb-mi/breakpoint/main.cpp
new file mode 100644
index 000000000000..9416a0d01c7d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/breakpoint/main.cpp
@@ -0,0 +1,27 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <cstdio>
+
+namespace ns
+{
+ int foo1(void) { printf("In foo1\n"); return 1; }
+ int foo2(void) { printf("In foo2\n"); return 2; }
+}
+
+// BP_before_main
+
+int x;
+int
+main(int argc, char const *argv[])
+{
+ printf("Print a formatted string so that GCC does not optimize this printf call: %s\n", argv[0]);
+ x = ns::foo1() + ns::foo2();
+ return 0; // BP_return
+}
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/control/Makefile b/packages/Python/lldbsuite/test/tools/lldb-mi/control/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/control/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/control/TestMiExec.py b/packages/Python/lldbsuite/test/tools/lldb-mi/control/TestMiExec.py
new file mode 100644
index 000000000000..742bbc8af6bd
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/control/TestMiExec.py
@@ -0,0 +1,457 @@
+"""
+Test lldb-mi -exec-xxx commands.
+"""
+
+from __future__ import print_function
+
+
+
+import lldbmi_testcase
+from lldbsuite.test.lldbtest import *
+
+class MiExecTestCase(lldbmi_testcase.MiTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @expectedFailureLinux # llvm.org/pr25000: lldb-mi does not receive broadcasted notification from Core/Process about process stopped
+ def test_lldbmi_exec_run(self):
+ """Test that 'lldb-mi --interpreter' can stop at entry."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Test that program is stopped at entry
+ self.runCmd("-exec-run --start")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"signal-received\",signal-name=\"SIGSTOP\",signal-meaning=\"Stop\",.*?thread-id=\"1\",stopped-threads=\"all\"")
+ # Test that lldb-mi is ready to execute next commands
+ self.expect(self.child_prompt, exactly = True)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_exec_abort(self):
+ """Test that 'lldb-mi --interpreter' works for -exec-abort."""
+
+ self.spawnLldbMi(args = None)
+
+ # Test that -exec-abort fails on invalid process
+ self.runCmd("-exec-abort")
+ self.expect("\^error,msg=\"Command 'exec-abort'\. Invalid process during debug session\"")
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Set arguments
+ self.runCmd("-exec-arguments arg1")
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that arguments were passed
+ self.runCmd("-data-evaluate-expression argc")
+ self.expect("\^done,value=\"2\"")
+
+ # Test that program may be aborted
+ self.runCmd("-exec-abort")
+ self.expect("\^done")
+ self.expect("\*stopped,reason=\"exited-normally\"")
+
+ # Test that program can be run again
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that arguments were passed again
+ self.runCmd("-data-evaluate-expression argc")
+ self.expect("\^done,value=\"2\"")
+
+ # Test that program may be aborted again
+ self.runCmd("-exec-abort")
+ self.expect("\^done")
+ self.expect("\*stopped,reason=\"exited-normally\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_exec_arguments_set(self):
+ """Test that 'lldb-mi --interpreter' can pass args using -exec-arguments."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Set arguments
+ self.runCmd("-exec-arguments --arg1 \"2nd arg\" third_arg fourth=\"4th arg\"")
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Check argc and argv to see if arg passed
+ self.runCmd("-data-evaluate-expression argc")
+ self.expect("\^done,value=\"5\"")
+ #self.runCmd("-data-evaluate-expression argv[1]")
+ #self.expect("\^done,value=\"--arg1\"")
+ self.runCmd("-interpreter-exec command \"print argv[1]\"")
+ self.expect("\"--arg1\"")
+ #self.runCmd("-data-evaluate-expression argv[2]")
+ #self.expect("\^done,value=\"2nd arg\"")
+ self.runCmd("-interpreter-exec command \"print argv[2]\"")
+ self.expect("\"2nd arg\"")
+ #self.runCmd("-data-evaluate-expression argv[3]")
+ #self.expect("\^done,value=\"third_arg\"")
+ self.runCmd("-interpreter-exec command \"print argv[3]\"")
+ self.expect("\"third_arg\"")
+ #self.runCmd("-data-evaluate-expression argv[4]")
+ #self.expect("\^done,value=\"fourth=\\\\\\\"4th arg\\\\\\\"\"")
+ self.runCmd("-interpreter-exec command \"print argv[4]\"")
+ self.expect("\"fourth=\\\\\\\"4th arg\\\\\\\"\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_exec_arguments_reset(self):
+ """Test that 'lldb-mi --interpreter' can reset previously set args using -exec-arguments."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Set arguments
+ self.runCmd("-exec-arguments arg1")
+ self.expect("\^done")
+ self.runCmd("-exec-arguments")
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Check argc to see if arg passed
+ self.runCmd("-data-evaluate-expression argc")
+ self.expect("\^done,value=\"1\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_exec_next(self):
+ """Test that 'lldb-mi --interpreter' works for stepping."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Warning: the following is sensitive to the lines in the source
+
+ # Test -exec-next
+ self.runCmd("-exec-next --thread 1 --frame 0")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"29\"")
+
+ # Test that --thread is optional
+ self.runCmd("-exec-next --frame 0")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"30\"")
+
+ # Test that --frame is optional
+ self.runCmd("-exec-next --thread 1")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"31\"")
+
+ # Test that both --thread and --frame are optional
+ self.runCmd("-exec-next")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"32\"")
+
+ # Test that an invalid --thread is handled
+ self.runCmd("-exec-next --thread 0")
+ self.expect("\^error,message=\"error: Thread index 0 is out of range")
+ self.runCmd("-exec-next --thread 10")
+ self.expect("\^error,message=\"error: Thread index 10 is out of range")
+
+ # Test that an invalid --frame is handled
+ # FIXME: no error is returned
+ self.runCmd("-exec-next --frame 10")
+ #self.expect("\^error: Frame index 10 is out of range")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @expectedFailurei386 #xfail to get buildbot green, failing config: i386 binary running on ubuntu 14.04 x86_64
+ def test_lldbmi_exec_next_instruction(self):
+ """Test that 'lldb-mi --interpreter' works for instruction stepping."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Warning: the following is sensitive to the lines in the
+ # source and optimizations
+
+ # Test -exec-next-instruction
+ self.runCmd("-exec-next-instruction --thread 1 --frame 0")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"28\"")
+
+ # Test that --thread is optional
+ self.runCmd("-exec-next-instruction --frame 0")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"28\"")
+
+ # Test that --frame is optional
+ self.runCmd("-exec-next-instruction --thread 1")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"29\"")
+
+ # Test that both --thread and --frame are optional
+ self.runCmd("-exec-next-instruction")
+ self.expect("\^running")
+ # Depending on compiler, it can stop at different line
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"(29|30)\"")
+
+ # Test that an invalid --thread is handled
+ self.runCmd("-exec-next-instruction --thread 0")
+ self.expect("\^error,message=\"error: Thread index 0 is out of range")
+ self.runCmd("-exec-next-instruction --thread 10")
+ self.expect("\^error,message=\"error: Thread index 10 is out of range")
+
+ # Test that an invalid --frame is handled
+ # FIXME: no error is returned
+ self.runCmd("-exec-next-instruction --frame 10")
+ #self.expect("\^error: Frame index 10 is out of range")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_exec_step(self):
+ """Test that 'lldb-mi --interpreter' works for stepping into."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Warning: the following is sensitive to the lines in the source
+
+ # Test that -exec-step steps into (or not) printf depending on debug info
+ # Note that message is different in Darwin and Linux:
+ # Darwin: "*stopped,reason=\"end-stepping-range\",frame={addr=\"0x[0-9a-f]+\",func=\"main\",args=[{name=\"argc\",value=\"1\"},{name=\"argv\",value="0x[0-9a-f]+\"}],file=\"main.cpp\",fullname=\".+main.cpp\",line=\"\d\"},thread-id=\"1\",stopped-threads=\"all\"
+ # Linux: "*stopped,reason=\"end-stepping-range\",frame={addr="0x[0-9a-f]+\",func=\"__printf\",args=[{name=\"format\",value=\"0x[0-9a-f]+\"}],file=\"printf.c\",fullname=\".+printf.c\",line="\d+"},thread-id=\"1\",stopped-threads=\"all\"
+ self.runCmd("-exec-step --thread 1 --frame 0")
+ self.expect("\^running")
+ it = self.expect([ "\*stopped,reason=\"end-stepping-range\".+?func=\"main\"",
+ "\*stopped,reason=\"end-stepping-range\".+?func=\"(?!main).+?\"" ])
+ # Exit from printf if needed
+ if it == 1:
+ self.runCmd("-exec-finish")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\"main\"")
+
+ # Test that -exec-step steps into g_MyFunction and back out
+ # (and that --thread is optional)
+ self.runCmd("-exec-step --frame 0")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\"g_MyFunction.*?\"")
+ # Use -exec-finish here to make sure that control reaches the caller.
+ # -exec-step can keep us in the g_MyFunction for gcc
+ self.runCmd("-exec-finish --frame 0")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"30\"")
+
+ # Test that -exec-step steps into s_MyFunction
+ # (and that --frame is optional)
+ self.runCmd("-exec-step --thread 1")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\".*?s_MyFunction.*?\"")
+
+ # Test that -exec-step steps into g_MyFunction from inside
+ # s_MyFunction (and that both --thread and --frame are optional)
+ self.runCmd("-exec-step")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\"g_MyFunction.*?\"")
+
+ # Test that an invalid --thread is handled
+ self.runCmd("-exec-step --thread 0")
+ self.expect("\^error,message=\"error: Thread index 0 is out of range")
+ self.runCmd("-exec-step --thread 10")
+ self.expect("\^error,message=\"error: Thread index 10 is out of range")
+
+ # Test that an invalid --frame is handled
+ # FIXME: no error is returned
+ self.runCmd("-exec-step --frame 10")
+ #self.expect("\^error: Frame index 10 is out of range")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_exec_step_instruction(self):
+ """Test that 'lldb-mi --interpreter' works for instruction stepping into."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Warning: the following is sensitive to the lines in the
+ # source and optimizations
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that -exec-next steps over printf
+ self.runCmd("-exec-next --thread 1 --frame 0")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\",line=\"29\"")
+
+ # Test that -exec-step-instruction steps over non branching
+ # instruction
+ self.runCmd("-exec-step-instruction --thread 1 --frame 0")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?main\.cpp\"")
+
+ # Test that -exec-step-instruction steps into g_MyFunction
+ # instruction (and that --thread is optional)
+ self.runCmd("-exec-step-instruction --frame 0")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\"g_MyFunction.*?\"")
+
+ # Test that -exec-step-instruction steps over non branching
+ # (and that --frame is optional)
+ self.runCmd("-exec-step-instruction --thread 1")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\"g_MyFunction.*?\"")
+
+ # Test that -exec-step-instruction steps into g_MyFunction
+ # (and that both --thread and --frame are optional)
+ self.runCmd("-exec-step-instruction")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\"g_MyFunction.*?\"")
+
+ # Test that an invalid --thread is handled
+ self.runCmd("-exec-step-instruction --thread 0")
+ self.expect("\^error,message=\"error: Thread index 0 is out of range")
+ self.runCmd("-exec-step-instruction --thread 10")
+ self.expect("\^error,message=\"error: Thread index 10 is out of range")
+
+ # Test that an invalid --frame is handled
+ # FIXME: no error is returned
+ self.runCmd("-exec-step-instruction --frame 10")
+ #self.expect("\^error: Frame index 10 is out of range")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_exec_finish(self):
+ """Test that 'lldb-mi --interpreter' works for -exec-finish."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Set BP at g_MyFunction and run to BP
+ self.runCmd("-break-insert -f g_MyFunction")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that -exec-finish returns from g_MyFunction
+ self.runCmd("-exec-finish --thread 1 --frame 0")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\"main\"")
+
+ # Run to BP inside s_MyFunction call
+ self.runCmd("-break-insert s_MyFunction")
+ self.expect("\^done,bkpt={number=\"2\"")
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that -exec-finish hits BP at g_MyFunction call inside
+ # s_MyFunction (and that --thread is optional)
+ self.runCmd("-exec-finish --frame 0")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that -exec-finish returns from g_MyFunction call inside
+ # s_MyFunction (and that --frame is optional)
+ self.runCmd("-exec-finish --thread 1")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\".*?s_MyFunction.*?\"")
+
+ # Test that -exec-finish returns from s_MyFunction
+ # (and that both --thread and --frame are optional)
+ self.runCmd("-exec-finish")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\"main\"")
+
+ # Test that an invalid --thread is handled
+ self.runCmd("-exec-finish --thread 0")
+ self.expect("\^error,message=\"error: Thread index 0 is out of range")
+ self.runCmd("-exec-finish --thread 10")
+ self.expect("\^error,message=\"error: Thread index 10 is out of range")
+
+ # Test that an invalid --frame is handled
+ # FIXME: no error is returned
+ #self.runCmd("-exec-finish --frame 10")
+ #self.expect("\^error: Frame index 10 is out of range")
+
+ # Set BP at printf and run to BP
+ self.runCmd("-break-insert -f printf")
+ self.expect("\^done,bkpt={number=\"3\"")
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ ## Test that -exec-finish returns from printf
+ self.runCmd("-exec-finish --thread 1 --frame 0")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\"main\"")
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/control/main.cpp b/packages/Python/lldbsuite/test/tools/lldb-mi/control/main.cpp
new file mode 100644
index 000000000000..ae0c3d9800a7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/control/main.cpp
@@ -0,0 +1,33 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <cstdio>
+
+void
+g_MyFunction(void)
+{
+ printf("g_MyFunction");
+}
+
+static void
+s_MyFunction(void)
+{
+ g_MyFunction();
+ printf("s_MyFunction");
+}
+
+int
+main(int argc, char const *argv[])
+{
+ printf("start");
+ g_MyFunction();
+ s_MyFunction();
+ printf("exit");
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/data/Makefile b/packages/Python/lldbsuite/test/tools/lldb-mi/data/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/data/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/data/TestMiData.py b/packages/Python/lldbsuite/test/tools/lldb-mi/data/TestMiData.py
new file mode 100644
index 000000000000..df9f54110f4b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/data/TestMiData.py
@@ -0,0 +1,337 @@
+"""
+Test lldb-mi -data-xxx commands.
+"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import lldbmi_testcase
+from lldbsuite.test.lldbtest import *
+
+class MiDataTestCase(lldbmi_testcase.MiTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_data_disassemble(self):
+ """Test that 'lldb-mi --interpreter' works for -data-disassemble."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Get an address for disassembling: use main
+ self.runCmd("-data-evaluate-expression main")
+ self.expect("\^done,value=\"0x[0-9a-f]+ \(a.out`main at main.cpp:[0-9]+\)\"")
+ addr = int(self.child.after.split("\"")[1].split(" ")[0], 16)
+
+ # Test -data-disassemble: try to disassemble some address
+ self.runCmd("-data-disassemble -s %#x -e %#x -- 0" % (addr, addr + 0x10))
+ self.expect("\^done,asm_insns=\[{address=\"0x0*%x\",func-name=\"main\",offset=\"0\",size=\"[1-9]+\",inst=\".+?\"}," % addr)
+
+ # Test -data-disassemble without "--"
+ self.runCmd("-data-disassemble -s %#x -e %#x 0" % (addr, addr + 0x10))
+ self.expect("\^done,asm_insns=\[{address=\"0x0*%x\",func-name=\"main\",offset=\"0\",size=\"[1-9]+\",inst=\".+?\"}," % addr)
+
+ # Run to hello_world
+ self.runCmd("-break-insert -f hello_world")
+ self.expect("\^done,bkpt={number=\"2\"")
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Get an address for disassembling: use hello_world
+ self.runCmd("-data-evaluate-expression hello_world")
+ self.expect("\^done,value=\"0x[0-9a-f]+ \(a.out`hello_world\(\) at main.cpp:[0-9]+\)\"")
+ addr = int(self.child.after.split("\"")[1].split(" ")[0], 16)
+
+ # Test -data-disassemble: try to disassemble some address
+ self.runCmd("-data-disassemble -s %#x -e %#x -- 0" % (addr, addr + 0x10))
+
+ # This matches a line similar to:
+ # Darwin: {address="0x0000000100000f18",func-name="hello_world()",offset="8",size="7",inst="leaq 0x65(%rip), %rdi; \"Hello, World!\\n\""},
+ # Linux: {address="0x0000000000400642",func-name="hello_world()",offset="18",size="5",inst="callq 0x4004d0; symbol stub for: printf"}
+ # To match the escaped characters in the ouptut, we must use four backslashes per matches backslash
+ # See https://docs.python.org/2/howto/regex.html#the-backslash-plague
+ self.expect([ "{address=\"0x[0-9a-f]+\",func-name=\"hello_world\(\)\",offset=\"[0-9]+\",size=\"[0-9]+\",inst=\".+?; \\\\\"Hello, World!\\\\\\\\n\\\\\"\"}",
+ "{address=\"0x[0-9a-f]+\",func-name=\"hello_world\(\)\",offset=\"[0-9]+\",size=\"[0-9]+\",inst=\".+?; symbol stub for: printf\"}" ])
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @unittest2.skip("-data-evaluate-expression doesn't work on globals") #FIXME: the global case worked before refactoring
+ def test_lldbmi_data_read_memory_bytes_global(self):
+ """Test that -data-read-memory-bytes can access global buffers."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Get address of char[] (global)
+ self.runCmd("-data-evaluate-expression &g_CharArray")
+ self.expect("\^done,value=\"0x[0-9a-f]+\"")
+ addr = int(self.child.after.split("\"")[1], 16)
+ size = 5
+
+ # Test that -data-read-memory-bytes works for char[] type (global)
+ self.runCmd("-data-read-memory-bytes %#x %d" % (addr, size))
+ self.expect("\^done,memory=\[{begin=\"0x0*%x\",offset=\"0x0+\",end=\"0x0*%x\",contents=\"1112131400\"}\]" % (addr, addr + size))
+
+ # Get address of static char[]
+ self.runCmd("-data-evaluate-expression &s_CharArray")
+ self.expect("\^done,value=\"0x[0-9a-f]+\"")
+ addr = int(self.child.after.split("\"")[1], 16)
+ size = 5
+
+ # Test that -data-read-memory-bytes works for static char[] type
+ self.runCmd("-data-read-memory-bytes %#x %d" % (addr, size))
+ self.expect("\^done,memory=\[{begin=\"0x0*%x\",offset=\"0x0+\",end=\"0x0*%x\",contents=\"1112131400\"}\]" % (addr, addr + size))
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_data_read_memory_bytes_local(self):
+ """Test that -data-read-memory-bytes can access local buffers."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd('-file-exec-and-symbols %s' % self.myexe)
+ self.expect(r'\^done')
+
+ # Run to BP_local_array_test_inner
+ line = line_number('main.cpp', '// BP_local_array_test_inner')
+ self.runCmd('-break-insert main.cpp:%d' % line)
+ self.expect(r'\^done,bkpt=\{number="1"')
+ self.runCmd('-exec-run')
+ self.expect(r'\^running')
+ self.expect(r'\*stopped,reason="breakpoint-hit"')
+
+ # Get address of local char[]
+ self.runCmd('-data-evaluate-expression "(void *)&array"')
+ self.expect(r'\^done,value="0x[0-9a-f]+"')
+ addr = int(self.child.after.split('"')[1], 16)
+ size = 4
+
+ # Test that an unquoted hex literal address works
+ self.runCmd('-data-read-memory-bytes %#x %d' % (addr, size))
+ self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % (addr, addr + size))
+
+ # Test that a double-quoted hex literal address works
+ self.runCmd('-data-read-memory-bytes "%#x" %d' % (addr, size))
+ self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % (addr, addr + size))
+
+ # Test that unquoted expressions work
+ self.runCmd('-data-read-memory-bytes &array %d' % size)
+ self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % (addr, addr + size))
+
+ # This doesn't work, and perhaps that makes sense, but it does work on GDB
+ self.runCmd('-data-read-memory-bytes array 4')
+ self.expect(r'\^error')
+ #self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % (addr, addr + size))
+
+ self.runCmd('-data-read-memory-bytes &array[2] 2')
+ self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="0304"\}\]' % (addr + 2, addr + size))
+
+ self.runCmd('-data-read-memory-bytes first_element_ptr %d' % size)
+ self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % (addr, addr + size))
+
+ # Test that double-quoted expressions work
+ self.runCmd('-data-read-memory-bytes "&array" %d' % size)
+ self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % (addr, addr + size))
+
+ self.runCmd('-data-read-memory-bytes "&array[0] + 1" 3')
+ self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="020304"\}\]' % (addr + 1, addr + size))
+
+ self.runCmd('-data-read-memory-bytes "first_element_ptr + 1" 3')
+ self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="020304"\}\]' % (addr + 1, addr + size))
+
+ # Test the -o (offset) option
+ self.runCmd('-data-read-memory-bytes -o 1 &array 3')
+ self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="020304"\}\]' % (addr + 1, addr + size))
+
+ # Test the --thread option
+ self.runCmd('-data-read-memory-bytes --thread 1 &array 4')
+ self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % (addr, addr + size))
+
+ # Test the --thread option with an invalid value
+ self.runCmd('-data-read-memory-bytes --thread 999 &array 4')
+ self.expect(r'\^error')
+
+ # Test the --frame option (current frame)
+ self.runCmd('-data-read-memory-bytes --frame 0 &array 4')
+ self.expect(r'\^done,memory=\[\{begin="0x0*%x",offset="0x0+",end="0x0*%x",contents="01020304"\}\]' % (addr, addr + size))
+
+ # Test the --frame option (outer frame)
+ self.runCmd('-data-read-memory-bytes --frame 1 &array 4')
+ self.expect(r'\^done,memory=\[\{begin="0x[0-9a-f]+",offset="0x0+",end="0x[0-9a-f]+",contents="05060708"\}\]')
+
+ # Test the --frame option with an invalid value
+ self.runCmd('-data-read-memory-bytes --frame 999 &array 4')
+ self.expect(r'\^error')
+
+ # Test all the options at once
+ self.runCmd('-data-read-memory-bytes --thread 1 --frame 1 -o 2 &array 2')
+ self.expect(r'\^done,memory=\[\{begin="0x[0-9a-f]+",offset="0x0+",end="0x[0-9a-f]+",contents="0708"\}\]')
+
+ # Test that an expression that references undeclared variables doesn't work
+ self.runCmd('-data-read-memory-bytes "&undeclared_array1 + undeclared_array2[1]" 2')
+ self.expect(r'\^error')
+
+ # Test that the address argument is required
+ self.runCmd('-data-read-memory-bytes')
+ self.expect(r'\^error')
+
+ # Test that the count argument is required
+ self.runCmd('-data-read-memory-bytes &array')
+ self.expect(r'\^error')
+
+ # Test that the address and count arguments are required when other options are present
+ self.runCmd('-data-read-memory-bytes --thread 1')
+ self.expect(r'\^error')
+
+ self.runCmd('-data-read-memory-bytes --thread 1 --frame 0')
+ self.expect(r'\^error')
+
+ # Test that the count argument is required when other options are present
+ self.runCmd('-data-read-memory-bytes --thread 1 &array')
+ self.expect(r'\^error')
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_data_list_register_names(self):
+ """Test that 'lldb-mi --interpreter' works for -data-list-register-names."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test -data-list-register-names: try to get all registers
+ self.runCmd("-data-list-register-names")
+ self.expect("\^done,register-names=\[\".+?\",")
+
+ # Test -data-list-register-names: try to get specified registers
+ self.runCmd("-data-list-register-names 0")
+ self.expect("\^done,register-names=\[\".+?\"\]")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_data_list_register_values(self):
+ """Test that 'lldb-mi --interpreter' works for -data-list-register-values."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test -data-list-register-values: try to get all registers
+ self.runCmd("-data-list-register-values x")
+ self.expect("\^done,register-values=\[{number=\"0\",value=\"0x[0-9a-f]+\"")
+
+ # Test -data-list-register-values: try to get specified registers
+ self.runCmd("-data-list-register-values x 0")
+ self.expect("\^done,register-values=\[{number=\"0\",value=\"0x[0-9a-f]+\"}\]")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_data_info_line(self):
+ """Test that 'lldb-mi --interpreter' works for -data-info-line."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Get the address of main and its line
+ self.runCmd("-data-evaluate-expression main")
+ self.expect("\^done,value=\"0x[0-9a-f]+ \(a.out`main at main.cpp:[0-9]+\)\"")
+ addr = int(self.child.after.split("\"")[1].split(" ")[0], 16)
+ line = line_number('main.cpp', '// FUNC_main')
+
+ # Test that -data-info-line works for address
+ self.runCmd("-data-info-line *%#x" % addr)
+ self.expect("\^done,start=\"0x0*%x\",end=\"0x[0-9a-f]+\",file=\".+?main.cpp\",line=\"%d\"" % (addr, line))
+
+ # Test that -data-info-line works for file:line
+ self.runCmd("-data-info-line main.cpp:%d" % line)
+ self.expect("\^done,start=\"0x0*%x\",end=\"0x[0-9a-f]+\",file=\".+?main.cpp\",line=\"%d\"" % (addr, line))
+
+ # Test that -data-info-line fails when invalid address is specified
+ self.runCmd("-data-info-line *0x0")
+ self.expect("\^error,msg=\"Command 'data-info-line'\. Error: The LineEntry is absent or has an unknown format\.\"")
+
+ # Test that -data-info-line fails when file is unknown
+ self.runCmd("-data-info-line unknown_file:1")
+ self.expect("\^error,msg=\"Command 'data-info-line'\. Error: The LineEntry is absent or has an unknown format\.\"")
+
+ # Test that -data-info-line fails when line has invalid format
+ self.runCmd("-data-info-line main.cpp:bad_line")
+ self.expect("\^error,msg=\"error: invalid line number string 'bad_line'")
+ self.runCmd("-data-info-line main.cpp:0")
+ self.expect("\^error,msg=\"error: zero is an invalid line number")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_data_evaluate_expression(self):
+ """Test that 'lldb-mi --interpreter' works for -data-evaluate-expression."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ line = line_number('main.cpp', '// BP_local_2d_array_test')
+ self.runCmd('-break-insert main.cpp:%d' % line)
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Check 2d array
+ self.runCmd("-data-evaluate-expression array2d")
+ self.expect("\^done,value=\"\{\[0\] = \{\[0\] = 1, \[1\] = 2, \[2\] = 3\}, \[1\] = \{\[0\] = 4, \[1\] = 5, \[2\] = 6\}\}\"")
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/data/main.cpp b/packages/Python/lldbsuite/test/tools/lldb-mi/data/main.cpp
new file mode 100644
index 000000000000..8030fe891de2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/data/main.cpp
@@ -0,0 +1,59 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+
+const char g_CharArray[] = "\x10\x11\x12\x13";
+static const char s_CharArray[] = "\x20\x21\x22\x23";
+
+void
+local_array_test_inner()
+{
+ char array[] = { 0x01, 0x02, 0x03, 0x04 };
+ char *first_element_ptr = &array[0];
+ // BP_local_array_test_inner
+ return;
+}
+
+void
+local_array_test()
+{
+ char array[] = { 0x05, 0x06, 0x07, 0x08 };
+ // BP_local_array_test
+ local_array_test_inner();
+ return;
+}
+
+void
+local_2d_array_test()
+{
+ int array2d[2][3];
+ array2d[0][0] = 1;
+ array2d[0][1] = 2;
+ array2d[0][2] = 3;
+ array2d[1][0] = 4;
+ array2d[1][1] = 5;
+ array2d[1][2] = 6;
+ return; // BP_local_2d_array_test
+}
+
+void
+hello_world()
+{
+ printf("Hello, World!\n"); // BP_hello_world
+}
+
+int
+main(int argc, char const *argv[])
+{ // FUNC_main
+ local_array_test();
+ hello_world();
+ local_2d_array_test();
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/Makefile b/packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/TestMiCliSupport.py b/packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/TestMiCliSupport.py
new file mode 100644
index 000000000000..562be912fbc1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/TestMiCliSupport.py
@@ -0,0 +1,206 @@
+"""
+Test lldb-mi can interpret CLI commands directly.
+"""
+
+from __future__ import print_function
+
+
+
+import lldbmi_testcase
+from lldbsuite.test.lldbtest import *
+
+class MiCliSupportTestCase(lldbmi_testcase.MiTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_target_create(self):
+ """Test that 'lldb-mi --interpreter' can create target by 'target create' command."""
+
+ self.spawnLldbMi(args = None)
+
+ # Test that "target create" loads executable
+ self.runCmd("target create \"%s\"" % self.myexe)
+ self.expect("\^done")
+
+ # Test that executable was loaded properly
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots
+ def test_lldbmi_breakpoint_set(self):
+ """Test that 'lldb-mi --interpreter' can set breakpoint by 'breakpoint set' command."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Test that "breakpoint set" sets a breakpoint
+ self.runCmd("breakpoint set --name main")
+ self.expect("\^done")
+ self.expect("=breakpoint-created,bkpt={number=\"1\"")
+
+ # Test that breakpoint was set properly
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("=breakpoint-modified,bkpt={number=\"1\"")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots
+ def test_lldbmi_settings_set_target_run_args_before(self):
+ """Test that 'lldb-mi --interpreter' can set target arguments by 'setting set target.run-args' command before than target was created."""
+
+ self.spawnLldbMi(args = None)
+
+ # Test that "settings set target.run-args" passes arguments to executable
+ #FIXME: --arg1 causes an error
+ self.runCmd("setting set target.run-args arg1 \"2nd arg\" third_arg fourth=\"4th arg\"")
+ self.expect("\^done")
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+
+ # Test that arguments were passed properly
+ self.expect("@\"argc=5\\\\r\\\\n\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots
+ def test_lldbmi_settings_set_target_run_args_after(self):
+ """Test that 'lldb-mi --interpreter' can set target arguments by 'setting set target.run-args' command after than target was created."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Test that "settings set target.run-args" passes arguments to executable
+ #FIXME: --arg1 causes an error
+ self.runCmd("setting set target.run-args arg1 \"2nd arg\" third_arg fourth=\"4th arg\"")
+ self.expect("\^done")
+
+ # Run
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+
+ # Test that arguments were passed properly
+ self.expect("@\"argc=5\\\\r\\\\n\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots
+ def test_lldbmi_process_launch(self):
+ """Test that 'lldb-mi --interpreter' can launch process by "process launch" command."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Set breakpoint
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+
+ # Test that "process launch" launches executable
+ self.runCmd("process launch")
+ self.expect("\^done")
+
+ # Test that breakpoint hit
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots
+ def test_lldbmi_thread_step_in(self):
+ """Test that 'lldb-mi --interpreter' can step in by "thread step-in" command."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that "thread step-in" steps into (or not) printf depending on debug info
+ # Note that message is different in Darwin and Linux:
+ # Darwin: "*stopped,reason=\"end-stepping-range\",frame={addr=\"0x[0-9a-f]+\",func=\"main\",args=[{name=\"argc\",value=\"1\"},{name=\"argv\",value="0x[0-9a-f]+\"}],file=\"main.cpp\",fullname=\".+main.cpp\",line=\"\d\"},thread-id=\"1\",stopped-threads=\"all\"
+ # Linux: "*stopped,reason=\"end-stepping-range\",frame={addr="0x[0-9a-f]+\",func=\"__printf\",args=[{name=\"format\",value=\"0x[0-9a-f]+\"}],file=\"printf.c\",fullname=\".+printf.c\",line="\d+"},thread-id=\"1\",stopped-threads=\"all\"
+ self.runCmd("thread step-in")
+ self.expect("\^done")
+ it = self.expect([ "@\"argc=1\\\\r\\\\n\"",
+ "\*stopped,reason=\"end-stepping-range\".+?func=\"(?!main).+?\"" ])
+ if it == 0:
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\"main\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots
+ def test_lldbmi_thread_step_over(self):
+ """Test that 'lldb-mi --interpreter' can step over by "thread step-over" command."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that "thread step-over" steps over
+ self.runCmd("thread step-over")
+ self.expect("\^done")
+ self.expect("@\"argc=1\\\\r\\\\n\"")
+ self.expect("\*stopped,reason=\"end-stepping-range\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots
+ def test_lldbmi_thread_continue(self):
+ """Test that 'lldb-mi --interpreter' can continue execution by "thread continue" command."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that "thread continue" continues execution
+ self.runCmd("thread continue")
+ self.expect("\^done")
+ self.expect("@\"argc=1\\\\r\\\\n")
+ self.expect("\*stopped,reason=\"exited-normally\"")
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/TestMiInterpreterExec.py b/packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/TestMiInterpreterExec.py
new file mode 100644
index 000000000000..93d9f25683b0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/TestMiInterpreterExec.py
@@ -0,0 +1,229 @@
+"""
+Test lldb-mi -interpreter-exec command.
+"""
+
+from __future__ import print_function
+
+
+
+import lldbmi_testcase
+from lldbsuite.test.lldbtest import *
+
+class MiInterpreterExecTestCase(lldbmi_testcase.MiTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_target_create(self):
+ """Test that 'lldb-mi --interpreter' can create target by 'target create' command."""
+
+ self.spawnLldbMi(args = None)
+
+ # Test that "target create" loads executable
+ self.runCmd("-interpreter-exec console \"target create \\\"%s\\\"\"" % self.myexe)
+ self.expect("\^done")
+
+ # Test that executable was loaded properly
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_breakpoint_set(self):
+ """Test that 'lldb-mi --interpreter' can set breakpoint by 'breakpoint set' command."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Test that "breakpoint set" sets a breakpoint
+ self.runCmd("-interpreter-exec console \"breakpoint set --name main\"")
+ self.expect("\^done")
+ self.expect("=breakpoint-created,bkpt={number=\"1\"")
+
+ # Test that breakpoint was set properly
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("=breakpoint-modified,bkpt={number=\"1\"")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @expectedFailureLinux # Failing in ~9/600 dosep runs (build 3120-3122)
+ def test_lldbmi_settings_set_target_run_args_before(self):
+ """Test that 'lldb-mi --interpreter' can set target arguments by 'setting set target.run-args' command before than target was created."""
+
+ self.spawnLldbMi(args = None)
+
+ # Test that "settings set target.run-args" passes arguments to executable
+ #FIXME: --arg1 causes an error
+ self.runCmd("-interpreter-exec console \"setting set target.run-args arg1 \\\"2nd arg\\\" third_arg fourth=\\\"4th arg\\\"\"")
+ self.expect("\^done")
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+
+ # Test that arguments were passed properly
+ self.expect("@\"argc=5\\\\r\\\\n\"")
+ self.expect("@\"argv.0.=.*lldb-mi")
+ self.expect("@\"argv.1.=arg1\\\\r\\\\n\"")
+ self.expect("@\"argv.2.=2nd arg\\\\r\\\\n\"")
+ self.expect("@\"argv.3.=third_arg\\\\r\\\\n\"")
+ self.expect("@\"argv.4.=fourth=4th arg\\\\r\\\\n\"")
+
+ # Test that program exited normally
+ self.expect("\*stopped,reason=\"exited-normally\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @expectedFailureLinux # Failing in ~9/600 dosep runs (build 3120-3122)
+ def test_lldbmi_settings_set_target_run_args_after(self):
+ """Test that 'lldb-mi --interpreter' can set target arguments by 'setting set target.run-args' command after than target was created."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Test that "settings set target.run-args" passes arguments to executable
+ #FIXME: --arg1 causes an error
+ self.runCmd("-interpreter-exec console \"setting set target.run-args arg1 \\\"2nd arg\\\" third_arg fourth=\\\"4th arg\\\"\"")
+ self.expect("\^done")
+
+ # Run to BP_printf
+ line = line_number('main.cpp', '// BP_printf')
+ self.runCmd("-break-insert main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running");
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Run to BP_return
+ line = line_number('main.cpp', '// BP_return')
+ self.runCmd("-break-insert main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"2\"")
+ self.runCmd("-exec-continue")
+ self.expect("\^running");
+
+ # Test that arguments were passed properly
+ self.expect("@\"argc=5\\\\r\\\\n\"")
+ self.expect("@\"argv.0.=.*lldb-mi")
+ self.expect("@\"argv.1.=arg1\\\\r\\\\n\"")
+ self.expect("@\"argv.2.=2nd arg\\\\r\\\\n\"")
+ self.expect("@\"argv.3.=third_arg\\\\r\\\\n\"")
+ self.expect("@\"argv.4.=fourth=4th arg\\\\r\\\\n\"")
+
+ # Hit BP_return
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_process_launch(self):
+ """Test that 'lldb-mi --interpreter' can launch process by "process launch" command."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Set breakpoint
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+
+ # Test that "process launch" launches executable
+ self.runCmd("-interpreter-exec console \"process launch\"")
+ self.expect("\^done")
+
+ # Test that breakpoint hit
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_thread_step_in(self):
+ """Test that 'lldb-mi --interpreter' can step in by "thread step-in" command."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that "thread step-in" steps into (or not) printf depending on debug info
+ # Note that message is different in Darwin and Linux:
+ # Darwin: "*stopped,reason=\"end-stepping-range\",frame={addr=\"0x[0-9a-f]+\",func=\"main\",args=[{name=\"argc\",value=\"1\"},{name=\"argv\",value="0x[0-9a-f]+\"}],file=\"main.cpp\",fullname=\".+main.cpp\",line=\"\d\"},thread-id=\"1\",stopped-threads=\"all\"
+ # Linux: "*stopped,reason=\"end-stepping-range\",frame={addr="0x[0-9a-f]+\",func=\"__printf\",args=[{name=\"format\",value=\"0x[0-9a-f]+\"}],file=\"printf.c\",fullname=\".+printf.c\",line="\d+"},thread-id=\"1\",stopped-threads=\"all\"
+ self.runCmd("-interpreter-exec console \"thread step-in\"")
+ self.expect("\^done")
+ it = self.expect([ "@\"argc=1\\\\r\\\\n\"",
+ "\*stopped,reason=\"end-stepping-range\".+?func=\"(?!main).+?\"" ])
+ if it == 0:
+ self.expect("\*stopped,reason=\"end-stepping-range\".+?func=\"main\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_thread_step_over(self):
+ """Test that 'lldb-mi --interpreter' can step over by "thread step-over" command."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that "thread step-over" steps over
+ self.runCmd("-interpreter-exec console \"thread step-over\"")
+ self.expect("\^done")
+ self.expect("@\"argc=1\\\\r\\\\n\"")
+ self.expect("\*stopped,reason=\"end-stepping-range\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @expectedFlakeyLinux("llvm.org/pr25470")
+ def test_lldbmi_thread_continue(self):
+ """Test that 'lldb-mi --interpreter' can continue execution by "thread continue" command."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that "thread continue" continues execution
+ self.runCmd("-interpreter-exec console \"thread continue\"")
+ self.expect("\^done")
+ self.expect("@\"argc=1\\\\r\\\\n")
+ self.expect("\*stopped,reason=\"exited-normally\"")
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/main.cpp b/packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/main.cpp
new file mode 100644
index 000000000000..0c042d466988
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/interpreter/main.cpp
@@ -0,0 +1,19 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <cstdio>
+
+int
+main(int argc, char const *argv[])
+{
+ printf("argc=%d\n", argc); // BP_printf
+ for (int i = 0; i < argc; ++i)
+ printf("argv[%d]=%s\n", i, argv[i]);
+ return 0; // BP_return
+}
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/lldbmi_testcase.py b/packages/Python/lldbsuite/test/tools/lldb-mi/lldbmi_testcase.py
new file mode 100644
index 000000000000..277ffe70c1ca
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/lldbmi_testcase.py
@@ -0,0 +1,54 @@
+"""
+Base class for lldb-mi test cases.
+"""
+
+from __future__ import print_function
+
+
+
+from lldbsuite.test.lldbtest import *
+
+class MiTestCaseBase(Base):
+
+ mydir = None
+ myexe = "a.out"
+ mylog = "child.log"
+
+ def getCategories(self):
+ return ['lldb-mi']
+
+ @classmethod
+ def classCleanup(cls):
+ TestBase.RemoveTempFile(cls.myexe)
+ TestBase.RemoveTempFile(cls.mylog)
+
+ def setUp(self):
+ Base.setUp(self)
+ self.buildDefault()
+ self.child_prompt = "(gdb)"
+
+ def tearDown(self):
+ if self.TraceOn():
+ print("\n\nContents of %s:" % self.mylog)
+ try:
+ print(open(self.mylog, "r").read())
+ except IOError:
+ pass
+ Base.tearDown(self)
+
+ def spawnLldbMi(self, args=None):
+ import pexpect
+ self.child = pexpect.spawn("%s --interpreter %s" % (
+ self.lldbMiExec, args if args else ""))
+ self.child.setecho(True)
+ self.child.logfile_read = open(self.mylog, "w")
+ # wait until lldb-mi has started up and is ready to go
+ self.expect(self.child_prompt, exactly = True)
+
+ def runCmd(self, cmd):
+ self.child.sendline(cmd)
+
+ def expect(self, pattern, exactly=False, *args, **kwargs):
+ if exactly:
+ return self.child.expect_exact(pattern, *args, **kwargs)
+ return self.child.expect(pattern, *args, **kwargs)
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/main.cpp b/packages/Python/lldbsuite/test/tools/lldb-mi/main.cpp
new file mode 100644
index 000000000000..6a2079f2ce74
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/main.cpp
@@ -0,0 +1,19 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <cstdio>
+
+int
+main(int argc, char const *argv[])
+{
+ int a = 10;
+
+ printf("argc=%d\n", argc); // BP_printf
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/signal/Makefile b/packages/Python/lldbsuite/test/tools/lldb-mi/signal/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/signal/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/signal/TestMiSignal.py b/packages/Python/lldbsuite/test/tools/lldb-mi/signal/TestMiSignal.py
new file mode 100644
index 000000000000..11e7b8a82f68
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/signal/TestMiSignal.py
@@ -0,0 +1,197 @@
+"""
+Test that the lldb-mi handles signals properly.
+"""
+
+from __future__ import print_function
+
+
+
+import lldbmi_testcase
+from lldbsuite.test.lldbtest import *
+
+class MiSignalTestCase(lldbmi_testcase.MiTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Fails on FreeBSD apparently due to thread race conditions
+ def test_lldbmi_stopped_when_interrupt(self):
+ """Test that 'lldb-mi --interpreter' interrupt and resume a looping app."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Set doloop=1 and run (to loop forever)
+ self.runCmd("-data-evaluate-expression \"do_loop=1\"")
+ self.expect("\^done,value=\"1\"")
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+
+ # Test that -exec-interrupt can interrupt an execution
+ self.runCmd("-exec-interrupt")
+ self.expect("\*stopped,reason=\"signal-received\",signal-name=\"SIGINT\",signal-meaning=\"Interrupt\",.+?thread-id=\"1\",stopped-threads=\"all\"")
+
+ # Continue (to loop forever)
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+
+ # Test that Ctrl+C can interrupt an execution
+ self.child.sendintr() #FIXME: here uses self.child directly
+ self.expect("\*stopped,reason=\"signal-received\",signal-name=\"SIGINT\",signal-meaning=\"Interrupt\",.*thread-id=\"1\",stopped-threads=\"all\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Fails on FreeBSD apparently due to thread race conditions
+ @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots
+ def test_lldbmi_stopped_when_stopatentry_local(self):
+ """Test that 'lldb-mi --interpreter' notifies after it was stopped on entry (local)."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run with stop-at-entry flag
+ self.runCmd("-interpreter-exec command \"process launch -s\"")
+ self.expect("\^done")
+
+ # Test that *stopped is printed
+ # Note that message is different in Darwin and Linux:
+ # Darwin: "*stopped,reason=\"signal-received\",signal-name=\"SIGSTOP\",signal-meaning=\"Stop\",frame={level=\"0\",addr=\"0x[0-9a-f]+\",func=\"_dyld_start\",file=\"??\",fullname=\"??\",line=\"-1\"},thread-id=\"1\",stopped-threads=\"all\"
+ # Linux: "*stopped,reason=\"end-stepping-range\",frame={addr=\"0x[0-9a-f]+\",func=\"??\",args=[],file=\"??\",fullname=\"??\",line=\"-1\"},thread-id=\"1\",stopped-threads=\"all\"
+ self.expect([ "\*stopped,reason=\"signal-received\",signal-name=\"SIGSTOP\",signal-meaning=\"Stop\",frame=\{level=\"0\",addr=\"0x[0-9a-f]+\",func=\"_dyld_start\",file=\"\?\?\",fullname=\"\?\?\",line=\"-1\"\},thread-id=\"1\",stopped-threads=\"all\"",
+ "\*stopped,reason=\"end-stepping-range\",frame={addr=\"0x[0-9a-f]+\",func=\"\?\?\",args=\[\],file=\"\?\?\",fullname=\"\?\?\",line=\"-1\"},thread-id=\"1\",stopped-threads=\"all\"" ])
+
+ # Run to main to make sure we have not exited the application
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipUnlessDarwin
+ def test_lldbmi_stopped_when_stopatentry_remote(self):
+ """Test that 'lldb-mi --interpreter' notifies after it was stopped on entry (remote)."""
+
+ # Prepare debugserver
+ import lldbgdbserverutils
+ debugserver_exe = lldbgdbserverutils.get_debugserver_exe()
+ if not debugserver_exe:
+ self.skipTest("debugserver exe not found")
+ hostname = "localhost"
+ import random
+ port = 12000 + random.randint(0,3999) # the same as GdbRemoteTestCaseBase.get_next_port
+ import pexpect
+ debugserver_child = pexpect.spawn("%s %s:%d" % (debugserver_exe, hostname, port))
+ self.addTearDownHook(lambda: debugserver_child.terminate(force = True))
+
+ self.spawnLldbMi(args = None)
+
+ # Connect to debugserver
+ self.runCmd("-interpreter-exec command \"platform select remote-macosx --sysroot /\"")
+ self.expect("\^done")
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+ self.runCmd("-interpreter-exec command \"process connect connect://%s:%d\"" % (hostname, port))
+ self.expect("\^done")
+
+ # Run with stop-at-entry flag
+ self.runCmd("-interpreter-exec command \"process launch -s\"")
+ self.expect("\^done")
+
+ # Test that *stopped is printed
+ self.expect("\*stopped,reason=\"signal-received\",signal-name=\"SIGSTOP\",signal-meaning=\"Stop\",.+?thread-id=\"1\",stopped-threads=\"all\"")
+
+ # Exit
+ self.runCmd("-gdb-exit")
+ self.expect("\^exit")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots
+ def test_lldbmi_stopped_when_segfault_local(self):
+ """Test that 'lldb-mi --interpreter' notifies after it was stopped when segfault occurred (local)."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Set do_segfault=1 and run (to cause a segfault error)
+ self.runCmd("-data-evaluate-expression \"do_segfault=1\"")
+ self.expect("\^done,value=\"1\"")
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+
+ # Test that *stopped is printed
+ # Note that message is different in Darwin and Linux:
+ # Darwin: "*stopped,reason=\"exception-received\",exception=\"EXC_BAD_ACCESS (code=1, address=0x0)\",thread-id=\"1\",stopped-threads=\"all\""
+ # Linux: "*stopped,reason=\"exception-received\",exception=\"invalid address (fault address: 0x0)\",thread-id=\"1\",stopped-threads=\"all\""
+ self.expect([ "\*stopped,reason=\"exception-received\",exception=\"EXC_BAD_ACCESS \(code=1, address=0x0\)\",thread-id=\"1\",stopped-threads=\"all\"",
+ "\*stopped,reason=\"exception-received\",exception=\"invalid address \(fault address: 0x0\)\",thread-id=\"1\",stopped-threads=\"all\"" ])
+
+ @skipUnlessDarwin
+ def test_lldbmi_stopped_when_segfault_remote(self):
+ """Test that 'lldb-mi --interpreter' notifies after it was stopped when segfault occurred (remote)."""
+
+ # Prepare debugserver
+ import lldbgdbserverutils
+ debugserver_exe = lldbgdbserverutils.get_debugserver_exe()
+ if not debugserver_exe:
+ self.skipTest("debugserver exe not found")
+ hostname = "localhost"
+ import random
+ port = 12000 + random.randint(0,3999) # the same as GdbRemoteTestCaseBase.get_next_port
+ import pexpect
+ debugserver_child = pexpect.spawn("%s %s:%d" % (debugserver_exe, hostname, port))
+ self.addTearDownHook(lambda: debugserver_child.terminate(force = True))
+
+ self.spawnLldbMi(args = None)
+
+ # Connect to debugserver
+ self.runCmd("-interpreter-exec command \"platform select remote-macosx --sysroot /\"")
+ self.expect("\^done")
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+ self.runCmd("-interpreter-exec command \"process connect connect://%s:%d\"" % (hostname, port))
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ #FIXME -exec-run doesn't work
+ self.runCmd("-interpreter-exec command \"process launch\"") #FIXME: self.runCmd("-exec-run")
+ self.expect("\^done") #FIXME: self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Set do_segfault=1 and run (to cause a segfault error)
+ self.runCmd("-data-evaluate-expression \"do_segfault=1\"")
+ self.expect("\^done,value=\"1\"")
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+
+ # Test that *stopped is printed
+ self.expect("\*stopped,reason=\"exception-received\",exception=\"EXC_BAD_ACCESS \(code=1, address=0x0\)\",thread-id=\"1\",stopped-threads=\"all\"")
+
+ # Exit
+ self.runCmd("-gdb-exit")
+ self.expect("\^exit")
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/signal/main.cpp b/packages/Python/lldbsuite/test/tools/lldb-mi/signal/main.cpp
new file mode 100644
index 000000000000..7f6eeca70c01
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/signal/main.cpp
@@ -0,0 +1,33 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <cstddef>
+#include <unistd.h>
+
+int do_loop;
+int do_segfault;
+
+int
+main(int argc, char const *argv[])
+{
+ if (do_loop)
+ {
+ do
+ sleep(1);
+ while (do_loop); // BP_loop_condition
+ }
+
+ if (do_segfault)
+ {
+ int *null_ptr = NULL;
+ return *null_ptr;
+ }
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/stack/Makefile b/packages/Python/lldbsuite/test/tools/lldb-mi/stack/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/stack/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/stack/TestMiStack.py b/packages/Python/lldbsuite/test/tools/lldb-mi/stack/TestMiStack.py
new file mode 100644
index 000000000000..14dab38bb338
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/stack/TestMiStack.py
@@ -0,0 +1,479 @@
+"""
+Test lldb-mi -stack-xxx commands.
+"""
+
+from __future__ import print_function
+
+
+
+import lldbmi_testcase
+from lldbsuite.test.lldbtest import *
+
+class MiStackTestCase(lldbmi_testcase.MiTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_stack_list_arguments(self):
+ """Test that 'lldb-mi --interpreter' can shows arguments."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that -stack-list-arguments lists empty stack arguments if range is empty
+ self.runCmd("-stack-list-arguments 0 1 0")
+ self.expect("\^done,stack-args=\[\]")
+
+ # Test that -stack-list-arguments lists stack arguments without values
+ # (and that low-frame and high-frame are optional)
+ self.runCmd("-stack-list-arguments 0")
+ self.expect("\^done,stack-args=\[frame={level=\"0\",args=\[name=\"argc\",name=\"argv\"\]}")
+ self.runCmd("-stack-list-arguments --no-values")
+ self.expect("\^done,stack-args=\[frame={level=\"0\",args=\[name=\"argc\",name=\"argv\"\]}")
+
+ # Test that -stack-list-arguments lists stack arguments with all values
+ self.runCmd("-stack-list-arguments 1 0 0")
+ self.expect("\^done,stack-args=\[frame={level=\"0\",args=\[{name=\"argc\",value=\"1\"},{name=\"argv\",value=\".*\"}\]}\]")
+ self.runCmd("-stack-list-arguments --all-values 0 0")
+ self.expect("\^done,stack-args=\[frame={level=\"0\",args=\[{name=\"argc\",value=\"1\"},{name=\"argv\",value=\".*\"}\]}\]")
+
+ # Test that -stack-list-arguments lists stack arguments with simple values
+ self.runCmd("-stack-list-arguments 2 0 1")
+ self.expect("\^done,stack-args=\[frame={level=\"0\",args=\[{name=\"argc\",type=\"int\",value=\"1\"},{name=\"argv\",type=\"const char \*\*\",value=\".*\"}\]}")
+ self.runCmd("-stack-list-arguments --simple-values 0 1")
+ self.expect("\^done,stack-args=\[frame={level=\"0\",args=\[{name=\"argc\",type=\"int\",value=\"1\"},{name=\"argv\",type=\"const char \*\*\",value=\".*\"}\]}")
+
+ # Test that an invalid low-frame is handled
+ # FIXME: -1 is treated as unsigned int
+ self.runCmd("-stack-list-arguments 0 -1 0")
+ #self.expect("\^error")
+ self.runCmd("-stack-list-arguments 0 0")
+ self.expect("\^error,msg=\"Command 'stack-list-arguments'\. Thread frame range invalid\"")
+
+ # Test that an invalid high-frame is handled
+ # FIXME: -1 is treated as unsigned int
+ self.runCmd("-stack-list-arguments 0 0 -1")
+ #self.expect("\^error")
+
+ # Test that a missing low-frame or high-frame is handled
+ self.runCmd("-stack-list-arguments 0 0")
+ self.expect("\^error,msg=\"Command 'stack-list-arguments'\. Thread frame range invalid\"")
+
+ # Test that an invalid low-frame is handled
+ self.runCmd("-stack-list-arguments 0 0")
+ self.expect("\^error,msg=\"Command 'stack-list-arguments'\. Thread frame range invalid\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_stack_list_locals(self):
+ """Test that 'lldb-mi --interpreter' can shows local variables."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test int local variables:
+ # Run to BP_local_int_test
+ line = line_number('main.cpp', '// BP_local_int_test')
+ self.runCmd("-break-insert --file main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"2\"")
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test -stack-list-locals: use 0 or --no-values
+ self.runCmd("-stack-list-locals 0")
+ self.expect("\^done,locals=\[name=\"a\",name=\"b\"\]")
+ self.runCmd("-stack-list-locals --no-values")
+ self.expect("\^done,locals=\[name=\"a\",name=\"b\"\]")
+
+ # Test -stack-list-locals: use 1 or --all-values
+ self.runCmd("-stack-list-locals 1")
+ self.expect("\^done,locals=\[{name=\"a\",value=\"10\"},{name=\"b\",value=\"20\"}\]")
+ self.runCmd("-stack-list-locals --all-values")
+ self.expect("\^done,locals=\[{name=\"a\",value=\"10\"},{name=\"b\",value=\"20\"}\]")
+
+ # Test -stack-list-locals: use 2 or --simple-values
+ self.runCmd("-stack-list-locals 2")
+ self.expect("\^done,locals=\[{name=\"a\",type=\"int\",value=\"10\"},{name=\"b\",type=\"int\",value=\"20\"}\]")
+ self.runCmd("-stack-list-locals --simple-values")
+ self.expect("\^done,locals=\[{name=\"a\",type=\"int\",value=\"10\"},{name=\"b\",type=\"int\",value=\"20\"}\]")
+
+ # Test struct local variable:
+ # Run to BP_local_struct_test
+ line = line_number('main.cpp', '// BP_local_struct_test')
+ self.runCmd("-break-insert --file main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"3\"")
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test -stack-list-locals: use 0 or --no-values
+ self.runCmd("-stack-list-locals 0")
+ self.expect("\^done,locals=\[name=\"var_c\"\]")
+ self.runCmd("-stack-list-locals --no-values")
+ self.expect("\^done,locals=\[name=\"var_c\"\]")
+
+ # Test -stack-list-locals: use 1 or --all-values
+ self.runCmd("-stack-list-locals 1")
+ self.expect("\^done,locals=\[{name=\"var_c\",value=\"{var_a = 10, var_b = 97 'a', inner_ = {var_d = 30}}\"}\]")
+ self.runCmd("-stack-list-locals --all-values")
+ self.expect("\^done,locals=\[{name=\"var_c\",value=\"{var_a = 10, var_b = 97 'a', inner_ = {var_d = 30}}\"}\]")
+
+ # Test -stack-list-locals: use 2 or --simple-values
+ self.runCmd("-stack-list-locals 2")
+ self.expect("\^done,locals=\[{name=\"var_c\",type=\"my_type\"}\]")
+ self.runCmd("-stack-list-locals --simple-values")
+ self.expect("\^done,locals=\[{name=\"var_c\",type=\"my_type\"}\]")
+
+ # Test array local variable:
+ # Run to BP_local_array_test
+ line = line_number('main.cpp', '// BP_local_array_test')
+ self.runCmd("-break-insert --file main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"4\"")
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test -stack-list-locals: use 0 or --no-values
+ self.runCmd("-stack-list-locals 0")
+ self.expect("\^done,locals=\[name=\"array\"\]")
+ self.runCmd("-stack-list-locals --no-values")
+ self.expect("\^done,locals=\[name=\"array\"\]")
+
+ # Test -stack-list-locals: use 1 or --all-values
+ self.runCmd("-stack-list-locals 1")
+ self.expect("\^done,locals=\[{name=\"array\",value=\"{\[0\] = 100, \[1\] = 200, \[2\] = 300}\"}\]")
+ self.runCmd("-stack-list-locals --all-values")
+ self.expect("\^done,locals=\[{name=\"array\",value=\"{\[0\] = 100, \[1\] = 200, \[2\] = 300}\"}\]")
+
+ # Test -stack-list-locals: use 2 or --simple-values
+ self.runCmd("-stack-list-locals 2")
+ self.expect("\^done,locals=\[{name=\"array\",type=\"int \[3\]\"}\]")
+ self.runCmd("-stack-list-locals --simple-values")
+ self.expect("\^done,locals=\[{name=\"array\",type=\"int \[3\]\"}\]")
+
+ # Test pointers as local variable:
+ # Run to BP_local_pointer_test
+ line = line_number('main.cpp', '// BP_local_pointer_test')
+ self.runCmd("-break-insert --file main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"5\"")
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test -stack-list-locals: use 0 or --no-values
+ self.runCmd("-stack-list-locals 0")
+ self.expect("\^done,locals=\[name=\"test_str\",name=\"var_e\",name=\"ptr\"\]")
+ self.runCmd("-stack-list-locals --no-values")
+ self.expect("\^done,locals=\[name=\"test_str\",name=\"var_e\",name=\"ptr\"\]")
+
+ # Test -stack-list-locals: use 1 or --all-values
+ self.runCmd("-stack-list-locals 1")
+ self.expect("\^done,locals=\[{name=\"test_str\",value=\".*?Rakaposhi.*?\"},{name=\"var_e\",value=\"24\"},{name=\"ptr\",value=\".*?\"}\]")
+ self.runCmd("-stack-list-locals --all-values")
+ self.expect("\^done,locals=\[{name=\"test_str\",value=\".*?Rakaposhi.*?\"},{name=\"var_e\",value=\"24\"},{name=\"ptr\",value=\".*?\"}\]")
+
+ # Test -stack-list-locals: use 2 or --simple-values
+ self.runCmd("-stack-list-locals 2")
+ self.expect("\^done,locals=\[{name=\"test_str\",type=\"const char \*\",value=\".*?Rakaposhi.*?\"},{name=\"var_e\",type=\"int\",value=\"24\"},{name=\"ptr\",type=\"int \*\",value=\".*?\"}\]")
+ self.runCmd("-stack-list-locals --simple-values")
+ self.expect("\^done,locals=\[{name=\"test_str\",type=\"const char \*\",value=\".*?Rakaposhi.*?\"},{name=\"var_e\",type=\"int\",value=\"24\"},{name=\"ptr\",type=\"int \*\",value=\".*?\"}\]")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_stack_list_variables(self):
+ """Test that 'lldb-mi --interpreter' can shows local variables and arguments."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test int local variables:
+ # Run to BP_local_int_test
+ line = line_number('main.cpp', '// BP_local_int_test_with_args')
+ self.runCmd("-break-insert --file main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"2\"")
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test -stack-list-variables: use 0 or --no-values
+ self.runCmd("-stack-list-variables 0")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"c\"},{arg=\"1\",name=\"d\"},{name=\"a\"},{name=\"b\"}\]")
+ self.runCmd("-stack-list-variables --no-values")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"c\"},{arg=\"1\",name=\"d\"},{name=\"a\"},{name=\"b\"}\]")
+
+ # Test -stack-list-variables: use 1 or --all-values
+ self.runCmd("-stack-list-variables 1")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"c\",value=\"30\"},{arg=\"1\",name=\"d\",value=\"40\"},{name=\"a\",value=\"10\"},{name=\"b\",value=\"20\"}\]")
+ self.runCmd("-stack-list-variables --all-values")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"c\",value=\"30\"},{arg=\"1\",name=\"d\",value=\"40\"},{name=\"a\",value=\"10\"},{name=\"b\",value=\"20\"}\]")
+
+ # Test -stack-list-variables: use 2 or --simple-values
+ self.runCmd("-stack-list-variables 2")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"c\",type=\"int\",value=\"30\"},{arg=\"1\",name=\"d\",type=\"int\",value=\"40\"},{name=\"a\",type=\"int\",value=\"10\"},{name=\"b\",type=\"int\",value=\"20\"}\]")
+ self.runCmd("-stack-list-variables --simple-values")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"c\",type=\"int\",value=\"30\"},{arg=\"1\",name=\"d\",type=\"int\",value=\"40\"},{name=\"a\",type=\"int\",value=\"10\"},{name=\"b\",type=\"int\",value=\"20\"}\]")
+
+ # Test struct local variable:
+ # Run to BP_local_struct_test
+ line = line_number('main.cpp', '// BP_local_struct_test_with_args')
+ self.runCmd("-break-insert --file main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"3\"")
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test -stack-list-variables: use 0 or --no-values
+ self.runCmd("-stack-list-variables 0")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"var_e\"},{name=\"var_c\"}\]")
+ self.runCmd("-stack-list-variables --no-values")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"var_e\"},{name=\"var_c\"}\]")
+
+ # Test -stack-list-variables: use 1 or --all-values
+ self.runCmd("-stack-list-variables 1")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"var_e\",value=\"{var_a = 20, var_b = 98 'b', inner_ = {var_d = 40}}\"},{name=\"var_c\",value=\"{var_a = 10, var_b = 97 'a', inner_ = {var_d = 30}}\"}\]")
+ self.runCmd("-stack-list-variables --all-values")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"var_e\",value=\"{var_a = 20, var_b = 98 'b', inner_ = {var_d = 40}}\"},{name=\"var_c\",value=\"{var_a = 10, var_b = 97 'a', inner_ = {var_d = 30}}\"}\]")
+
+ # Test -stack-list-variables: use 2 or --simple-values
+ self.runCmd("-stack-list-variables 2")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"var_e\",type=\"my_type\"},{name=\"var_c\",type=\"my_type\"}\]")
+ self.runCmd("-stack-list-variables --simple-values")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"var_e\",type=\"my_type\"},{name=\"var_c\",type=\"my_type\"}\]")
+
+ # Test array local variable:
+ # Run to BP_local_array_test
+ line = line_number('main.cpp', '// BP_local_array_test_with_args')
+ self.runCmd("-break-insert --file main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"4\"")
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test -stack-list-variables: use 0 or --no-values
+ self.runCmd("-stack-list-variables 0")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"other_array\"},{name=\"array\"}\]")
+ self.runCmd("-stack-list-variables --no-values")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"other_array\"},{name=\"array\"}\]")
+
+ # Test -stack-list-variables: use 1 or --all-values
+ self.runCmd("-stack-list-variables 1")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"other_array\",value=\".*?\"},{name=\"array\",value=\"{\[0\] = 100, \[1\] = 200, \[2\] = 300}\"}\]")
+ self.runCmd("-stack-list-variables --all-values")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"other_array\",value=\".*?\"},{name=\"array\",value=\"{\[0\] = 100, \[1\] = 200, \[2\] = 300}\"}\]")
+
+ # Test -stack-list-variables: use 2 or --simple-values
+ self.runCmd("-stack-list-variables 2")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"other_array\",type=\"int \*\",value=\".*?\"},{name=\"array\",type=\"int \[3\]\"}\]")
+ self.runCmd("-stack-list-variables --simple-values")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"other_array\",type=\"int \*\",value=\".*?\"},{name=\"array\",type=\"int \[3\]\"}\]")
+
+ # Test pointers as local variable:
+ # Run to BP_local_pointer_test
+ line = line_number('main.cpp', '// BP_local_pointer_test_with_args')
+ self.runCmd("-break-insert --file main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"5\"")
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test -stack-list-variables: use 0 or --no-values
+ self.runCmd("-stack-list-variables 0")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"arg_str\"},{arg=\"1\",name=\"arg_ptr\"},{name=\"test_str\"},{name=\"var_e\"},{name=\"ptr\"}\]")
+ self.runCmd("-stack-list-variables --no-values")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"arg_str\"},{arg=\"1\",name=\"arg_ptr\"},{name=\"test_str\"},{name=\"var_e\"},{name=\"ptr\"}\]")
+
+ # Test -stack-list-variables: use 1 or --all-values
+ self.runCmd("-stack-list-variables 1")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"arg_str\",value=\".*?String.*?\"},{arg=\"1\",name=\"arg_ptr\",value=\".*?\"},{name=\"test_str\",value=\".*?Rakaposhi.*?\"},{name=\"var_e\",value=\"24\"},{name=\"ptr\",value=\".*?\"}\]")
+ self.runCmd("-stack-list-variables --all-values")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"arg_str\",value=\".*?String.*?\"},{arg=\"1\",name=\"arg_ptr\",value=\".*?\"},{name=\"test_str\",value=\".*?Rakaposhi.*?\"},{name=\"var_e\",value=\"24\"},{name=\"ptr\",value=\".*?\"}\]")
+
+ # Test -stack-list-variables: use 2 or --simple-values
+ self.runCmd("-stack-list-variables 2")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"arg_str\",type=\"const char \*\",value=\".*?String.*?\"},{arg=\"1\",name=\"arg_ptr\",type=\"int \*\",value=\".*?\"},{name=\"test_str\",type=\"const char \*\",value=\".*?Rakaposhi.*?\"},{name=\"var_e\",type=\"int\",value=\"24\"},{name=\"ptr\",type=\"int \*\",value=\".*?\"}\]")
+ self.runCmd("-stack-list-variables --simple-values")
+ self.expect("\^done,variables=\[{arg=\"1\",name=\"arg_str\",type=\"const char \*\",value=\".*?String.*?\"},{arg=\"1\",name=\"arg_ptr\",type=\"int \*\",value=\".*?\"},{name=\"test_str\",type=\"const char \*\",value=\".*?Rakaposhi.*?\"},{name=\"var_e\",type=\"int\",value=\"24\"},{name=\"ptr\",type=\"int \*\",value=\".*?\"}\]")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_stack_info_depth(self):
+ """Test that 'lldb-mi --interpreter' can shows depth of the stack."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that -stack-info-depth works
+ # (and that max-depth is optional)
+ self.runCmd("-stack-info-depth")
+ self.expect("\^done,depth=\"[1-9]\"")
+
+ # Test that max-depth restricts check of stack depth
+ #FIXME: max-depth argument is ignored
+ self.runCmd("-stack-info-depth 1")
+ #self.expect("\^done,depth=\"1\"")
+
+ # Test that invalid max-depth argument is handled
+ #FIXME: max-depth argument is ignored
+ self.runCmd("-stack-info-depth -1")
+ #self.expect("\^error")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @skipUnlessDarwin
+ def test_lldbmi_stack_info_frame(self):
+ """Test that 'lldb-mi --interpreter' can show information about current frame."""
+
+ self.spawnLldbMi(args = None)
+
+ # Test that -stack-info-frame fails when program isn't running
+ self.runCmd("-stack-info-frame")
+ self.expect("\^error,msg=\"Command 'stack-info-frame'\. Invalid process during debug session\"")
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that -stack-info-frame works when program was stopped on BP
+ self.runCmd("-stack-info-frame")
+ self.expect("\^done,frame=\{level=\"0\",addr=\"0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\"\}")
+
+ # Select frame #1
+ self.runCmd("-stack-select-frame 1")
+ self.expect("\^done")
+
+ # Test that -stack-info-frame works when specified frame was selected
+ self.runCmd("-stack-info-frame")
+ self.expect("\^done,frame=\{level=\"1\",addr=\"0x[0-9a-f]+\",func=\".+?\",file=\"\?\?\",fullname=\"\?\?\",line=\"-1\"\}")
+
+ # Test that -stack-info-frame fails when an argument is specified
+ #FIXME: unknown argument is ignored
+ self.runCmd("-stack-info-frame unknown_arg")
+ #self.expect("\^error")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_stack_list_frames(self):
+ """Test that 'lldb-mi --interpreter' can lists the frames on the stack."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test stack frame: get frame #0 info
+ self.runCmd("-stack-list-frames 0 0")
+ self.expect("\^done,stack=\[frame=\{level=\"0\",addr=\"0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\"\}\]")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_stack_select_frame(self):
+ """Test that 'lldb-mi --interpreter' can choose current frame."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that -stack-select-frame requires 1 mandatory argument
+ self.runCmd("-stack-select-frame")
+ self.expect("\^error,msg=\"Command 'stack-select-frame'\. Command Args\. Validation failed. Mandatory args not found: frame_id\"")
+
+ # Test that -stack-select-frame fails on invalid frame number
+ self.runCmd("-stack-select-frame 99")
+ self.expect("\^error,msg=\"Command 'stack-select-frame'\. Frame ID invalid\"")
+
+ # Test that current frame is #0
+ self.runCmd("-stack-info-frame")
+ self.expect("\^done,frame=\{level=\"0\",addr=\"0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\"\}")
+
+ # Test that -stack-select-frame can select the selected frame
+ self.runCmd("-stack-select-frame 0")
+ self.expect("\^done")
+
+ # Test that current frame is still #0
+ self.runCmd("-stack-info-frame")
+ self.expect("\^done,frame=\{level=\"0\",addr=\"0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\"\}")
+
+ # Test that -stack-select-frame can select frame #1 (parent frame)
+ self.runCmd("-stack-select-frame 1")
+ self.expect("\^done")
+
+ # Test that current frame is #1
+ # Note that message is different in Darwin and Linux:
+ # Darwin: "^done,frame={level=\"1\",addr=\"0x[0-9a-f]+\",func=\"start\",file=\"??\",fullname=\"??\",line=\"-1\"}"
+ # Linux: "^done,frame={level=\"1\",addr=\"0x[0-9a-f]+\",func=\".+\",file=\".+\",fullname=\".+\",line=\"\d+\"}"
+ self.runCmd("-stack-info-frame")
+ self.expect("\^done,frame=\{level=\"1\",addr=\"0x[0-9a-f]+\",func=\".+?\",file=\".+?\",fullname=\".+?\",line=\"(-1|\d+)\"\}")
+
+ # Test that -stack-select-frame can select frame #0 (child frame)
+ self.runCmd("-stack-select-frame 0")
+ self.expect("\^done")
+
+ # Test that current frame is #0 and it has the same information
+ self.runCmd("-stack-info-frame")
+ self.expect("\^done,frame=\{level=\"0\",addr=\"0x[0-9a-f]+\",func=\"main\",file=\"main\.cpp\",fullname=\".+?main\.cpp\",line=\"\d+\"\}")
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/stack/main.cpp b/packages/Python/lldbsuite/test/tools/lldb-mi/stack/main.cpp
new file mode 100644
index 000000000000..e11f83e108ec
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/stack/main.cpp
@@ -0,0 +1,127 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+struct inner
+{
+ int var_d;
+};
+
+struct my_type
+{
+ int var_a;
+ char var_b;
+ struct inner inner_;
+};
+
+int
+local_int_test(void)
+{
+ int a = 10, b = 20;
+ return 0; // BP_local_int_test
+}
+
+int
+local_int_test_with_args(int c, int d)
+{
+ int a = 10, b = 20;
+ return 0; // BP_local_int_test_with_args
+}
+
+int
+local_struct_test(void)
+{
+ struct my_type var_c;
+ var_c.var_a = 10;
+ var_c.var_b = 'a';
+ var_c.inner_.var_d = 30;
+ return 0; // BP_local_struct_test
+}
+
+int local_struct_test_with_args(struct my_type var_e)
+{
+ struct my_type var_c;
+ var_c.var_a = 10;
+ var_c.var_b = 'a';
+ var_c.inner_.var_d = 30;
+ return 0; // BP_local_struct_test_with_args
+}
+
+int
+local_array_test(void)
+{
+ int array[3];
+ array[0] = 100;
+ array[1] = 200;
+ array[2] = 300;
+ return 0; // BP_local_array_test
+}
+
+int
+local_array_test_with_args(int* other_array)
+{
+ int array[3];
+ array[0] = 100;
+ array[1] = 200;
+ array[2] = 300;
+ return 0; // BP_local_array_test_with_args
+}
+
+int
+local_pointer_test(void)
+{
+ const char *test_str = "Rakaposhi";
+ int var_e = 24;
+ int *ptr = &var_e;
+ return 0; // BP_local_pointer_test
+}
+
+int
+local_pointer_test_with_args(const char *arg_str, int *arg_ptr)
+{
+ const char *test_str = "Rakaposhi";
+ int var_e = 24;
+ int *ptr = &var_e;
+ return 0; // BP_local_pointer_test_with_args
+}
+
+int do_tests_with_args()
+{
+ local_int_test_with_args(30, 40);
+
+ struct my_type var_e;
+ var_e.var_a = 20;
+ var_e.var_b = 'b';
+ var_e.inner_.var_d = 40;
+ local_struct_test_with_args(var_e);
+
+ int array[3];
+ array[0] = 400;
+ array[1] = 500;
+ array[2] = 600;
+ local_array_test_with_args(array);
+
+ const char *test_str = "String";
+ int var_z = 25;
+ int *ptr = &var_z;
+ local_pointer_test_with_args(test_str, ptr);
+
+ return 0;
+}
+
+int
+main(int argc, char const *argv[])
+{
+ local_int_test();
+ local_struct_test();
+ local_array_test();
+ local_pointer_test();
+
+ do_tests_with_args();
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/Makefile b/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/TestMiStartupOptions.py b/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/TestMiStartupOptions.py
new file mode 100644
index 000000000000..8f02f1c1eca8
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/TestMiStartupOptions.py
@@ -0,0 +1,290 @@
+"""
+Test lldb-mi startup options.
+"""
+
+from __future__ import print_function
+
+
+
+import lldbmi_testcase
+from lldbsuite.test.lldbtest import *
+
+class MiStartupOptionsTestCase(lldbmi_testcase.MiTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_executable_option_file(self):
+ """Test that 'lldb-mi --interpreter %s' loads executable file."""
+
+ self.spawnLldbMi(args = "%s" % self.myexe)
+
+ # Test that the executable is loaded when file was specified
+ self.expect("-file-exec-and-symbols \"%s\"" % self.myexe)
+ self.expect("\^done")
+
+ # Test that lldb-mi is ready when executable was loaded
+ self.expect(self.child_prompt, exactly = True)
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Continue
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"exited-normally\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_executable_option_unknown_file(self):
+ """Test that 'lldb-mi --interpreter %s' fails on unknown executable file."""
+
+ # Prepare path to executable
+ path = "unknown_file"
+
+ self.spawnLldbMi(args = "%s" % path)
+
+ # Test that the executable isn't loaded when unknown file was specified
+ self.expect("-file-exec-and-symbols \"%s\"" % path)
+ self.expect("\^error,msg=\"Command 'file-exec-and-symbols'. Target binary '%s' is invalid. error: unable to find executable for '%s'\"" % (path, path))
+
+ # Test that lldb-mi is ready when executable was loaded
+ self.expect(self.child_prompt, exactly = True)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_executable_option_absolute_path(self):
+ """Test that 'lldb-mi --interpreter %s' loads executable which is specified via absolute path."""
+
+ # Prepare path to executable
+ import os
+ path = os.path.join(os.getcwd(), self.myexe)
+
+ self.spawnLldbMi(args = "%s" % path)
+
+ # Test that the executable is loaded when file was specified using absolute path
+ self.expect("-file-exec-and-symbols \"%s\"" % path)
+ self.expect("\^done")
+
+ # Test that lldb-mi is ready when executable was loaded
+ self.expect(self.child_prompt, exactly = True)
+
+ # Run
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"exited-normally\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_executable_option_relative_path(self):
+ """Test that 'lldb-mi --interpreter %s' loads executable which is specified via relative path."""
+
+ # Prepare path to executable
+ path = "./%s" % self.myexe
+
+ self.spawnLldbMi(args = "%s" % path)
+
+ # Test that the executable is loaded when file was specified using relative path
+ self.expect("-file-exec-and-symbols \"%s\"" % path)
+ self.expect("\^done")
+
+ # Test that lldb-mi is ready when executable was loaded
+ self.expect(self.child_prompt, exactly = True)
+
+ # Run
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"exited-normally\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_executable_option_unknown_path(self):
+ """Test that 'lldb-mi --interpreter %s' fails on executable file which is specified via unknown path."""
+
+ # Prepare path to executable
+ path = "unknown_dir/%s" % self.myexe
+
+ self.spawnLldbMi(args = "%s" % path)
+
+ # Test that the executable isn't loaded when file was specified using unknown path
+ self.expect("-file-exec-and-symbols \"%s\"" % path)
+ self.expect("\^error,msg=\"Command 'file-exec-and-symbols'. Target binary '%s' is invalid. error: unable to find executable for '%s'\"" % (path, path))
+
+ # Test that lldb-mi is ready when executable was loaded
+ self.expect(self.child_prompt, exactly = True)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots
+ def test_lldbmi_source_option_start_script(self):
+ """Test that 'lldb-mi --interpreter' can execute user's commands after initial commands were executed."""
+
+ # Prepared source file
+ sourceFile = "start_script"
+
+ self.spawnLldbMi(args = "--source %s" % sourceFile)
+
+ # After '-file-exec-and-symbols a.out'
+ self.expect("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # After '-break-insert -f main'
+ self.expect("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+
+ # After '-exec-run'
+ self.expect("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # After '-break-insert main.cpp:BP_return'
+ line = line_number('main.cpp', '//BP_return')
+ self.expect("-break-insert main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"2\"")
+
+ # After '-exec-continue'
+ self.expect("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that lldb-mi is ready after execution of --source start_script
+ self.expect(self.child_prompt, exactly = True)
+
+ # Try to evaluate 'a' expression
+ self.runCmd("-data-evaluate-expression a")
+ self.expect("\^done,value=\"10\"")
+ self.expect(self.child_prompt, exactly = True)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots
+ def test_lldbmi_source_option_start_script_exit(self):
+ """Test that 'lldb-mi --interpreter' can execute a prepared file which passed via --source option."""
+
+ # Prepared source file
+ sourceFile = "start_script_exit"
+
+ self.spawnLldbMi(args = "--source %s" % sourceFile)
+
+ # After '-file-exec-and-symbols a.out'
+ self.expect("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # After '-break-insert -f main'
+ self.expect("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+
+ # After '-exec-run'
+ self.expect("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # After '-break-insert main.cpp:BP_return'
+ line = line_number('main.cpp', '//BP_return')
+ self.expect("-break-insert main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"2\"")
+
+ # After '-exec-continue'
+ self.expect("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # After '-data-evaluate-expression a'
+ self.expect("-data-evaluate-expression a")
+ self.expect("\^done,value=\"10\"")
+
+ # After '-gdb-exit'
+ self.expect("-gdb-exit")
+ self.expect("\^exit")
+ self.expect("\*stopped,reason=\"exited-normally\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_source_option_start_script_error(self):
+ """Test that 'lldb-mi --interpreter' stops execution of initial commands in case of error."""
+
+ # Prepared source file
+ sourceFile = "start_script_error"
+
+ self.spawnLldbMi(args = "--source %s" % sourceFile)
+
+ # After '-file-exec-and-symbols a.out'
+ self.expect("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # After '-break-ins -f main'
+ self.expect("-break-ins -f main")
+ self.expect("\^error")
+
+ # Test that lldb-mi is ready after execution of --source start_script
+ self.expect(self.child_prompt, exactly = True)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_log_option(self):
+ """Test that 'lldb-mi --log' creates a log file in the current directory."""
+
+ logDirectory = "."
+ self.spawnLldbMi(args = "%s --log" % self.myexe)
+
+ # Test that the executable is loaded when file was specified
+ self.expect("-file-exec-and-symbols \"%s\"" % self.myexe)
+ self.expect("\^done")
+
+ # Test that lldb-mi is ready when executable was loaded
+ self.expect(self.child_prompt, exactly = True)
+
+ # Run
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"exited-normally\"")
+
+ # Check log file is created
+ import glob,os
+ logFile = glob.glob(logDirectory + "/lldb-mi-*.log")
+
+ if not logFile:
+ self.fail("log file not found")
+
+ # Delete log
+ for f in logFile:
+ os.remove(f)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_log_directory_option(self):
+ """Test that 'lldb-mi --log --log-dir' creates a log file in the directory specified by --log-dir."""
+
+ # Create log in temp directory
+ import tempfile
+ logDirectory = tempfile.gettempdir()
+
+ self.spawnLldbMi(args = "%s --log --log-dir=%s" % (self.myexe,logDirectory))
+
+ # Test that the executable is loaded when file was specified
+ self.expect("-file-exec-and-symbols \"%s\"" % self.myexe)
+ self.expect("\^done")
+
+ # Test that lldb-mi is ready when executable was loaded
+ self.expect(self.child_prompt, exactly = True)
+
+ # Run
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"exited-normally\"")
+
+ # Check log file is created
+ import glob,os
+ logFile = glob.glob(logDirectory + "/lldb-mi-*.log")
+
+ if not logFile:
+ self.fail("log file not found")
+
+ # Delete log
+ for f in logFile:
+ os.remove(f)
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/main.cpp b/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/main.cpp
new file mode 100644
index 000000000000..7f2d5246faf9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/main.cpp
@@ -0,0 +1,15 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+int
+main(int argc, char const *argv[])
+{
+ int a = 10;
+ return 0; //BP_return
+}
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/start_script b/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/start_script
new file mode 100644
index 000000000000..511c02248258
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/start_script
@@ -0,0 +1,5 @@
+-file-exec-and-symbols a.out
+-break-insert -f main
+-exec-run
+-break-insert main.cpp:14
+-exec-continue
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/start_script_error b/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/start_script_error
new file mode 100644
index 000000000000..d834e7407c57
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/start_script_error
@@ -0,0 +1,2 @@
+-file-exec-and-symbols a.out
+-break-ins -f main
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/start_script_exit b/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/start_script_exit
new file mode 100644
index 000000000000..8379018c29df
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/startup_options/start_script_exit
@@ -0,0 +1,7 @@
+-file-exec-and-symbols a.out
+-break-insert -f main
+-exec-run
+-break-insert main.cpp:14
+-exec-continue
+-data-evaluate-expression a
+-gdb-exit
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/Makefile b/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/Makefile
new file mode 100644
index 000000000000..dde38f4e486c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp symbol_list_lines_inline_test.cpp symbol_list_lines_inline_test2.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/TestMiSymbol.py b/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/TestMiSymbol.py
new file mode 100644
index 000000000000..3566b2f220c2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/TestMiSymbol.py
@@ -0,0 +1,81 @@
+"""
+Test lldb-mi -symbol-xxx commands.
+"""
+
+from __future__ import print_function
+
+
+
+import lldbmi_testcase
+from lldbsuite.test.lldbtest import *
+
+class MiSymbolTestCase(lldbmi_testcase.MiTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @expectedFailureLinux # new failure after r256863
+ def test_lldbmi_symbol_list_lines_file(self):
+ """Test that 'lldb-mi --interpreter' works for -symbol-list-lines when file exists."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Get address of main and its line
+ self.runCmd("-data-evaluate-expression main")
+ self.expect("\^done,value=\"0x[0-9a-f]+ \(a.out`main at main.cpp:[0-9]+\)\"")
+ addr = int(self.child.after.split("\"")[1].split(" ")[0], 16)
+ line = line_number('main.cpp', '// FUNC_main')
+
+ # Test that -symbol-list-lines works on valid data
+ self.runCmd("-symbol-list-lines main.cpp")
+ self.expect("\^done,lines=\[\{pc=\"0x0*%x\",line=\"%d\"\}(,\{pc=\"0x[0-9a-f]+\",line=\"\d+\"\})+\]" % (addr, line))
+
+ # Test that -symbol-list-lines doesn't include lines from other sources
+ # by checking the first and last line, and making sure the other lines
+ # are between 30 and 39.
+ sline = line_number('symbol_list_lines_inline_test2.cpp', '// FUNC_gfunc2')
+ eline = line_number('symbol_list_lines_inline_test2.cpp', '// END_gfunc2')
+ self.runCmd("-symbol-list-lines symbol_list_lines_inline_test2.cpp")
+ self.expect("\^done,lines=\[\{pc=\"0x[0-9a-f]+\",line=\"%d\"\}(,\{pc=\"0x[0-9a-f]+\",line=\"3\d\"\})*,\{pc=\"0x[0-9a-f]+\",line=\"%d\"\}(,\{pc=\"0x[0-9a-f]+\",line=\"3\d\"\})*\]" % (sline, eline))
+ ##FIXME: This doesn't work for symbol_list_lines_inline_test.cpp due to clang bug llvm.org/pr24716 (fixed in newer versions of clang)
+ ##sline = line_number('symbol_list_lines_inline_test.cpp', '// FUNC_gfunc')
+ ##eline = line_number('symbol_list_lines_inline_test.cpp', '// STRUCT_s')
+ ##self.runCmd("-symbol-list-lines symbol_list_lines_inline_test.cpp")
+ ##self.expect("\^done,lines=\[\{pc=\"0x[0-9a-f]+\",line=\"%d\"\}(,\{pc=\"0x[0-9a-f]+\",line=\"3\d\"\})*,\{pc=\"0x[0-9a-f]+\",line=\"%d\"\}\]" % (sline, eline))
+
+ # Test that -symbol-list-lines works on header files by checking the first
+ # and last line, and making sure the other lines are under 29.
+ sline = line_number('symbol_list_lines_inline_test.h', '// FUNC_ifunc')
+ eline = line_number('symbol_list_lines_inline_test.h', '// FUNC_mfunc')
+ self.runCmd("-symbol-list-lines symbol_list_lines_inline_test.h")
+ self.expect("\^done,lines=\[\{pc=\"0x[0-9a-f]+\",line=\"%d\"\}(,\{pc=\"0x[0-9a-f]+\",line=\"\d\"\})*(,\{pc=\"0x[0-9a-f]+\",line=\"1\d\"\})*,\{pc=\"0x[0-9a-f]+\",line=\"%d\"\}(,\{pc=\"0x[0-9a-f]+\",line=\"2\d\"\})*\]" % (sline, eline))
+
+ # Test that -symbol-list-lines fails when file doesn't exist
+ self.runCmd("-symbol-list-lines unknown_file")
+ self.expect("\^error,message=\"error: No source filenames matched 'unknown_file'\. \"")
+
+ # Test that -symbol-list-lines fails when file is specified using relative path
+ self.runCmd("-symbol-list-lines ./main.cpp")
+ self.expect("\^error,message=\"error: No source filenames matched '\./main\.cpp'\. \"")
+
+ # Test that -symbol-list-lines works when file is specified using absolute path
+ import os
+ path = os.path.join(os.getcwd(), "main.cpp")
+ self.runCmd("-symbol-list-lines \"%s\"" % path)
+ self.expect("\^done,lines=\[\{pc=\"0x0*%x\",line=\"%d\"\}(,\{pc=\"0x[0-9a-f]+\",line=\"\d+\"\})+\]" % (addr, line))
+
+ # Test that -symbol-list-lines fails when file doesn't exist
+ self.runCmd("-symbol-list-lines unknown_dir/main.cpp")
+ self.expect("\^error,message=\"error: No source filenames matched 'unknown_dir/main\.cpp'\. \"")
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/main.cpp b/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/main.cpp
new file mode 100644
index 000000000000..6d725a5759b5
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/main.cpp
@@ -0,0 +1,18 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+extern int j;
+extern int gfunc(int i);
+extern int gfunc2(int i);
+int
+main()
+{ // FUNC_main
+ int i = gfunc(j) + gfunc2(j);
+ return i == 0;
+}
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/symbol_list_lines_inline_test.cpp b/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/symbol_list_lines_inline_test.cpp
new file mode 100644
index 000000000000..c432ba8c477c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/symbol_list_lines_inline_test.cpp
@@ -0,0 +1,39 @@
+// Skip lines so we can make sure we're not seeing any lines from
+// symbol_list_lines_inline_test.h included in -symbol-list-lines
+// symbol_list_lines_inline_test.cpp, by checking that all the lines
+// are between 30 and 39.
+// line 5
+// line 6
+// line 7
+// line 8
+// line 9
+// line 10
+// line 11
+// line 12
+// line 13
+// line 14
+// line 15
+// line 16
+// line 17
+// line 18
+// line 19
+// line 20
+// line 21
+// line 22
+// line 23
+// line 24
+// line 25
+// line 26
+// line 27
+// line 28
+// line 29
+#include "symbol_list_lines_inline_test.h"
+int
+gfunc(int i)
+{ // FUNC_gfunc
+ return ns::ifunc(i);
+}
+namespace ns
+{
+S s; // STRUCT_s
+}
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/symbol_list_lines_inline_test.h b/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/symbol_list_lines_inline_test.h
new file mode 100644
index 000000000000..4b986dc69321
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/symbol_list_lines_inline_test.h
@@ -0,0 +1,24 @@
+namespace ns
+{
+inline int
+ifunc(int i)
+{ // FUNC_ifunc
+ return i;
+}
+struct S
+{
+ int a;
+ int b;
+ S()
+ : a(3)
+ , b(4)
+ {
+ }
+ int
+ mfunc()
+ { // FUNC_mfunc
+ return a + b;
+ }
+};
+extern S s;
+}
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/symbol_list_lines_inline_test2.cpp b/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/symbol_list_lines_inline_test2.cpp
new file mode 100644
index 000000000000..cfedf47ad6b1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/symbol/symbol_list_lines_inline_test2.cpp
@@ -0,0 +1,38 @@
+// Skip lines so we can make sure we're not seeing any lines from
+// symbol_list_lines_inline_test.h included in -symbol-list-lines
+// symbol_list_lines_inline_test2.cpp, by checking that all the lines
+// are between 30 and 39.
+// line 5
+// line 6
+// line 7
+// line 8
+// line 9
+// line 10
+// line 11
+// line 12
+// line 13
+// line 14
+// line 15
+// line 16
+// line 17
+// line 18
+// line 19
+// line 20
+// line 21
+// line 22
+// line 23
+// line 24
+// line 25
+// line 26
+// line 27
+// line 28
+// line 29
+#include "symbol_list_lines_inline_test.h"
+int j = 2;
+int
+gfunc2(int i)
+{ // FUNC_gfunc2
+ i += ns::s.mfunc();
+ i += ns::ifunc(i);
+ return i == 0; // END_gfunc2
+}
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/syntax/Makefile b/packages/Python/lldbsuite/test/tools/lldb-mi/syntax/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/syntax/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/syntax/TestMiSyntax.py b/packages/Python/lldbsuite/test/tools/lldb-mi/syntax/TestMiSyntax.py
new file mode 100644
index 000000000000..f8a6743eb16d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/syntax/TestMiSyntax.py
@@ -0,0 +1,80 @@
+"""
+Test that the lldb-mi driver understands MI command syntax.
+"""
+
+from __future__ import print_function
+
+
+
+import lldbmi_testcase
+from lldbsuite.test.lldbtest import *
+
+class MiSyntaxTestCase(lldbmi_testcase.MiTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_tokens(self):
+ """Test that 'lldb-mi --interpreter' prints command tokens."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("000-file-exec-and-symbols %s" % self.myexe)
+ self.expect("000\^done")
+
+ # Run to main
+ self.runCmd("100000001-break-insert -f main")
+ self.expect("100000001\^done,bkpt={number=\"1\"")
+ self.runCmd("2-exec-run")
+ self.expect("2\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Exit
+ self.runCmd("0000000000000000000003-exec-continue")
+ self.expect("0000000000000000000003\^running")
+ self.expect("\*stopped,reason=\"exited-normally\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_specialchars(self):
+ """Test that 'lldb-mi --interpreter' handles complicated strings."""
+
+ # Create an alias for myexe
+ complicated_myexe = "C--mpl-x file's`s @#$%^&*()_+-={}[]| name"
+ os.symlink(self.myexe, complicated_myexe)
+ self.addTearDownHook(lambda: os.unlink(complicated_myexe))
+
+ self.spawnLldbMi(args = "\"%s\"" % complicated_myexe)
+
+ # Test that the executable was loaded
+ self.expect("-file-exec-and-symbols \"%s\"" % complicated_myexe, exactly = True)
+ self.expect("\^done")
+
+ # Check that it was loaded correctly
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @expectedFailureLinux # Failing in ~6/600 dosep runs (build 3120-3122)
+ def test_lldbmi_process_output(self):
+ """Test that 'lldb-mi --interpreter' wraps process output correctly."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+
+ # Test that a process output is wrapped correctly
+ self.expect("\@\"'\\\\r\\\\n\"")
+ self.expect("\@\"` - it's \\\\\\\\n\\\\x12\\\\\"\\\\\\\\\\\\\"")
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/syntax/main.cpp b/packages/Python/lldbsuite/test/tools/lldb-mi/syntax/main.cpp
new file mode 100644
index 000000000000..d2935b08f872
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/syntax/main.cpp
@@ -0,0 +1,17 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <cstdio>
+
+int
+main(int argc, char const *argv[])
+{
+ printf("'\n` - it's \\n\x12\"\\\"");
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/target/Makefile b/packages/Python/lldbsuite/test/tools/lldb-mi/target/Makefile
new file mode 100644
index 000000000000..b2550fe780d9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/target/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := test_attach.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/target/TestMiTarget.py b/packages/Python/lldbsuite/test/tools/lldb-mi/target/TestMiTarget.py
new file mode 100644
index 000000000000..73ef913691cf
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/target/TestMiTarget.py
@@ -0,0 +1,125 @@
+"""
+Test lldb-mi -target-xxx commands.
+"""
+
+from __future__ import print_function
+
+
+
+import lldbmi_testcase
+from lldbsuite.test.lldbtest import *
+
+class MiTargetTestCase(lldbmi_testcase.MiTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @skipIfLinux # cannot attach to process on linux
+ def test_lldbmi_target_attach_wait_for(self):
+ """Test that 'lldb-mi --interpreter' works for -target-attach -n <name> --waitfor."""
+
+ # Build target executable with unique name
+ exeName = self.testMethodName
+ d = {'EXE': exeName}
+ self.buildProgram("test_attach.cpp", exeName)
+ self.addTearDownCleanup(dictionary=d)
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ # FIXME: -file-exec-and-sybmols is not required for target attach, but the test will not pass without this
+ self.runCmd("-file-exec-and-symbols %s" % exeName)
+ self.expect("\^done")
+
+ # Set up attach
+ self.runCmd("-target-attach -n %s --waitfor" % exeName)
+ time.sleep(4) # Give attach time to setup
+
+ # Start target process
+ self.spawnSubprocess(os.path.join(os.path.dirname(__file__), exeName));
+ self.addTearDownHook(self.cleanupSubprocesses)
+ self.expect("\^done")
+
+ # Set breakpoint on printf
+ line = line_number('test_attach.cpp', '// BP_i++')
+ self.runCmd("-break-insert -f test_attach.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"1\"")
+
+ # Continue to breakpoint
+ self.runCmd("-exec-continue")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Detach
+ self.runCmd("-target-detach")
+ self.expect("\^done")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @skipIfLinux # cannot attach to process on linux
+ def test_lldbmi_target_attach_name(self):
+ """Test that 'lldb-mi --interpreter' works for -target-attach -n <name>."""
+
+ # Build target executable with unique name
+ exeName = self.testMethodName
+ d = {'EXE': exeName}
+ self.buildProgram("test_attach.cpp", exeName)
+ self.addTearDownCleanup(dictionary=d)
+
+ # Start target process
+ targetProcess = self.spawnSubprocess(os.path.join(os.path.dirname(__file__), exeName));
+ self.addTearDownHook(self.cleanupSubprocesses)
+
+ self.spawnLldbMi(args = None)
+
+ # Set up atatch
+ self.runCmd("-target-attach -n %s" % exeName)
+ self.expect("\^done")
+
+ # Set breakpoint on printf
+ line = line_number('test_attach.cpp', '// BP_i++')
+ self.runCmd("-break-insert -f test_attach.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"1\"")
+
+ # Continue to breakpoint
+ self.runCmd("-exec-continue")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Detach
+ self.runCmd("-target-detach")
+ self.expect("\^done")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @skipIfLinux # cannot attach to process on linux
+ def test_lldbmi_target_attach_pid(self):
+ """Test that 'lldb-mi --interpreter' works for -target-attach <pid>."""
+
+ # Build target executable with unique name
+ exeName = self.testMethodName
+ d = {'EXE': exeName}
+ self.buildProgram("test_attach.cpp", exeName)
+ self.addTearDownCleanup(dictionary=d)
+
+ # Start target process
+ targetProcess = self.spawnSubprocess(os.path.join(os.path.dirname(__file__), exeName));
+ self.addTearDownHook(self.cleanupSubprocesses)
+
+ self.spawnLldbMi(args = None)
+
+ # Set up atatch
+ self.runCmd("-target-attach %d" % targetProcess.pid)
+ self.expect("\^done")
+
+ # Set breakpoint on printf
+ line = line_number('test_attach.cpp', '// BP_i++')
+ self.runCmd("-break-insert -f test_attach.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"1\"")
+
+ # Continue to breakpoint
+ self.runCmd("-exec-continue")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Detach
+ self.runCmd("-target-detach")
+ self.expect("\^done")
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/target/test_attach.cpp b/packages/Python/lldbsuite/test/tools/lldb-mi/target/test_attach.cpp
new file mode 100644
index 000000000000..caaf33a46faf
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/target/test_attach.cpp
@@ -0,0 +1,21 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <cstdio>
+
+int
+main(int argc, char const *argv[])
+{
+ int i = 0;
+ for (;;)
+ {
+ i++; // BP_i++
+ }
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/variable/Makefile b/packages/Python/lldbsuite/test/tools/lldb-mi/variable/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/variable/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/variable/TestMiGdbSetShowPrint.py b/packages/Python/lldbsuite/test/tools/lldb-mi/variable/TestMiGdbSetShowPrint.py
new file mode 100644
index 000000000000..067df6408bd4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/variable/TestMiGdbSetShowPrint.py
@@ -0,0 +1,227 @@
+#coding=utf8
+"""
+Test lldb-mi -gdb-set and -gdb-show commands for 'print option-name'.
+"""
+
+from __future__ import print_function
+
+
+
+import lldbmi_testcase
+from lldbsuite.test.lldbtest import *
+
+class MiGdbSetShowTestCase(lldbmi_testcase.MiTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ # evaluates array when char-array-as-string is off
+ def eval_and_check_array(self, var, typ, length):
+ self.runCmd("-var-create - * %s" % var)
+ self.expect('\^done,name="var\d+",numchild="%d",value="\[%d\]",type="%s \[%d\]",thread-id="1",has_more="0"' % (length, length, typ, length))
+
+ # evaluates any type which can be represented as string of characters
+ def eval_and_match_string(self, var, value, typ):
+ value=value.replace("\\", "\\\\").replace("\"", "\\\"")
+ self.runCmd("-var-create - * " + var)
+ self.expect('\^done,name="var\d+",numchild="[0-9]+",value="%s",type="%s",thread-id="1",has_more="0"' % (value, typ))
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots
+ def test_lldbmi_gdb_set_show_print_char_array_as_string(self):
+ """Test that 'lldb-mi --interpreter' can print array of chars as string."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to BP_gdb_set_show_print_char_array_as_string_test
+ line = line_number('main.cpp', '// BP_gdb_set_show_print_char_array_as_string_test')
+ self.runCmd("-break-insert main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that default print char-array-as-string value is "off"
+ self.runCmd("-gdb-show print char-array-as-string")
+ self.expect("\^done,value=\"off\"")
+
+ # Test that a char* is expanded to string when print char-array-as-string is "off"
+ self.eval_and_match_string("cp", r'0x[0-9a-f]+ \"\\t\\\"hello\\\"\\n\"', r'const char \*')
+
+ # Test that a char[] isn't expanded to string when print char-array-as-string is "off"
+ self.eval_and_check_array("ca", "const char", 10);
+
+ # Test that a char16_t* is expanded to string when print char-array-as-string is "off"
+ self.eval_and_match_string("u16p", r'0x[0-9a-f]+ u\"\\t\\\"hello\\\"\\n\"', r'const char16_t \*')
+
+ # Test that a char16_t[] isn't expanded to string when print char-array-as-string is "off"
+ self.eval_and_check_array("u16a", "const char16_t", 10);
+
+ # Test that a char32_t* is expanded to string when print char-array-as-string is "off"
+ self.eval_and_match_string("u32p", r'0x[0-9a-f]+ U\"\\t\\\"hello\\\"\\n\"', r'const char32_t \*')
+
+ # Test that a char32_t[] isn't expanded to string when print char-array-as-string is "off"
+ self.eval_and_check_array("u32a", "const char32_t", 10);
+
+ # Test that -gdb-set can set print char-array-as-string flag
+ self.runCmd("-gdb-set print char-array-as-string on")
+ self.expect("\^done")
+ self.runCmd("-gdb-set print char-array-as-string 1")
+ self.expect("\^done")
+ self.runCmd("-gdb-show print char-array-as-string")
+ self.expect("\^done,value=\"on\"")
+
+ # Test that a char* with escape chars is expanded to string when print char-array-as-string is "on"
+ self.eval_and_match_string("cp", r'0x[0-9a-f]+ \"\\t\\\"hello\\\"\\n\"', r'const char \*')
+
+ # Test that a char[] with escape chars is expanded to string when print char-array-as-string is "on"
+ self.eval_and_match_string("ca", r'\"\\t\\\"hello\\\"\\n\"', r'const char \[10\]')
+
+ # Test that a char16_t* with escape chars is expanded to string when print char-array-as-string is "on"
+ self.eval_and_match_string("u16p", r'0x[0-9a-f]+ u\"\\t\\\"hello\\\"\\n\"', r'const char16_t \*')
+
+ # Test that a char16_t[] with escape chars is expanded to string when print char-array-as-string is "on"
+ self.eval_and_match_string("u16a", r'u\"\\t\\\"hello\\\"\\n\"', r'const char16_t \[10\]')
+
+ # Test that a char32_t* with escape chars is expanded to string when print char-array-as-string is "on"
+ self.eval_and_match_string("u32p", r'0x[0-9a-f]+ U\"\\t\\\"hello\\\"\\n\"', r'const char32_t \*')
+
+ # Test that a char32_t[] with escape chars is expanded to string when print char-array-as-string is "on"
+ self.eval_and_match_string("u32a", r'U\"\\t\\\"hello\\\"\\n\"', r'const char32_t \[10\]')
+
+ # Test russian unicode strings
+ self.eval_and_match_string("u16p_rus", r'0x[0-9a-f]+ u\"\\\\Аламо-сквер\"', r'const char16_t \*')
+ self.eval_and_match_string("u16a_rus", r'u\"\\\\Бейвью\"', r'const char16_t \[8\]')
+ self.eval_and_match_string("u32p_rus", r'0x[0-9a-f]+ U\"\\\\Чайнатаун\"', r'const char32_t \*')
+ self.eval_and_match_string("u32a_rus", r'U\"\\\\Догпатч\"', r'const char32_t \[9\]')
+
+ # Test that -gdb-set print char-array-as-string fails if "on"/"off" isn't specified
+ self.runCmd("-gdb-set print char-array-as-string")
+ self.expect("\^error,msg=\"The request ''print' expects option-name and \"on\" or \"off\"' failed.\"")
+
+ # Test that -gdb-set print char-array-as-string fails when option is unknown
+ self.runCmd("-gdb-set print char-array-as-string unknown")
+ self.expect("\^error,msg=\"The request ''print' expects option-name and \"on\" or \"off\"' failed.\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi working on Windows
+ @expectedFailureGcc("https://llvm.org/bugs/show_bug.cgi?id=23357")
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_gdb_set_show_print_expand_aggregates(self):
+ """Test that 'lldb-mi --interpreter' can expand aggregates everywhere."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to BP_gdb_set_show_print_expand_aggregates
+ line = line_number('main.cpp', '// BP_gdb_set_show_print_expand_aggregates')
+ self.runCmd("-break-insert main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that default print expand-aggregates value is "off"
+ self.runCmd("-gdb-show print expand-aggregates")
+ self.expect("\^done,value=\"off\"")
+
+ # Test that composite type isn't expanded when print expand-aggregates is "off"
+ self.runCmd("-var-create var1 * complx")
+ self.expect("\^done,name=\"var1\",numchild=\"3\",value=\"{\.\.\.}\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"")
+
+ # Test that composite type[] isn't expanded when print expand-aggregates is "off"
+ self.eval_and_check_array("complx_array", "complex_type", 2)
+
+ # Test that a struct with a char first element is not formatted as a string
+ self.runCmd("-var-create - * &nstr")
+ self.expect("\^done,name=\"var\d+\",numchild=\"2\",value=\"0x[0-9a-f]+\",type=\"not_str \*\",thread-id=\"1\",has_more=\"0\"")
+
+ # Test that -gdb-set can set print expand-aggregates flag
+ self.runCmd("-gdb-set print expand-aggregates on")
+ self.expect("\^done")
+ self.runCmd("-gdb-set print expand-aggregates 1")
+ self.expect("\^done")
+ self.runCmd("-gdb-show print expand-aggregates")
+ self.expect("\^done,value=\"on\"")
+
+ # Test that composite type is expanded when print expand-aggregates is "on"
+ self.runCmd("-var-create var3 * complx")
+ self.expect("\^done,name=\"var3\",numchild=\"3\",value=\"{i = 3, inner = {l = 3}, complex_ptr = 0x[0-9a-f]+}\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"")
+
+ # Test that composite type[] is expanded when print expand-aggregates is "on"
+ self.runCmd("-var-create var4 * complx_array")
+ self.expect("\^done,name=\"var4\",numchild=\"2\",value=\"{\[0\] = {i = 4, inner = {l = 4}, complex_ptr = 0x[0-9a-f]+}, \[1\] = {i = 5, inner = {l = 5}, complex_ptr = 0x[0-9a-f]+}}\",type=\"complex_type \[2\]\",thread-id=\"1\",has_more=\"0\"")
+
+ # Test that -gdb-set print expand-aggregates fails if "on"/"off" isn't specified
+ self.runCmd("-gdb-set print expand-aggregates")
+ self.expect("\^error,msg=\"The request ''print' expects option-name and \"on\" or \"off\"' failed.\"")
+
+ # Test that -gdb-set print expand-aggregates fails when option is unknown
+ self.runCmd("-gdb-set print expand-aggregates unknown")
+ self.expect("\^error,msg=\"The request ''print' expects option-name and \"on\" or \"off\"' failed.\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi working on Windows
+ @expectedFailureGcc("https://llvm.org/bugs/show_bug.cgi?id=23357")
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_gdb_set_show_print_aggregate_field_names(self):
+ """Test that 'lldb-mi --interpreter' can expand aggregates everywhere."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to BP_gdb_set_show_print_aggregate_field_names
+ line = line_number('main.cpp', '// BP_gdb_set_show_print_aggregate_field_names')
+ self.runCmd("-break-insert main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that default print aggregatep-field-names value is "on"
+ self.runCmd("-gdb-show print aggregate-field-names")
+ self.expect("\^done,value=\"on\"")
+
+ # Set print expand-aggregates flag to "on"
+ self.runCmd("-gdb-set print expand-aggregates on")
+ self.expect("\^done")
+
+ # Test that composite type is expanded with field name when print aggregate-field-names is "on"
+ self.runCmd("-var-create var1 * complx")
+ self.expect("\^done,name=\"var1\",numchild=\"3\",value=\"{i = 3, inner = {l = 3}, complex_ptr = 0x[0-9a-f]+}\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"")
+
+ # Test that composite type[] is expanded with field name when print aggregate-field-names is "on"
+ self.runCmd("-var-create var2 * complx_array")
+ self.expect("\^done,name=\"var2\",numchild=\"2\",value=\"{\[0\] = {i = 4, inner = {l = 4}, complex_ptr = 0x[0-9a-f]+}, \[1\] = {i = 5, inner = {l = 5}, complex_ptr = 0x[0-9a-f]+}}\",type=\"complex_type \[2\]\",thread-id=\"1\",has_more=\"0\"")
+
+ # Test that -gdb-set can set print aggregate-field-names flag
+ self.runCmd("-gdb-set print aggregate-field-names off")
+ self.expect("\^done")
+ self.runCmd("-gdb-set print aggregate-field-names 0")
+ self.expect("\^done")
+ self.runCmd("-gdb-show print aggregate-field-names")
+ self.expect("\^done,value=\"off\"")
+
+ # Test that composite type is expanded without field name when print aggregate-field-names is "off"
+ self.runCmd("-var-create var3 * complx")
+ self.expect("\^done,name=\"var3\",numchild=\"3\",value=\"{3,\{3\},0x[0-9a-f]+}\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"")
+
+ # Test that composite type[] is expanded without field name when print aggregate-field-names is "off"
+ self.runCmd("-var-create var4 * complx_array")
+ self.expect("\^done,name=\"var4\",numchild=\"2\",value=\"{{4,\{4\},0x[0-9a-f]+},{5,\{5\},0x[0-9a-f]+}}\",type=\"complex_type \[2\]\",thread-id=\"1\",has_more=\"0\"")
+
+ # Test that -gdb-set print aggregate-field-names fails if "on"/"off" isn't specified
+ self.runCmd("-gdb-set print aggregate-field-names")
+ self.expect("\^error,msg=\"The request ''print' expects option-name and \"on\" or \"off\"' failed.\"")
+
+ # Test that -gdb-set print aggregate-field-names fails when option is unknown
+ self.runCmd("-gdb-set print aggregate-field-names unknown")
+ self.expect("\^error,msg=\"The request ''print' expects option-name and \"on\" or \"off\"' failed.\"")
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/variable/TestMiVar.py b/packages/Python/lldbsuite/test/tools/lldb-mi/variable/TestMiVar.py
new file mode 100644
index 000000000000..26f3a9c63bdc
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/variable/TestMiVar.py
@@ -0,0 +1,396 @@
+"""
+Test lldb-mi -var-xxx commands.
+"""
+
+from __future__ import print_function
+
+
+
+import lldbmi_testcase
+from lldbsuite.test.lldbtest import *
+
+class MiVarTestCase(lldbmi_testcase.MiTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_eval(self):
+ """Test that 'lldb-mi --interpreter' works for evaluating."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to program return
+ line = line_number('main.cpp', '// BP_return')
+ self.runCmd("-break-insert main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Print non-existant variable
+ self.runCmd("-var-create var1 * undef")
+ self.expect("\^error,msg=\"error: error: use of undeclared identifier \'undef\'\\\\nerror: 1 errors parsing expression\\\\n\"")
+ self.runCmd("-data-evaluate-expression undef")
+ self.expect("\^error,msg=\"Could not evaluate expression\"")
+
+ # Print global "g_MyVar", modify, delete and create again
+ self.runCmd("-data-evaluate-expression g_MyVar")
+ self.expect("\^done,value=\"3\"")
+ self.runCmd("-var-create var2 * g_MyVar")
+ self.expect("\^done,name=\"var2\",numchild=\"0\",value=\"3\",type=\"int\",thread-id=\"1\",has_more=\"0\"")
+ self.runCmd("-var-evaluate-expression var2")
+ self.expect("\^done,value=\"3\"")
+ self.runCmd("-var-show-attributes var2")
+ self.expect("\^done,status=\"editable\"")
+ self.runCmd("-var-list-children var2")
+ self.expect("\^done,numchild=\"0\",has_more=\"0\"")
+ # Ensure -var-list-children also works with quotes
+ self.runCmd("-var-list-children \"var2\"")
+ self.expect("\^done,numchild=\"0\",has_more=\"0\"")
+ self.runCmd("-data-evaluate-expression \"g_MyVar=30\"")
+ self.expect("\^done,value=\"30\"")
+ self.runCmd("-var-update --all-values var2")
+ #self.expect("\^done,changelist=\[\{name=\"var2\",value=\"30\",in_scope=\"true\",type_changed=\"false\",has_more=\"0\"\}\]") #FIXME -var-update doesn't work
+ self.runCmd("-var-delete var2")
+ self.expect("\^done")
+ self.runCmd("-var-create var2 * g_MyVar")
+ self.expect("\^done,name=\"var2\",numchild=\"0\",value=\"30\",type=\"int\",thread-id=\"1\",has_more=\"0\"")
+
+ # Print static "s_MyVar", modify, delete and create again
+ self.runCmd("-data-evaluate-expression s_MyVar")
+ self.expect("\^done,value=\"30\"")
+ self.runCmd("-var-create var3 * s_MyVar")
+ self.expect("\^done,name=\"var3\",numchild=\"0\",value=\"30\",type=\"int\",thread-id=\"1\",has_more=\"0\"")
+ self.runCmd("-var-evaluate-expression var3")
+ self.expect("\^done,value=\"30\"")
+ self.runCmd("-var-show-attributes var3")
+ self.expect("\^done,status=\"editable\"")
+ self.runCmd("-var-list-children var3")
+ self.expect("\^done,numchild=\"0\",has_more=\"0\"")
+ self.runCmd("-data-evaluate-expression \"s_MyVar=3\"")
+ self.expect("\^done,value=\"3\"")
+ self.runCmd("-var-update --all-values var3")
+ #self.expect("\^done,changelist=\[\{name=\"var3\",value=\"3\",in_scope=\"true\",type_changed=\"false\",has_more=\"0\"\}\]") #FIXME -var-update doesn't work
+ self.runCmd("-var-delete var3")
+ self.expect("\^done")
+ self.runCmd("-var-create var3 * s_MyVar")
+ self.expect("\^done,name=\"var3\",numchild=\"0\",value=\"3\",type=\"int\",thread-id=\"1\",has_more=\"0\"")
+
+ # Print local "b", modify, delete and create again
+ self.runCmd("-data-evaluate-expression b")
+ self.expect("\^done,value=\"20\"")
+ self.runCmd("-var-create var4 * b")
+ self.expect("\^done,name=\"var4\",numchild=\"0\",value=\"20\",type=\"int\",thread-id=\"1\",has_more=\"0\"")
+ self.runCmd("-var-evaluate-expression var4")
+ self.expect("\^done,value=\"20\"")
+ self.runCmd("-var-show-attributes var4")
+ self.expect("\^done,status=\"editable\"")
+ self.runCmd("-var-list-children var4")
+ self.expect("\^done,numchild=\"0\",has_more=\"0\"")
+ self.runCmd("-data-evaluate-expression \"b=2\"")
+ self.expect("\^done,value=\"2\"")
+ self.runCmd("-var-update --all-values var4")
+ #self.expect("\^done,changelist=\[\{name=\"var4\",value=\"2\",in_scope=\"true\",type_changed=\"false\",has_more=\"0\"\}\]") #FIXME -var-update doesn't work
+ self.runCmd("-var-delete var4")
+ self.expect("\^done")
+ self.runCmd("-var-create var4 * b")
+ self.expect("\^done,name=\"var4\",numchild=\"0\",value=\"2\",type=\"int\",thread-id=\"1\",has_more=\"0\"")
+
+ # Print temp "a + b"
+ self.runCmd("-data-evaluate-expression \"a + b\"")
+ self.expect("\^done,value=\"12\"")
+ self.runCmd("-var-create var5 * \"a + b\"")
+ self.expect("\^done,name=\"var5\",numchild=\"0\",value=\"12\",type=\"int\",thread-id=\"1\",has_more=\"0\"")
+ self.runCmd("-var-evaluate-expression var5")
+ self.expect("\^done,value=\"12\"")
+ self.runCmd("-var-show-attributes var5")
+ self.expect("\^done,status=\"editable\"") #FIXME editable or not?
+ self.runCmd("-var-list-children var5")
+ self.expect("\^done,numchild=\"0\",has_more=\"0\"")
+
+ # Print argument "argv[0]"
+ self.runCmd("-data-evaluate-expression \"argv[0]\"")
+ self.expect("\^done,value=\"0x[0-9a-f]+ \\\\\\\".*?%s\\\\\\\"\"" % self.myexe)
+ self.runCmd("-var-create var6 * \"argv[0]\"")
+ self.expect("\^done,name=\"var6\",numchild=\"1\",value=\"0x[0-9a-f]+ \\\\\\\".*?%s\\\\\\\"\",type=\"const char \*\",thread-id=\"1\",has_more=\"0\"" % self.myexe)
+ self.runCmd("-var-evaluate-expression var6")
+ self.expect("\^done,value=\"0x[0-9a-f]+ \\\\\\\".*?%s\\\\\\\"\"" % self.myexe)
+ self.runCmd("-var-show-attributes var6")
+ self.expect("\^done,status=\"editable\"")
+ self.runCmd("-var-list-children --all-values var6")
+ # FIXME: The name below is not correct. It should be "var.*argv[0]".
+ self.expect("\^done,numchild=\"1\",children=\[child=\{name=\"var6\.\*\$[0-9]+\",exp=\"\*\$[0-9]+\",numchild=\"0\",type=\"const char\",thread-id=\"4294967295\",value=\"47 '/'\",has_more=\"0\"\}\],has_more=\"0\"") #FIXME -var-list-children shows invalid thread-id
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots
+ def test_lldbmi_var_update(self):
+ """Test that 'lldb-mi --interpreter' works for -var-update."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to BP_var_update_test_init
+ line = line_number('main.cpp', '// BP_var_update_test_init')
+ self.runCmd("-break-insert main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Setup variables
+ self.runCmd("-var-create var_l * l")
+ self.expect("\^done,name=\"var_l\",numchild=\"0\",value=\"1\",type=\"long\",thread-id=\"1\",has_more=\"0\"")
+ self.runCmd("-var-create var_complx * complx")
+ self.expect("\^done,name=\"var_complx\",numchild=\"3\",value=\"\{\.\.\.\}\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"")
+ self.runCmd("-var-create var_complx_array * complx_array")
+ self.expect("\^done,name=\"var_complx_array\",numchild=\"2\",value=\"\[2\]\",type=\"complex_type \[2\]\",thread-id=\"1\",has_more=\"0\"")
+
+ # Go to BP_var_update_test_l
+ line = line_number('main.cpp', '// BP_var_update_test_l')
+ self.runCmd("-break-insert main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"2\"")
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that var_l was updated
+ self.runCmd("-var-update --all-values var_l")
+ self.expect("\^done,changelist=\[\{name=\"var_l\",value=\"0\",in_scope=\"true\",type_changed=\"false\",has_more=\"0\"\}\]")
+
+ # Go to BP_var_update_test_complx
+ line = line_number('main.cpp', '// BP_var_update_test_complx')
+ self.runCmd("-break-insert main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"3\"")
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that var_complx was updated
+ self.runCmd("-var-update --all-values var_complx")
+ self.expect("\^done,changelist=\[\{name=\"var_complx\",value=\"\{\.\.\.\}\",in_scope=\"true\",type_changed=\"false\",has_more=\"0\"\}\]")
+
+ # Go to BP_var_update_test_complx_array
+ line = line_number('main.cpp', '// BP_var_update_test_complx_array')
+ self.runCmd("-break-insert main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"4\"")
+ self.runCmd("-exec-continue")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test that var_complex_array was updated
+ self.runCmd("-var-update --all-values var_complx_array")
+ self.expect("\^done,changelist=\[\{name=\"var_complx_array\",value=\"\[2\]\",in_scope=\"true\",type_changed=\"false\",has_more=\"0\"\}\]")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ def test_lldbmi_var_create_register(self):
+ """Test that 'lldb-mi --interpreter' works for -var-create $regname."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to main
+ self.runCmd("-break-insert -f main")
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Find name of register 0
+ self.runCmd("-data-list-register-names 0")
+ self.expect("\^done,register-names=\[\".+?\"\]")
+ register_name = self.child.after.split("\"")[1]
+
+ # Create variable for register 0
+ # Note that message is different in Darwin and Linux:
+ # Darwin: "^done,name=\"var_reg\",numchild=\"0\",value=\"0x[0-9a-f]+\",type=\"unsigned long\",thread-id=\"1\",has_more=\"0\"
+ # Linux: "^done,name=\"var_reg\",numchild=\"0\",value=\"0x[0-9a-f]+\",type=\"unsigned int\",thread-id=\"1\",has_more=\"0\"
+ self.runCmd("-var-create var_reg * $%s" % register_name)
+ self.expect("\^done,name=\"var_reg\",numchild=\"0\",value=\"0x[0-9a-f]+\",type=\"unsigned (long|int)\",thread-id=\"1\",has_more=\"0\"")
+
+ # Assign value to variable
+ self.runCmd("-var-assign var_reg \"6\"")
+ #FIXME: the output has different format for 32bit and 64bit values
+ self.expect("\^done,value=\"0x0*?6\"")
+
+ # Assert register 0 updated
+ self.runCmd("-data-list-register-values d 0")
+ self.expect("\^done,register-values=\[{number=\"0\",value=\"6\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi tests working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots
+ def test_lldbmi_var_list_children(self):
+ """Test that 'lldb-mi --interpreter' works for -var-list-children."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to BP_var_list_children_test
+ line = line_number('main.cpp', '// BP_var_list_children_test')
+ self.runCmd("-break-insert main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Create variable
+ self.runCmd("-var-create var_complx * complx")
+ self.expect("\^done,name=\"var_complx\",numchild=\"3\",value=\"\{\.\.\.\}\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"")
+ self.runCmd("-var-create var_complx_array * complx_array")
+ self.expect("\^done,name=\"var_complx_array\",numchild=\"2\",value=\"\[2\]\",type=\"complex_type \[2\]\",thread-id=\"1\",has_more=\"0\"")
+ self.runCmd("-var-create var_pcomplx * pcomplx")
+ self.expect("\^done,name=\"var_pcomplx\",numchild=\"2\",value=\"\{\.\.\.\}\",type=\"pcomplex_type\",thread-id=\"1\",has_more=\"0\"")
+
+ # Test that -var-evaluate-expression can evaluate the children of created varobj
+ self.runCmd("-var-list-children var_complx")
+ self.runCmd("-var-evaluate-expression var_complx.i")
+ self.expect("\^done,value=\"3\"")
+ self.runCmd("-var-list-children var_complx_array")
+ self.runCmd("-var-evaluate-expression var_complx_array.[0]")
+ self.expect("\^done,value=\"\{...\}\"")
+ self.runCmd("-var-list-children var_pcomplx")
+ self.runCmd("-var-evaluate-expression var_pcomplx.complex_type")
+ self.expect("\^done,value=\"\{...\}\"")
+
+ # Test that -var-list-children lists empty children if range is empty
+ # (and that print-values is optional)
+ self.runCmd("-var-list-children var_complx 0 0")
+ self.expect("\^done,numchild=\"0\",has_more=\"1\"")
+ self.runCmd("-var-list-children var_complx 99 0")
+ self.expect("\^done,numchild=\"0\",has_more=\"1\"")
+ self.runCmd("-var-list-children var_complx 99 3")
+ self.expect("\^done,numchild=\"0\",has_more=\"0\"")
+
+ # Test that -var-list-children lists all children with their values
+ # (and that from and to are optional)
+ self.runCmd("-var-list-children --all-values var_complx")
+ self.expect("\^done,numchild=\"3\",children=\[child=\{name=\"var_complx\.i\",exp=\"i\",numchild=\"0\",type=\"int\",thread-id=\"1\",value=\"3\",has_more=\"0\"\},child=\{name=\"var_complx\.inner\",exp=\"inner\",numchild=\"1\",type=\"complex_type::\(anonymous struct\)\",thread-id=\"1\",value=\"\{\.\.\.\}\",has_more=\"0\"\},child=\{name=\"var_complx\.complex_ptr\",exp=\"complex_ptr\",numchild=\"3\",type=\"complex_type \*\",thread-id=\"1\",value=\"0x[0-9a-f]+\",has_more=\"0\"\}\],has_more=\"0\"")
+ self.runCmd("-var-list-children --simple-values var_complx_array")
+ self.expect("\^done,numchild=\"2\",children=\[child=\{name=\"var_complx_array\.\[0\]\",exp=\"\[0\]\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"\},child=\{name=\"var_complx_array\.\[1\]\",exp=\"\[1\]\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"0\"")
+ self.runCmd("-var-list-children 0 var_pcomplx")
+ self.expect("\^done,numchild=\"2\",children=\[child=\{name=\"var_pcomplx\.complex_type\",exp=\"complex_type\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"\},child={name=\"var_pcomplx\.complx\",exp=\"complx\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"0\"")
+
+ # Test that -var-list-children lists children without values
+ self.runCmd("-var-list-children 0 var_complx 0 1")
+ self.expect("\^done,numchild=\"1\",children=\[child=\{name=\"var_complx\.i\",exp=\"i\",numchild=\"0\",type=\"int\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"1\"")
+ self.runCmd("-var-list-children --no-values var_complx 0 1")
+ self.expect("\^done,numchild=\"1\",children=\[child=\{name=\"var_complx\.i\",exp=\"i\",numchild=\"0\",type=\"int\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"1\"")
+ self.runCmd("-var-list-children --no-values var_complx_array 0 1")
+ self.expect("\^done,numchild=\"1\",children=\[child=\{name=\"var_complx_array\.\[0\]\",exp=\"\[0\]\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"1\"")
+ self.runCmd("-var-list-children --no-values var_pcomplx 0 1")
+ self.expect("\^done,numchild=\"1\",children=\[child=\{name=\"var_pcomplx\.complex_type\",exp=\"complex_type\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"1\"")
+
+ # Test that -var-list-children lists children with all values
+ self.runCmd("-var-list-children 1 var_complx 1 2")
+ self.expect("\^done,numchild=\"1\",children=\[child=\{name=\"var_complx\.inner\",exp=\"inner\",numchild=\"1\",type=\"complex_type::\(anonymous struct\)\",thread-id=\"1\",value=\"\{\.\.\.\}\",has_more=\"0\"\}\],has_more=\"1\"")
+ self.runCmd("-var-list-children --all-values var_complx 1 2")
+ self.expect("\^done,numchild=\"1\",children=\[child=\{name=\"var_complx\.inner\",exp=\"inner\",numchild=\"1\",type=\"complex_type::\(anonymous struct\)\",thread-id=\"1\",value=\"\{\.\.\.\}\",has_more=\"0\"\}\],has_more=\"1\"")
+ self.runCmd("-var-list-children --all-values var_complx_array 1 2")
+ self.expect("\^done,numchild=\"1\",children=\[child=\{name=\"var_complx_array\.\[1\]\",exp=\"\[1\]\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",value=\"\{\.\.\.\}\",has_more=\"0\"\}\],has_more=\"0\"")
+ self.runCmd("-var-list-children --all-values var_pcomplx 1 2")
+ self.expect("\^done,numchild=\"1\",children=\[child={name=\"var_pcomplx\.complx\",exp=\"complx\",numchild=\"3\",type=\"complex_type\",thread-id=\"1\",value=\"\{\.\.\.\}\",has_more=\"0\"\}\],has_more=\"0\"")
+
+ # Test that -var-list-children lists children with simple values
+ self.runCmd("-var-list-children 2 var_complx 2 4")
+ self.expect("\^done,numchild=\"1\",children=\[child=\{name=\"var_complx\.complex_ptr\",exp=\"complex_ptr\",numchild=\"3\",type=\"complex_type \*\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"0\"")
+ self.runCmd("-var-list-children --simple-values var_complx 2 4")
+ self.expect("\^done,numchild=\"1\",children=\[child=\{name=\"var_complx\.complex_ptr\",exp=\"complex_ptr\",numchild=\"3\",type=\"complex_type \*\",thread-id=\"1\",has_more=\"0\"\}\],has_more=\"0\"")
+ self.runCmd("-var-list-children --simple-values var_complx_array 2 4")
+ self.expect("\^done,numchild=\"0\",has_more=\"0\"")
+ self.runCmd("-var-list-children --simple-values var_pcomplx 2 4")
+ self.expect("\^done,numchild=\"0\",has_more=\"0\"")
+
+ # Test that an invalid from is handled
+ # FIXME: -1 is treated as unsigned int
+ self.runCmd("-var-list-children 0 var_complx -1 0")
+ #self.expect("\^error,msg=\"Command 'var-list-children'\. Variable children range invalid\"")
+
+ # Test that an invalid to is handled
+ # FIXME: -1 is treated as unsigned int
+ self.runCmd("-var-list-children 0 var_complx 0 -1")
+ #self.expect("\^error,msg=\"Command 'var-list-children'\. Variable children range invalid\"")
+
+ # Test that a missing low-frame or high-frame is handled
+ self.runCmd("-var-list-children 0 var_complx 0")
+ self.expect("\^error,msg=\"Command 'var-list-children'. Variable children range invalid\"")
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots
+ def test_lldbmi_var_create_for_stl_types(self):
+ """Test that 'lldb-mi --interpreter' print summary for STL types."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to BP_gdb_set_show_print_char_array_as_string_test
+ line = line_number('main.cpp', '// BP_cpp_stl_types_test')
+ self.runCmd("-break-insert main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Test for std::string
+ self.runCmd("-var-create - * std_string")
+ self.expect('\^done,name="var\d+",numchild="[0-9]+",value="\\\\"hello\\\\"",type="std::[\S]*?string",thread-id="1",has_more="0"')
+
+ @skipIfWindows #llvm.org/pr24452: Get lldb-mi working on Windows
+ @skipIfFreeBSD # llvm.org/pr22411: Failure presumably due to known thread races
+ @skipIfLinux # llvm.org/pr22841: lldb-mi tests fail on all Linux buildbots
+ def test_lldbmi_var_create_for_unnamed_objects(self):
+ """Test that 'lldb-mi --interpreter' can expand unnamed structures and unions."""
+
+ self.spawnLldbMi(args = None)
+
+ # Load executable
+ self.runCmd("-file-exec-and-symbols %s" % self.myexe)
+ self.expect("\^done")
+
+ # Run to breakpoint
+ line = line_number('main.cpp', '// BP_unnamed_objects_test')
+ self.runCmd("-break-insert main.cpp:%d" % line)
+ self.expect("\^done,bkpt={number=\"1\"")
+ self.runCmd("-exec-run")
+ self.expect("\^running")
+ self.expect("\*stopped,reason=\"breakpoint-hit\"")
+
+ # Evaluate struct_with_unions type and its children
+ self.runCmd("-var-create v0 * swu")
+ self.expect('\^done,name="v0",numchild="2",value="\{\.\.\.\}",type="struct_with_unions",thread-id="1",has_more="0"')
+
+ self.runCmd("-var-list-children v0")
+
+ # inspect the first unnamed union
+ self.runCmd("-var-list-children v0.$0")
+ self.runCmd("-var-evaluate-expression v0.$0.u_i")
+ self.expect('\^done,value="1"')
+
+ # inspect the second unnamed union
+ self.runCmd("-var-list-children v0.$1")
+ self.runCmd("-var-evaluate-expression v0.$1.u1")
+ self.expect('\^done,value="-1"')
+ # inspect unnamed structure
+ self.runCmd("-var-list-children v0.$1.$1")
+ self.runCmd("-var-evaluate-expression v0.$1.$1.s1")
+ self.expect('\^done,value="-1"')
+
diff --git a/packages/Python/lldbsuite/test/tools/lldb-mi/variable/main.cpp b/packages/Python/lldbsuite/test/tools/lldb-mi/variable/main.cpp
new file mode 100644
index 000000000000..8c79539d4d85
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-mi/variable/main.cpp
@@ -0,0 +1,152 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <cstdint>
+#include <string>
+
+struct complex_type
+{
+ int i;
+ struct { long l; } inner;
+ complex_type *complex_ptr;
+};
+
+struct pcomplex_type : complex_type
+{
+ pcomplex_type(const complex_type &complx_base, const complex_type &complx_member)
+ : complex_type(complx_base), complx(complx_member) { }
+ complex_type complx;
+ static int si;
+};
+
+int pcomplex_type::si;
+
+struct struct_with_unions
+{
+ struct_with_unions(): u_i(1), u1(-1) {}
+ union
+ {
+ int u_i;
+ int u_j;
+ };
+ union
+ {
+ int u1;
+ struct
+ {
+ short s1;
+ short s2;
+ };
+ };
+};
+
+void
+var_update_test(void)
+{
+ long l = 1;
+ complex_type complx = { 3, { 3L }, &complx };
+ complex_type complx_array[2] = { { 4, { 4L }, &complx_array[1] }, { 5, { 5 }, &complx_array[0] } };
+ // BP_var_update_test_init
+
+ l = 0;
+ // BP_var_update_test_l
+
+ complx.inner.l = 2;
+ // BP_var_update_test_complx
+
+ complx_array[1].inner.l = 4;
+ // BP_var_update_test_complx_array
+}
+
+void
+var_list_children_test(void)
+{
+ complex_type complx = { 3, { 3L }, &complx };
+ complex_type complx_array[2] = { { 4, { 4L }, &complx_array[1] }, { 5, { 5 }, &complx_array[0] } };
+ pcomplex_type pcomplx({ 6, { 6L }, &pcomplx}, { 7, { 7L }, &pcomplx});
+
+ // BP_var_list_children_test
+}
+
+void
+gdb_set_show_print_char_array_as_string_test(void)
+{
+ const char *cp = "\t\"hello\"\n";
+ const char ca[] = "\t\"hello\"\n";
+ const char16_t *u16p = u"\t\"hello\"\n";
+ const char16_t u16a[] = u"\t\"hello\"\n";
+ const char32_t *u32p = U"\t\"hello\"\n";
+ const char32_t u32a[] = U"\t\"hello\"\n";
+
+ const char16_t* u16p_rus = u"\\Аламо-сквер";
+ const char16_t u16a_rus[] = u"\\Бейвью";
+ const char32_t* u32p_rus = U"\\Чайнатаун";
+ const char32_t u32a_rus[] = U"\\Догпатч";
+
+ // BP_gdb_set_show_print_char_array_as_string_test
+}
+
+void
+cpp_stl_types_test(void)
+{
+ std::string std_string = "hello";
+ // BP_cpp_stl_types_test
+}
+
+void
+unnamed_objects_test(void)
+{
+ struct_with_unions swu;
+ // BP_unnamed_objects_test
+}
+
+struct not_str
+{
+ not_str(char _c, int _f)
+ : c(_c), f(_f) { }
+ char c;
+ int f;
+};
+
+void
+gdb_set_show_print_expand_aggregates(void)
+{
+ complex_type complx = { 3, { 3L }, &complx };
+ complex_type complx_array[2] = { { 4, { 4L }, &complx_array[1] }, { 5, { 5 }, &complx_array[0] } };
+ not_str nstr('a', 0);
+
+ // BP_gdb_set_show_print_expand_aggregates
+}
+
+void
+gdb_set_show_print_aggregate_field_names(void)
+{
+ complex_type complx = { 3, { 3L }, &complx };
+ complex_type complx_array[2] = { { 4, { 4L }, &complx_array[1] }, { 5, { 5 }, &complx_array[0] } };
+
+ // BP_gdb_set_show_print_aggregate_field_names
+}
+
+int g_MyVar = 3;
+static int s_MyVar = 4;
+
+int
+main(int argc, char const *argv[])
+{
+ int a = 10, b = 20;
+ s_MyVar = a + b;
+ var_update_test();
+ var_list_children_test();
+ gdb_set_show_print_char_array_as_string_test();
+ cpp_stl_types_test();
+ unnamed_objects_test();
+ gdb_set_show_print_expand_aggregates();
+ gdb_set_show_print_aggregate_field_names();
+ return 0; // BP_return
+}
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/Makefile b/packages/Python/lldbsuite/test/tools/lldb-server/Makefile
new file mode 100644
index 000000000000..6ae4e6624eef
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../make
+
+CFLAGS_EXTRAS += -D__STDC_LIMIT_MACROS -D__STDC_FORMAT_MACROS
+ENABLE_THREADS := YES
+CXX_SOURCES := main.cpp
+MAKE_DSYM :=NO
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/TestGDBRemoteMemoryRead.py b/packages/Python/lldbsuite/test/tools/lldb-server/TestGDBRemoteMemoryRead.py
new file mode 100644
index 000000000000..7b974e548a58
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/TestGDBRemoteMemoryRead.py
@@ -0,0 +1,41 @@
+"""
+Tests the binary ($x) and hex ($m) memory read packets of the remote stub
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+import binascii
+
+
+class MemoryReadTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @skipUnlessPlatform(getDarwinOSTriples()+["linux"])
+ def test_memory_read(self):
+ self.build()
+ exe = os.path.join (os.getcwd(), "a.out")
+
+ target = self.dbg.CreateTarget(exe)
+ lldbutil.run_break_set_by_symbol(self, "main")
+
+ process = target.LaunchSimple (None, None, self.get_process_working_directory())
+ self.assertTrue(process, PROCESS_IS_VALID)
+ self.assertEqual(process.GetState(), lldb.eStateStopped, "Process is stopped")
+
+ pc = process.GetSelectedThread().GetSelectedFrame().GetPC()
+ for size in [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]:
+ error = lldb.SBError()
+ memory = process.ReadMemory(pc, size, error)
+ self.assertTrue(error.Success())
+ self.match("process plugin packet send x%x,%x" % (pc, size), ["response:", memory])
+ self.match("process plugin packet send m%x,%x" % (pc, size), ["response:", binascii.hexlify(memory)])
+
+ process.Continue()
+ self.assertEqual(process.GetState(), lldb.eStateExited, "Process exited")
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAttach.py b/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAttach.py
new file mode 100644
index 000000000000..ca96a9a837b9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAttach.py
@@ -0,0 +1,60 @@
+from __future__ import print_function
+
+
+
+import gdbremote_testcase
+import lldbgdbserverutils
+
+from lldbsuite.test.lldbtest import *
+
+class TestGdbRemoteAttach(gdbremote_testcase.GdbRemoteTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def attach_with_vAttach(self):
+ # Start the inferior, start the debug monitor, nothing is attached yet.
+ procs = self.prep_debug_monitor_and_inferior(inferior_args=["sleep:60"])
+ self.assertIsNotNone(procs)
+
+ # Make sure the target process has been launched.
+ inferior = procs.get("inferior")
+ self.assertIsNotNone(inferior)
+ self.assertTrue(inferior.pid > 0)
+ self.assertTrue(lldbgdbserverutils.process_is_running(inferior.pid, True))
+
+ # Add attach packets.
+ self.test_sequence.add_log_lines([
+ # Do the attach.
+ "read packet: $vAttach;{:x}#00".format(inferior.pid),
+ # Expect a stop notification from the attach.
+ { "direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})[^#]*#[0-9a-fA-F]{2}$", "capture":{1:"stop_signal_hex"} },
+ ], True)
+ self.add_process_info_collection_packets()
+
+ # Run the stream
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Gather process info response
+ process_info = self.parse_process_info_response(context)
+ self.assertIsNotNone(process_info)
+
+ # Ensure the process id matches what we expected.
+ pid_text = process_info.get('pid', None)
+ self.assertIsNotNone(pid_text)
+ reported_pid = int(pid_text, base=16)
+ self.assertEqual(reported_pid, inferior.pid)
+
+ @debugserver_test
+ def test_attach_with_vAttach_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_attach_manually()
+ self.attach_with_vAttach()
+
+ @llgs_test
+ def test_attach_with_vAttach_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_attach_manually()
+ self.attach_with_vAttach()
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAuxvSupport.py b/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAuxvSupport.py
new file mode 100644
index 000000000000..1ce5779e7897
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteAuxvSupport.py
@@ -0,0 +1,201 @@
+from __future__ import print_function
+
+
+
+import gdbremote_testcase
+from lldbsuite.test.lldbtest import *
+
+class TestGdbRemoteAuxvSupport(gdbremote_testcase.GdbRemoteTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ AUXV_SUPPORT_FEATURE_NAME = "qXfer:auxv:read"
+
+ def has_auxv_support(self):
+ inferior_args = ["message:main entered", "sleep:5"]
+ procs = self.prep_debug_monitor_and_inferior(inferior_args=inferior_args)
+
+ # Don't do anything until we match the launched inferior main entry output.
+ # Then immediately interrupt the process.
+ # This prevents auxv data being asked for before it's ready and leaves
+ # us in a stopped state.
+ self.test_sequence.add_log_lines([
+ # Start the inferior...
+ "read packet: $c#63",
+ # ... match output....
+ { "type":"output_match", "regex":r"^message:main entered\r\n$" },
+ ], True)
+ # ... then interrupt.
+ self.add_interrupt_packets()
+ self.add_qSupported_packets()
+
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ features = self.parse_qSupported_response(context)
+ return self.AUXV_SUPPORT_FEATURE_NAME in features and features[self.AUXV_SUPPORT_FEATURE_NAME] == "+"
+
+ def get_raw_auxv_data(self):
+ # Start up llgs and inferior, and check for auxv support.
+ if not self.has_auxv_support():
+ self.skipTest("auxv data not supported")
+
+ # Grab pointer size for target. We'll assume that is equivalent to an unsigned long on the target.
+ # Auxv is specified in terms of pairs of unsigned longs.
+ self.reset_test_sequence()
+ self.add_process_info_collection_packets()
+
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ proc_info = self.parse_process_info_response(context)
+ self.assertIsNotNone(proc_info)
+ self.assertTrue("ptrsize" in proc_info)
+ word_size = int(proc_info["ptrsize"])
+
+ OFFSET = 0
+ LENGTH = 0x400
+
+ # Grab the auxv data.
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines([
+ "read packet: $qXfer:auxv:read::{:x},{:x}:#00".format(OFFSET, LENGTH),
+ {"direction":"send", "regex":re.compile(r"^\$([^E])(.*)#[0-9a-fA-F]{2}$", re.MULTILINE|re.DOTALL), "capture":{1:"response_type", 2:"content_raw"} }
+ ], True)
+
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Ensure we end up with all auxv data in one packet.
+ # FIXME don't assume it all comes back in one packet.
+ self.assertEqual(context.get("response_type"), "l")
+
+ # Decode binary data.
+ content_raw = context.get("content_raw")
+ self.assertIsNotNone(content_raw)
+ return (word_size, self.decode_gdbremote_binary(content_raw))
+
+ def supports_auxv(self):
+ # When non-auxv platforms support llgs, skip the test on platforms
+ # that don't support auxv.
+ self.assertTrue(self.has_auxv_support())
+
+ #
+ # We skip the "supports_auxv" test on debugserver. The rest of the tests
+ # appropriately skip the auxv tests if the support flag is not present
+ # in the qSupported response, so the debugserver test bits are still there
+ # in case debugserver code one day does have auxv support and thus those
+ # tests don't get skipped.
+ #
+
+ @llgs_test
+ def test_supports_auxv_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.supports_auxv()
+
+ def auxv_data_is_correct_size(self):
+ (word_size, auxv_data) = self.get_raw_auxv_data()
+ self.assertIsNotNone(auxv_data)
+
+ # Ensure auxv data is a multiple of 2*word_size (there should be two unsigned long fields per auxv entry).
+ self.assertEqual(len(auxv_data) % (2*word_size), 0)
+ # print("auxv contains {} entries".format(len(auxv_data) / (2*word_size)))
+
+ @debugserver_test
+ def test_auxv_data_is_correct_size_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.auxv_data_is_correct_size()
+
+ @llgs_test
+ def test_auxv_data_is_correct_size_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.auxv_data_is_correct_size()
+
+ def auxv_keys_look_valid(self):
+ (word_size, auxv_data) = self.get_raw_auxv_data()
+ self.assertIsNotNone(auxv_data)
+
+ # Grab endian.
+ self.reset_test_sequence()
+ self.add_process_info_collection_packets()
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ process_info = self.parse_process_info_response(context)
+ self.assertIsNotNone(process_info)
+ endian = process_info.get("endian")
+ self.assertIsNotNone(endian)
+
+ auxv_dict = self.build_auxv_dict(endian, word_size, auxv_data)
+ self.assertIsNotNone(auxv_dict)
+
+ # Verify keys look reasonable.
+ for auxv_key in auxv_dict:
+ self.assertTrue(auxv_key >= 1)
+ self.assertTrue(auxv_key <= 1000)
+ # print("auxv dict: {}".format(auxv_dict))
+
+ @debugserver_test
+ def test_auxv_keys_look_valid_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.auxv_keys_look_valid()
+
+ @llgs_test
+ def test_auxv_keys_look_valid_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.auxv_keys_look_valid()
+
+ def auxv_chunked_reads_work(self):
+ # Verify that multiple smaller offset,length reads of auxv data
+ # return the same data as a single larger read.
+
+ # Grab the auxv data with a single large read here.
+ (word_size, auxv_data) = self.get_raw_auxv_data()
+ self.assertIsNotNone(auxv_data)
+
+ # Grab endian.
+ self.reset_test_sequence()
+ self.add_process_info_collection_packets()
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ process_info = self.parse_process_info_response(context)
+ self.assertIsNotNone(process_info)
+ endian = process_info.get("endian")
+ self.assertIsNotNone(endian)
+
+ auxv_dict = self.build_auxv_dict(endian, word_size, auxv_data)
+ self.assertIsNotNone(auxv_dict)
+
+ iterated_auxv_data = self.read_binary_data_in_chunks("qXfer:auxv:read::", 2*word_size)
+ self.assertIsNotNone(iterated_auxv_data)
+
+ auxv_dict_iterated = self.build_auxv_dict(endian, word_size, iterated_auxv_data)
+ self.assertIsNotNone(auxv_dict_iterated)
+
+ # Verify both types of data collection returned same content.
+ self.assertEqual(auxv_dict_iterated, auxv_dict)
+
+ @debugserver_test
+ def test_auxv_chunked_reads_work_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.auxv_chunked_reads_work()
+
+ @llgs_test
+ def test_auxv_chunked_reads_work_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.auxv_chunked_reads_work()
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteExpeditedRegisters.py b/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteExpeditedRegisters.py
new file mode 100644
index 000000000000..6535ce40475d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteExpeditedRegisters.py
@@ -0,0 +1,144 @@
+from __future__ import print_function
+
+
+
+import gdbremote_testcase
+from lldbsuite.test.lldbtest import *
+
+class TestGdbRemoteExpeditedRegisters(gdbremote_testcase.GdbRemoteTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def gather_expedited_registers(self):
+ # Setup the stub and set the gdb remote command stream.
+ procs = self.prep_debug_monitor_and_inferior(inferior_args=["sleep:2"])
+ self.test_sequence.add_log_lines([
+ # Start up the inferior.
+ "read packet: $c#63",
+ # Immediately tell it to stop. We want to see what it reports.
+ "read packet: {}".format(chr(3)),
+ {"direction":"send", "regex":r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", "capture":{1:"stop_result", 2:"key_vals_text"} },
+ ], True)
+
+ # Run the gdb remote command stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Pull out expedited registers.
+ key_vals_text = context.get("key_vals_text")
+ self.assertIsNotNone(key_vals_text)
+
+ expedited_registers = self.extract_registers_from_stop_notification(key_vals_text)
+ self.assertIsNotNone(expedited_registers)
+
+ return expedited_registers
+
+ def stop_notification_contains_generic_register(self, generic_register_name):
+ # Generate a stop reply, parse out expedited registers from stop notification.
+ expedited_registers = self.gather_expedited_registers()
+ self.assertIsNotNone(expedited_registers)
+ self.assertTrue(len(expedited_registers) > 0)
+
+ # Gather target register infos.
+ reg_infos = self.gather_register_infos()
+
+ # Find the generic register.
+ reg_info = self.find_generic_register_with_name(reg_infos, generic_register_name)
+ self.assertIsNotNone(reg_info)
+
+ # Ensure the expedited registers contained it.
+ self.assertTrue(reg_info["lldb_register_index"] in expedited_registers)
+ # print("{} reg_info:{}".format(generic_register_name, reg_info))
+
+ def stop_notification_contains_any_registers(self):
+ # Generate a stop reply, parse out expedited registers from stop notification.
+ expedited_registers = self.gather_expedited_registers()
+ # Verify we have at least one expedited register.
+ self.assertTrue(len(expedited_registers) > 0)
+
+ @debugserver_test
+ def test_stop_notification_contains_any_registers_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.stop_notification_contains_any_registers()
+
+ @llgs_test
+ def test_stop_notification_contains_any_registers_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.stop_notification_contains_any_registers()
+
+ def stop_notification_contains_no_duplicate_registers(self):
+ # Generate a stop reply, parse out expedited registers from stop notification.
+ expedited_registers = self.gather_expedited_registers()
+ # Verify no expedited register was specified multiple times.
+ for (reg_num, value) in list(expedited_registers.items()):
+ if (type(value) == list) and (len(value) > 0):
+ self.fail("expedited register number {} specified more than once ({} times)".format(reg_num, len(value)))
+
+ @debugserver_test
+ def test_stop_notification_contains_no_duplicate_registers_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.stop_notification_contains_no_duplicate_registers()
+
+ @llgs_test
+ def test_stop_notification_contains_no_duplicate_registers_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.stop_notification_contains_no_duplicate_registers()
+
+ def stop_notification_contains_pc_register(self):
+ self.stop_notification_contains_generic_register("pc")
+
+ @debugserver_test
+ def test_stop_notification_contains_pc_register_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.stop_notification_contains_pc_register()
+
+ @llgs_test
+ def test_stop_notification_contains_pc_register_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.stop_notification_contains_pc_register()
+
+ def stop_notification_contains_fp_register(self):
+ self.stop_notification_contains_generic_register("fp")
+
+ @debugserver_test
+ def test_stop_notification_contains_fp_register_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.stop_notification_contains_fp_register()
+
+ @llgs_test
+ def test_stop_notification_contains_fp_register_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.stop_notification_contains_fp_register()
+
+ def stop_notification_contains_sp_register(self):
+ self.stop_notification_contains_generic_register("sp")
+
+ @debugserver_test
+ def test_stop_notification_contains_sp_register_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.stop_notification_contains_sp_register()
+
+ @llgs_test
+ def test_stop_notification_contains_sp_register_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.stop_notification_contains_sp_register()
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteKill.py b/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteKill.py
new file mode 100644
index 000000000000..b253254c78ed
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteKill.py
@@ -0,0 +1,53 @@
+from __future__ import print_function
+
+
+
+import gdbremote_testcase
+import lldbgdbserverutils
+
+from lldbsuite.test.lldbtest import *
+
+class TestGdbRemoteKill(gdbremote_testcase.GdbRemoteTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def attach_commandline_kill_after_initial_stop(self):
+ procs = self.prep_debug_monitor_and_inferior()
+ self.test_sequence.add_log_lines([
+ "read packet: $k#6b",
+ {"direction":"send", "regex":r"^\$X[0-9a-fA-F]+([^#]*)#[0-9A-Fa-f]{2}" },
+ ], True)
+
+ if self.stub_sends_two_stop_notifications_on_kill:
+ # Add an expectation for a second X result for stubs that send two of these.
+ self.test_sequence.add_log_lines([
+ {"direction":"send", "regex":r"^\$X[0-9a-fA-F]+([^#]*)#[0-9A-Fa-f]{2}" },
+ ], True)
+
+ self.expect_gdbremote_sequence()
+
+ # Wait a moment for completed and now-detached inferior process to clear.
+ time.sleep(1)
+
+ if not lldb.remote_platform:
+ # Process should be dead now. Reap results.
+ poll_result = procs["inferior"].poll()
+ self.assertIsNotNone(poll_result)
+
+ # Where possible, verify at the system level that the process is not running.
+ self.assertFalse(lldbgdbserverutils.process_is_running(procs["inferior"].pid, False))
+
+ @debugserver_test
+ def test_attach_commandline_kill_after_initial_stop_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_attach()
+ self.attach_commandline_kill_after_initial_stop()
+
+ @llgs_test
+ def test_attach_commandline_kill_after_initial_stop_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_attach()
+ self.attach_commandline_kill_after_initial_stop()
+
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteProcessInfo.py b/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteProcessInfo.py
new file mode 100644
index 000000000000..a11167b87c25
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteProcessInfo.py
@@ -0,0 +1,179 @@
+from __future__ import print_function
+
+
+
+import gdbremote_testcase
+import lldbgdbserverutils
+import sys
+
+from lldbsuite.test.lldbtest import *
+
+class TestGdbRemoteProcessInfo(gdbremote_testcase.GdbRemoteTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def qProcessInfo_returns_running_process(self):
+ procs = self.prep_debug_monitor_and_inferior()
+ self.add_process_info_collection_packets()
+
+ # Run the stream
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Gather process info response
+ process_info = self.parse_process_info_response(context)
+ self.assertIsNotNone(process_info)
+
+ # Ensure the process id looks reasonable.
+ pid_text = process_info.get("pid")
+ self.assertIsNotNone(pid_text)
+ pid = int(pid_text, base=16)
+ self.assertNotEqual(0, pid)
+
+ # If possible, verify that the process is running.
+ self.assertTrue(lldbgdbserverutils.process_is_running(pid, True))
+
+ @debugserver_test
+ def test_qProcessInfo_returns_running_process_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.qProcessInfo_returns_running_process()
+
+ @llgs_test
+ def test_qProcessInfo_returns_running_process_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.qProcessInfo_returns_running_process()
+
+ def attach_commandline_qProcessInfo_reports_correct_pid(self):
+ procs = self.prep_debug_monitor_and_inferior()
+ self.assertIsNotNone(procs)
+ self.add_process_info_collection_packets()
+
+ # Run the stream
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Gather process info response
+ process_info = self.parse_process_info_response(context)
+ self.assertIsNotNone(process_info)
+
+ # Ensure the process id matches what we expected.
+ pid_text = process_info.get('pid', None)
+ self.assertIsNotNone(pid_text)
+ reported_pid = int(pid_text, base=16)
+ self.assertEqual(reported_pid, procs["inferior"].pid)
+
+ @debugserver_test
+ def test_attach_commandline_qProcessInfo_reports_correct_pid_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_attach()
+ self.attach_commandline_qProcessInfo_reports_correct_pid()
+
+ @llgs_test
+ def test_attach_commandline_qProcessInfo_reports_correct_pid_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_attach()
+ self.attach_commandline_qProcessInfo_reports_correct_pid()
+
+ def qProcessInfo_reports_valid_endian(self):
+ procs = self.prep_debug_monitor_and_inferior()
+ self.add_process_info_collection_packets()
+
+ # Run the stream
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Gather process info response
+ process_info = self.parse_process_info_response(context)
+ self.assertIsNotNone(process_info)
+
+ # Ensure the process id looks reasonable.
+ endian = process_info.get("endian")
+ self.assertIsNotNone(endian)
+ self.assertTrue(endian in ["little", "big", "pdp"])
+
+ @debugserver_test
+ def test_qProcessInfo_reports_valid_endian_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.qProcessInfo_reports_valid_endian()
+
+ @llgs_test
+ def test_qProcessInfo_reports_valid_endian_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.qProcessInfo_reports_valid_endian()
+
+ def qProcessInfo_contains_keys(self, expected_key_set):
+ procs = self.prep_debug_monitor_and_inferior()
+ self.add_process_info_collection_packets()
+
+ # Run the stream
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Gather process info response
+ process_info = self.parse_process_info_response(context)
+ self.assertIsNotNone(process_info)
+
+ # Ensure the expected keys are present and non-None within the process info.
+ missing_key_set = set()
+ for expected_key in expected_key_set:
+ if expected_key not in process_info:
+ missing_key_set.add(expected_key)
+
+ self.assertEqual(missing_key_set, set(), "the listed keys are missing in the qProcessInfo result")
+
+ def qProcessInfo_does_not_contain_keys(self, absent_key_set):
+ procs = self.prep_debug_monitor_and_inferior()
+ self.add_process_info_collection_packets()
+
+ # Run the stream
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Gather process info response
+ process_info = self.parse_process_info_response(context)
+ self.assertIsNotNone(process_info)
+
+ # Ensure the unexpected keys are not present
+ unexpected_key_set = set()
+ for unexpected_key in absent_key_set:
+ if unexpected_key in process_info:
+ unexpected_key_set.add(unexpected_key)
+
+ self.assertEqual(unexpected_key_set, set(), "the listed keys were present but unexpected in qProcessInfo result")
+
+ @skipUnlessDarwin
+ @debugserver_test
+ def test_qProcessInfo_contains_cputype_cpusubtype_debugserver_darwin(self):
+ self.init_debugserver_test()
+ self.build()
+ self.qProcessInfo_contains_keys(set(['cputype', 'cpusubtype']))
+
+ @skipUnlessPlatform(["linux"])
+ @llgs_test
+ def test_qProcessInfo_contains_triple_llgs_linux(self):
+ self.init_llgs_test()
+ self.build()
+ self.qProcessInfo_contains_keys(set(['triple']))
+
+ @skipUnlessDarwin
+ @debugserver_test
+ def test_qProcessInfo_does_not_contain_triple_debugserver_darwin(self):
+ self.init_debugserver_test()
+ self.build()
+ # We don't expect to see triple on darwin. If we do, we'll prefer triple
+ # to cputype/cpusubtype and skip some darwin-based ProcessGDBRemote ArchSpec setup
+ # for the remote Host and Process.
+ self.qProcessInfo_does_not_contain_keys(set(['triple']))
+
+ @skipUnlessPlatform(["linux"])
+ @llgs_test
+ def test_qProcessInfo_does_not_contain_cputype_cpusubtype_llgs_linux(self):
+ self.init_llgs_test()
+ self.build()
+ self.qProcessInfo_does_not_contain_keys(set(['cputype', 'cpusubtype']))
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteRegisterState.py b/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteRegisterState.py
new file mode 100644
index 000000000000..a36b4ae781ad
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteRegisterState.py
@@ -0,0 +1,126 @@
+from __future__ import print_function
+
+
+
+import gdbremote_testcase
+from lldbsuite.test.lldbtest import *
+
+class TestGdbRemoteRegisterState(gdbremote_testcase.GdbRemoteTestCaseBase):
+ """Test QSaveRegisterState/QRestoreRegisterState support."""
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def grp_register_save_restore_works(self, with_suffix):
+ # Start up the process, use thread suffix, grab main thread id.
+ inferior_args = ["message:main entered", "sleep:5"]
+ procs = self.prep_debug_monitor_and_inferior(inferior_args=inferior_args)
+
+ self.add_process_info_collection_packets()
+ self.add_register_info_collection_packets()
+ if with_suffix:
+ self.add_thread_suffix_request_packets()
+ self.add_threadinfo_collection_packets()
+ self.test_sequence.add_log_lines([
+ # Start the inferior...
+ "read packet: $c#63",
+ # ... match output....
+ { "type":"output_match", "regex":r"^message:main entered\r\n$" },
+ ], True)
+ # ... then interrupt.
+ self.add_interrupt_packets()
+
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Gather process info.
+ process_info = self.parse_process_info_response(context)
+ endian = process_info.get("endian")
+ self.assertIsNotNone(endian)
+
+ # Gather register info.
+ reg_infos = self.parse_register_info_packets(context)
+ self.assertIsNotNone(reg_infos)
+ self.add_lldb_register_index(reg_infos)
+
+ # Pull out the register infos that we think we can bit flip successfully.
+ gpr_reg_infos = [reg_info for reg_info in reg_infos if self.is_bit_flippable_register(reg_info)]
+ self.assertTrue(len(gpr_reg_infos) > 0)
+
+ # Gather thread info.
+ if with_suffix:
+ threads = self.parse_threadinfo_packets(context)
+ self.assertIsNotNone(threads)
+ thread_id = threads[0]
+ self.assertIsNotNone(thread_id)
+ # print("Running on thread: 0x{:x}".format(thread_id))
+ else:
+ thread_id = None
+
+ # Save register state.
+ self.reset_test_sequence()
+ self.add_QSaveRegisterState_packets(thread_id)
+
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ (success, state_id) = self.parse_QSaveRegisterState_response(context)
+ self.assertTrue(success)
+ self.assertIsNotNone(state_id)
+ # print("saved register state id: {}".format(state_id))
+
+ # Remember initial register values.
+ initial_reg_values = self.read_register_values(gpr_reg_infos, endian, thread_id=thread_id)
+ # print("initial_reg_values: {}".format(initial_reg_values))
+
+ # Flip gpr register values.
+ (successful_writes, failed_writes) = self.flip_all_bits_in_each_register_value(gpr_reg_infos, endian, thread_id=thread_id)
+ # print("successful writes: {}, failed writes: {}".format(successful_writes, failed_writes))
+ self.assertTrue(successful_writes > 0)
+
+ flipped_reg_values = self.read_register_values(gpr_reg_infos, endian, thread_id=thread_id)
+ # print("flipped_reg_values: {}".format(flipped_reg_values))
+
+ # Restore register values.
+ self.reset_test_sequence()
+ self.add_QRestoreRegisterState_packets(state_id, thread_id)
+
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Verify registers match initial register values.
+ final_reg_values = self.read_register_values(gpr_reg_infos, endian, thread_id=thread_id)
+ # print("final_reg_values: {}".format(final_reg_values))
+ self.assertIsNotNone(final_reg_values)
+ self.assertEqual(final_reg_values, initial_reg_values)
+
+ @debugserver_test
+ def test_grp_register_save_restore_works_with_suffix_debugserver(self):
+ USE_THREAD_SUFFIX = True
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.grp_register_save_restore_works(USE_THREAD_SUFFIX)
+
+ @llgs_test
+ def test_grp_register_save_restore_works_with_suffix_llgs(self):
+ USE_THREAD_SUFFIX = True
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.grp_register_save_restore_works(USE_THREAD_SUFFIX)
+
+ @debugserver_test
+ def test_grp_register_save_restore_works_no_suffix_debugserver(self):
+ USE_THREAD_SUFFIX = False
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.grp_register_save_restore_works(USE_THREAD_SUFFIX)
+
+ @llgs_test
+ def test_grp_register_save_restore_works_no_suffix_llgs(self):
+ USE_THREAD_SUFFIX = False
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.grp_register_save_restore_works(USE_THREAD_SUFFIX)
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteSingleStep.py b/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteSingleStep.py
new file mode 100644
index 000000000000..3b008249f557
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteSingleStep.py
@@ -0,0 +1,25 @@
+from __future__ import print_function
+
+
+
+import gdbremote_testcase
+from lldbsuite.test.lldbtest import *
+
+class TestGdbRemoteSingleStep(gdbremote_testcase.GdbRemoteTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @debugserver_test
+ def test_single_step_only_steps_one_instruction_with_s_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.single_step_only_steps_one_instruction(use_Hc_packet=True, step_instruction="s")
+
+ @llgs_test
+ @expectedFailureAndroid(bugnumber="llvm.com/pr24739", archs=["arm", "aarch64"])
+ def test_single_step_only_steps_one_instruction_with_s_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.single_step_only_steps_one_instruction(use_Hc_packet=True, step_instruction="s")
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteThreadsInStopReply.py b/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteThreadsInStopReply.py
new file mode 100644
index 000000000000..a7938795b9bf
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemoteThreadsInStopReply.py
@@ -0,0 +1,164 @@
+from __future__ import print_function
+
+
+
+import gdbremote_testcase
+from lldbsuite.test.lldbtest import *
+
+class TestGdbRemoteThreadsInStopReply(gdbremote_testcase.GdbRemoteTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ ENABLE_THREADS_IN_STOP_REPLY_ENTRIES = [
+ "read packet: $QListThreadsInStopReply#21",
+ "send packet: $OK#00",
+ ]
+
+ def gather_stop_reply_threads(self, post_startup_log_lines, thread_count):
+ # Set up the inferior args.
+ inferior_args=[]
+ for i in range(thread_count - 1):
+ inferior_args.append("thread:new")
+ inferior_args.append("sleep:10")
+ procs = self.prep_debug_monitor_and_inferior(inferior_args=inferior_args)
+
+ # Assumes test_sequence has anything added needed to setup the initial state.
+ # (Like optionally enabling QThreadsInStopReply.)
+ if post_startup_log_lines:
+ self.test_sequence.add_log_lines(post_startup_log_lines, True)
+ self.test_sequence.add_log_lines([
+ "read packet: $c#63"
+ ], True)
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Give threads time to start up, then break.
+ time.sleep(1)
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines([
+ "read packet: {}".format(chr(3)),
+ {"direction":"send", "regex":r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", "capture":{1:"stop_result", 2:"key_vals_text"} },
+ ], True)
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Wait until all threads have started.
+ threads = self.wait_for_thread_count(thread_count, timeout_seconds=3)
+ self.assertIsNotNone(threads)
+ self.assertEqual(len(threads), thread_count)
+
+ # Run, then stop the process, grab the stop reply content.
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines([
+ "read packet: $c#63",
+ "read packet: {}".format(chr(3)),
+ {"direction":"send", "regex":r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", "capture":{1:"stop_result", 2:"key_vals_text"} },
+ ], True)
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Parse the stop reply contents.
+ key_vals_text = context.get("key_vals_text")
+ self.assertIsNotNone(key_vals_text)
+ kv_dict = self.parse_key_val_dict(key_vals_text)
+ self.assertIsNotNone(kv_dict)
+
+ # Pull out threads from stop response.
+ stop_reply_threads_text = kv_dict.get("threads")
+ if stop_reply_threads_text:
+ return [int(thread_id, 16) for thread_id in stop_reply_threads_text.split(",")]
+ else:
+ return []
+
+ def QListThreadsInStopReply_supported(self):
+ procs = self.prep_debug_monitor_and_inferior()
+ self.test_sequence.add_log_lines(self.ENABLE_THREADS_IN_STOP_REPLY_ENTRIES, True)
+
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ @debugserver_test
+ def test_QListThreadsInStopReply_supported_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.QListThreadsInStopReply_supported()
+
+ @llgs_test
+ def test_QListThreadsInStopReply_supported_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.QListThreadsInStopReply_supported()
+
+ def stop_reply_reports_multiple_threads(self, thread_count):
+ # Gather threads from stop notification when QThreadsInStopReply is enabled.
+ stop_reply_threads = self.gather_stop_reply_threads(self.ENABLE_THREADS_IN_STOP_REPLY_ENTRIES, thread_count)
+ self.assertEqual(len(stop_reply_threads), thread_count)
+
+ @debugserver_test
+ def test_stop_reply_reports_multiple_threads_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.stop_reply_reports_multiple_threads(5)
+
+ @llgs_test
+ def test_stop_reply_reports_multiple_threads_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.stop_reply_reports_multiple_threads(5)
+
+ def no_QListThreadsInStopReply_supplies_no_threads(self, thread_count):
+ # Gather threads from stop notification when QThreadsInStopReply is not enabled.
+ stop_reply_threads = self.gather_stop_reply_threads(None, thread_count)
+ self.assertEqual(len(stop_reply_threads), 0)
+
+ @debugserver_test
+ def test_no_QListThreadsInStopReply_supplies_no_threads_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.no_QListThreadsInStopReply_supplies_no_threads(5)
+
+ @llgs_test
+ def test_no_QListThreadsInStopReply_supplies_no_threads_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.no_QListThreadsInStopReply_supplies_no_threads(5)
+
+ def stop_reply_reports_correct_threads(self, thread_count):
+ # Gather threads from stop notification when QThreadsInStopReply is enabled.
+ stop_reply_threads = self.gather_stop_reply_threads(self.ENABLE_THREADS_IN_STOP_REPLY_ENTRIES, thread_count)
+ self.assertEqual(len(stop_reply_threads), thread_count)
+
+ # Gather threads from q{f,s}ThreadInfo.
+ self.reset_test_sequence()
+ self.add_threadinfo_collection_packets()
+
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ threads = self.parse_threadinfo_packets(context)
+ self.assertIsNotNone(threads)
+ self.assertEqual(len(threads), thread_count)
+
+ # Ensure each thread in q{f,s}ThreadInfo appears in stop reply threads
+ for tid in threads:
+ self.assertTrue(tid in stop_reply_threads)
+
+ @debugserver_test
+ def test_stop_reply_reports_correct_threads_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.stop_reply_reports_correct_threads(5)
+
+ @llgs_test
+ def test_stop_reply_reports_correct_threads_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.stop_reply_reports_correct_threads(5)
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_qThreadStopInfo.py b/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_qThreadStopInfo.py
new file mode 100644
index 000000000000..cce484451de4
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_qThreadStopInfo.py
@@ -0,0 +1,150 @@
+from __future__ import print_function
+
+
+
+import sys
+
+import unittest2
+import gdbremote_testcase
+from lldbsuite.test.lldbtest import *
+
+class TestGdbRemote_qThreadStopInfo(gdbremote_testcase.GdbRemoteTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+ THREAD_COUNT = 5
+
+ def gather_stop_replies_via_qThreadStopInfo(self, thread_count):
+ # Set up the inferior args.
+ inferior_args=[]
+ for i in range(thread_count - 1):
+ inferior_args.append("thread:new")
+ inferior_args.append("sleep:10")
+ procs = self.prep_debug_monitor_and_inferior(inferior_args=inferior_args)
+
+ # Assumes test_sequence has anything added needed to setup the initial state.
+ # (Like optionally enabling QThreadsInStopReply.)
+ self.test_sequence.add_log_lines([
+ "read packet: $c#63"
+ ], True)
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Give threads time to start up, then break.
+ time.sleep(1)
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines([
+ "read packet: {}".format(chr(3)),
+ {"direction":"send", "regex":r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", "capture":{1:"stop_result", 2:"key_vals_text"} },
+ ], True)
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Wait until all threads have started.
+ threads = self.wait_for_thread_count(thread_count, timeout_seconds=3)
+ self.assertIsNotNone(threads)
+ self.assertEqual(len(threads), thread_count)
+
+ # Grab stop reply for each thread via qThreadStopInfo{tid:hex}.
+ stop_replies = {}
+ thread_dicts = {}
+ for thread in threads:
+ # Run the qThreadStopInfo command.
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines([
+ "read packet: $qThreadStopInfo{:x}#00".format(thread),
+ {"direction":"send", "regex":r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", "capture":{1:"stop_result", 2:"key_vals_text"} },
+ ], True)
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Parse stop reply contents.
+ key_vals_text = context.get("key_vals_text")
+ self.assertIsNotNone(key_vals_text)
+ kv_dict = self.parse_key_val_dict(key_vals_text)
+ self.assertIsNotNone(kv_dict)
+
+ # Verify there is a thread and that it matches the expected thread id.
+ kv_thread = kv_dict.get("thread")
+ self.assertIsNotNone(kv_thread)
+ kv_thread_id = int(kv_thread, 16)
+ self.assertEqual(kv_thread_id, thread)
+
+ # Grab the stop id reported.
+ stop_result_text = context.get("stop_result")
+ self.assertIsNotNone(stop_result_text)
+ stop_replies[kv_thread_id] = int(stop_result_text, 16)
+
+ # Hang on to the key-val dictionary for the thread.
+ thread_dicts[kv_thread_id] = kv_dict
+
+ return (stop_replies, thread_dicts)
+
+ def qThreadStopInfo_works_for_multiple_threads(self, thread_count):
+ (stop_replies, _) = self.gather_stop_replies_via_qThreadStopInfo(thread_count)
+ self.assertEqual(len(stop_replies), thread_count)
+
+ @debugserver_test
+ def test_qThreadStopInfo_works_for_multiple_threads_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.qThreadStopInfo_works_for_multiple_threads(self.THREAD_COUNT)
+
+ @llgs_test
+ def test_qThreadStopInfo_works_for_multiple_threads_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.qThreadStopInfo_works_for_multiple_threads(self.THREAD_COUNT)
+
+ def qThreadStopInfo_only_reports_one_thread_stop_reason_during_interrupt(self, thread_count):
+ (stop_replies, _) = self.gather_stop_replies_via_qThreadStopInfo(thread_count)
+ self.assertIsNotNone(stop_replies)
+
+ no_stop_reason_count = sum(1 for stop_reason in list(stop_replies.values()) if stop_reason == 0)
+ with_stop_reason_count = sum(1 for stop_reason in list(stop_replies.values()) if stop_reason != 0)
+
+ # All but one thread should report no stop reason.
+ self.assertEqual(no_stop_reason_count, thread_count - 1)
+
+ # Only one thread should should indicate a stop reason.
+ self.assertEqual(with_stop_reason_count, 1)
+
+ @debugserver_test
+ def test_qThreadStopInfo_only_reports_one_thread_stop_reason_during_interrupt_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.qThreadStopInfo_only_reports_one_thread_stop_reason_during_interrupt(self.THREAD_COUNT)
+
+ @llgs_test
+ def test_qThreadStopInfo_only_reports_one_thread_stop_reason_during_interrupt_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.qThreadStopInfo_only_reports_one_thread_stop_reason_during_interrupt(self.THREAD_COUNT)
+
+ def qThreadStopInfo_has_valid_thread_names(self, thread_count, expected_thread_name):
+ (_, thread_dicts) = self.gather_stop_replies_via_qThreadStopInfo(thread_count)
+ self.assertIsNotNone(thread_dicts)
+
+ for thread_dict in list(thread_dicts.values()):
+ name = thread_dict.get("name")
+ self.assertIsNotNone(name)
+ self.assertEqual(name, expected_thread_name)
+
+ @unittest2.skip("MacOSX doesn't have a default thread name")
+ @debugserver_test
+ def test_qThreadStopInfo_has_valid_thread_names_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.qThreadStopInfo_has_valid_thread_names(self.THREAD_COUNT, "a.out")
+
+ @skipUnlessPlatform(["linux"]) # test requires OS with set, equal thread names by default.
+ @llgs_test
+ def test_qThreadStopInfo_has_valid_thread_names_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.qThreadStopInfo_has_valid_thread_names(self.THREAD_COUNT, "a.out")
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_vCont.py b/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_vCont.py
new file mode 100644
index 000000000000..579e99d6d774
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/TestGdbRemote_vCont.py
@@ -0,0 +1,116 @@
+from __future__ import print_function
+
+
+
+import gdbremote_testcase
+from lldbsuite.test.lldbtest import *
+
+class TestGdbRemote_vCont(gdbremote_testcase.GdbRemoteTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def vCont_supports_mode(self, mode, inferior_args=None):
+ # Setup the stub and set the gdb remote command stream.
+ procs = self.prep_debug_monitor_and_inferior(inferior_args=inferior_args)
+ self.add_vCont_query_packets()
+
+ # Run the gdb remote command stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Pull out supported modes.
+ supported_vCont_modes = self.parse_vCont_query_response(context)
+ self.assertIsNotNone(supported_vCont_modes)
+
+ # Verify we support the given mode.
+ self.assertTrue(mode in supported_vCont_modes)
+
+ def vCont_supports_c(self):
+ self.vCont_supports_mode("c")
+
+ def vCont_supports_C(self):
+ self.vCont_supports_mode("C")
+
+ def vCont_supports_s(self):
+ self.vCont_supports_mode("s")
+
+ def vCont_supports_S(self):
+ self.vCont_supports_mode("S")
+
+ @debugserver_test
+ def test_vCont_supports_c_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.vCont_supports_c()
+
+ @llgs_test
+ def test_vCont_supports_c_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.vCont_supports_c()
+
+ @debugserver_test
+ def test_vCont_supports_C_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.vCont_supports_C()
+
+ @llgs_test
+ def test_vCont_supports_C_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.vCont_supports_C()
+
+ @debugserver_test
+ def test_vCont_supports_s_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.vCont_supports_s()
+
+ @llgs_test
+ def test_vCont_supports_s_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.vCont_supports_s()
+
+ @debugserver_test
+ def test_vCont_supports_S_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.vCont_supports_S()
+
+ @llgs_test
+ def test_vCont_supports_S_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.vCont_supports_S()
+
+ @debugserver_test
+ def test_single_step_only_steps_one_instruction_with_Hc_vCont_s_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.single_step_only_steps_one_instruction(use_Hc_packet=True, step_instruction="vCont;s")
+
+ @llgs_test
+ @expectedFailureAndroid(bugnumber="llvm.com/pr24739", archs=["arm", "aarch64"])
+ def test_single_step_only_steps_one_instruction_with_Hc_vCont_s_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.single_step_only_steps_one_instruction(use_Hc_packet=True, step_instruction="vCont;s")
+
+ @debugserver_test
+ def test_single_step_only_steps_one_instruction_with_vCont_s_thread_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.single_step_only_steps_one_instruction(use_Hc_packet=False, step_instruction="vCont;s:{thread}")
+
+ @llgs_test
+ @expectedFailureAndroid(bugnumber="llvm.com/pr24739", archs=["arm", "aarch64"])
+ def test_single_step_only_steps_one_instruction_with_vCont_s_thread_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.single_step_only_steps_one_instruction(use_Hc_packet=False, step_instruction="vCont;s:{thread}")
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/TestLldbGdbServer.py b/packages/Python/lldbsuite/test/tools/lldb-server/TestLldbGdbServer.py
new file mode 100644
index 000000000000..aec040c50569
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/TestLldbGdbServer.py
@@ -0,0 +1,1473 @@
+"""
+Test case for testing the gdbremote protocol.
+
+Tests run against debugserver and lldb-server (llgs).
+lldb-server tests run where the lldb-server exe is
+available.
+
+This class will be broken into smaller test case classes by
+gdb remote packet functional areas. For now it contains
+the initial set of tests implemented.
+"""
+
+from __future__ import print_function
+
+
+
+import unittest2
+import gdbremote_testcase
+import lldbgdbserverutils
+import platform
+import signal
+from lldbsuite.test.lldbtest import *
+
+class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ @debugserver_test
+ def test_exe_starts_debugserver(self):
+ self.init_debugserver_test()
+ server = self.connect_to_debug_monitor()
+
+ @llgs_test
+ def test_exe_starts_llgs(self):
+ self.init_llgs_test()
+ server = self.connect_to_debug_monitor()
+
+ def start_no_ack_mode(self):
+ server = self.connect_to_debug_monitor()
+ self.assertIsNotNone(server)
+
+ self.add_no_ack_remote_stream()
+ self.expect_gdbremote_sequence()
+
+ @debugserver_test
+ def test_start_no_ack_mode_debugserver(self):
+ self.init_debugserver_test()
+ self.start_no_ack_mode()
+
+ @llgs_test
+ def test_start_no_ack_mode_llgs(self):
+ self.init_llgs_test()
+ self.start_no_ack_mode()
+
+ def thread_suffix_supported(self):
+ server = self.connect_to_debug_monitor()
+ self.assertIsNotNone(server)
+
+ self.add_no_ack_remote_stream()
+ self.test_sequence.add_log_lines(
+ ["lldb-server < 26> read packet: $QThreadSuffixSupported#e4",
+ "lldb-server < 6> send packet: $OK#9a"],
+ True)
+
+ self.expect_gdbremote_sequence()
+
+ @debugserver_test
+ def test_thread_suffix_supported_debugserver(self):
+ self.init_debugserver_test()
+ self.thread_suffix_supported()
+
+ @llgs_test
+ def test_thread_suffix_supported_llgs(self):
+ self.init_llgs_test()
+ self.thread_suffix_supported()
+
+ def list_threads_in_stop_reply_supported(self):
+ server = self.connect_to_debug_monitor()
+ self.assertIsNotNone(server)
+
+ self.add_no_ack_remote_stream()
+ self.test_sequence.add_log_lines(
+ ["lldb-server < 27> read packet: $QListThreadsInStopReply#21",
+ "lldb-server < 6> send packet: $OK#9a"],
+ True)
+ self.expect_gdbremote_sequence()
+
+ @debugserver_test
+ def test_list_threads_in_stop_reply_supported_debugserver(self):
+ self.init_debugserver_test()
+ self.list_threads_in_stop_reply_supported()
+
+ @llgs_test
+ def test_list_threads_in_stop_reply_supported_llgs(self):
+ self.init_llgs_test()
+ self.list_threads_in_stop_reply_supported()
+
+ def install_and_create_launch_args(self):
+ exe_path = os.path.abspath('a.out')
+ if not lldb.remote_platform:
+ return [exe_path]
+ remote_path = lldbutil.append_to_process_working_directory(os.path.basename(exe_path))
+ remote_file_spec = lldb.SBFileSpec(remote_path, False)
+ err = lldb.remote_platform.Install(lldb.SBFileSpec(exe_path, True), remote_file_spec)
+ if err.Fail():
+ raise Exception("remote_platform.Install('%s', '%s') failed: %s" % (exe_path, remote_path, err))
+ return [remote_path]
+
+ def start_inferior(self):
+ launch_args = self.install_and_create_launch_args()
+
+ server = self.connect_to_debug_monitor()
+ self.assertIsNotNone(server)
+
+ self.add_no_ack_remote_stream()
+ self.test_sequence.add_log_lines(
+ ["read packet: %s" % lldbgdbserverutils.build_gdbremote_A_packet(launch_args),
+ "send packet: $OK#9a"],
+ True)
+ self.expect_gdbremote_sequence()
+
+ @debugserver_test
+ def test_start_inferior_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.start_inferior()
+
+ @llgs_test
+ def test_start_inferior_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.start_inferior()
+
+ def inferior_exit_0(self):
+ launch_args = self.install_and_create_launch_args()
+
+ server = self.connect_to_debug_monitor()
+ self.assertIsNotNone(server)
+
+ self.add_no_ack_remote_stream()
+ self.add_verified_launch_packets(launch_args)
+ self.test_sequence.add_log_lines(
+ ["read packet: $vCont;c#a8",
+ "send packet: $W00#00"],
+ True)
+
+ self.expect_gdbremote_sequence()
+
+ @debugserver_test
+ def test_inferior_exit_0_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.inferior_exit_0()
+
+ @llgs_test
+ def test_inferior_exit_0_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.inferior_exit_0()
+
+ def inferior_exit_42(self):
+ launch_args = self.install_and_create_launch_args()
+
+ server = self.connect_to_debug_monitor()
+ self.assertIsNotNone(server)
+
+ RETVAL = 42
+
+ # build launch args
+ launch_args += ["retval:%d" % RETVAL]
+
+ self.add_no_ack_remote_stream()
+ self.add_verified_launch_packets(launch_args)
+ self.test_sequence.add_log_lines(
+ ["read packet: $vCont;c#a8",
+ "send packet: $W{0:02x}#00".format(RETVAL)],
+ True)
+
+ self.expect_gdbremote_sequence()
+
+ @debugserver_test
+ def test_inferior_exit_42_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.inferior_exit_42()
+
+ @llgs_test
+ def test_inferior_exit_42_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.inferior_exit_42()
+
+ def c_packet_works(self):
+ launch_args = self.install_and_create_launch_args()
+
+ server = self.connect_to_debug_monitor()
+ self.assertIsNotNone(server)
+
+ self.add_no_ack_remote_stream()
+ self.add_verified_launch_packets(launch_args)
+ self.test_sequence.add_log_lines(
+ ["read packet: $c#63",
+ "send packet: $W00#00"],
+ True)
+
+ self.expect_gdbremote_sequence()
+
+ @debugserver_test
+ def test_c_packet_works_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.c_packet_works()
+
+ @llgs_test
+ def test_c_packet_works_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.c_packet_works()
+
+ def inferior_print_exit(self):
+ launch_args = self.install_and_create_launch_args()
+
+ server = self.connect_to_debug_monitor()
+ self.assertIsNotNone(server)
+
+ # build launch args
+ launch_args += ["hello, world"]
+
+ self.add_no_ack_remote_stream()
+ self.add_verified_launch_packets(launch_args)
+ self.test_sequence.add_log_lines(
+ ["read packet: $vCont;c#a8",
+ {"type":"output_match", "regex":r"^hello, world\r\n$" },
+ "send packet: $W00#00"],
+ True)
+
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ @debugserver_test
+ def test_inferior_print_exit_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.inferior_print_exit()
+
+ @llgs_test
+ def test_inferior_print_exit_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.inferior_print_exit()
+
+ def first_launch_stop_reply_thread_matches_first_qC(self):
+ launch_args = self.install_and_create_launch_args()
+
+ server = self.connect_to_debug_monitor()
+ self.assertIsNotNone(server)
+
+ # build launch args
+ launch_args += ["hello, world"]
+
+ self.add_no_ack_remote_stream()
+ self.add_verified_launch_packets(launch_args)
+ self.test_sequence.add_log_lines(
+ ["read packet: $qC#00",
+ { "direction":"send", "regex":r"^\$QC([0-9a-fA-F]+)#", "capture":{1:"thread_id"} },
+ "read packet: $?#00",
+ { "direction":"send", "regex":r"^\$T[0-9a-fA-F]{2}thread:([0-9a-fA-F]+)", "expect_captures":{1:"thread_id"} }],
+ True)
+ self.expect_gdbremote_sequence()
+
+ @debugserver_test
+ def test_first_launch_stop_reply_thread_matches_first_qC_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.first_launch_stop_reply_thread_matches_first_qC()
+
+ @llgs_test
+ def test_first_launch_stop_reply_thread_matches_first_qC_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.first_launch_stop_reply_thread_matches_first_qC()
+
+ def attach_commandline_continue_app_exits(self):
+ procs = self.prep_debug_monitor_and_inferior()
+ self.test_sequence.add_log_lines(
+ ["read packet: $vCont;c#a8",
+ "send packet: $W00#00"],
+ True)
+ self.expect_gdbremote_sequence()
+
+ # Wait a moment for completed and now-detached inferior process to clear.
+ time.sleep(1)
+
+ if not lldb.remote_platform:
+ # Process should be dead now. Reap results.
+ poll_result = procs["inferior"].poll()
+ self.assertIsNotNone(poll_result)
+
+ # Where possible, verify at the system level that the process is not running.
+ self.assertFalse(lldbgdbserverutils.process_is_running(procs["inferior"].pid, False))
+
+ @debugserver_test
+ def test_attach_commandline_continue_app_exits_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_attach()
+ self.attach_commandline_continue_app_exits()
+
+ @llgs_test
+ def test_attach_commandline_continue_app_exits_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_attach()
+ self.attach_commandline_continue_app_exits()
+
+ def qRegisterInfo_returns_one_valid_result(self):
+ launch_args = self.install_and_create_launch_args()
+
+ server = self.connect_to_debug_monitor()
+ self.assertIsNotNone(server)
+
+ # Build the expected protocol stream
+ self.add_no_ack_remote_stream()
+ self.add_verified_launch_packets(launch_args)
+ self.test_sequence.add_log_lines(
+ ["read packet: $qRegisterInfo0#00",
+ { "direction":"send", "regex":r"^\$(.+);#[0-9A-Fa-f]{2}", "capture":{1:"reginfo_0"} }],
+ True)
+
+ # Run the stream
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ reg_info_packet = context.get("reginfo_0")
+ self.assertIsNotNone(reg_info_packet)
+ self.assert_valid_reg_info(lldbgdbserverutils.parse_reg_info_response(reg_info_packet))
+
+ @debugserver_test
+ @expectedFailureDarwin("llvm.org/pr25486")
+ def test_qRegisterInfo_returns_one_valid_result_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.qRegisterInfo_returns_one_valid_result()
+
+ @llgs_test
+ def test_qRegisterInfo_returns_one_valid_result_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.qRegisterInfo_returns_one_valid_result()
+
+ def qRegisterInfo_returns_all_valid_results(self):
+ launch_args = self.install_and_create_launch_args()
+
+ server = self.connect_to_debug_monitor()
+ self.assertIsNotNone(server)
+
+ # Build the expected protocol stream.
+ self.add_no_ack_remote_stream()
+ self.add_verified_launch_packets(launch_args)
+ self.add_register_info_collection_packets()
+
+ # Run the stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Validate that each register info returned validates.
+ for reg_info in self.parse_register_info_packets(context):
+ self.assert_valid_reg_info(reg_info)
+
+ @debugserver_test
+ @expectedFailureDarwin("llvm.org/pr25486")
+ def test_qRegisterInfo_returns_all_valid_results_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.qRegisterInfo_returns_all_valid_results()
+
+ @llgs_test
+ def test_qRegisterInfo_returns_all_valid_results_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.qRegisterInfo_returns_all_valid_results()
+
+ def qRegisterInfo_contains_required_generics(self):
+ launch_args = self.install_and_create_launch_args()
+
+ server = self.connect_to_debug_monitor()
+ self.assertIsNotNone(server)
+
+ # Build the expected protocol stream
+ self.add_no_ack_remote_stream()
+ self.add_verified_launch_packets(launch_args)
+ self.add_register_info_collection_packets()
+
+ # Run the packet stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Gather register info entries.
+ reg_infos = self.parse_register_info_packets(context)
+
+ # Collect all generic registers found.
+ generic_regs = { reg_info['generic']:1 for reg_info in reg_infos if 'generic' in reg_info }
+
+ # Ensure we have a program counter register.
+ self.assertTrue('pc' in generic_regs)
+
+ # Ensure we have a frame pointer register.
+ self.assertTrue('fp' in generic_regs)
+
+ # Ensure we have a stack pointer register.
+ self.assertTrue('sp' in generic_regs)
+
+ # Ensure we have a flags register.
+ self.assertTrue('flags' in generic_regs)
+
+ @debugserver_test
+ def test_qRegisterInfo_contains_required_generics_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.qRegisterInfo_contains_required_generics()
+
+ @llgs_test
+ def test_qRegisterInfo_contains_required_generics_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.qRegisterInfo_contains_required_generics()
+
+ def qRegisterInfo_contains_at_least_one_register_set(self):
+ launch_args = self.install_and_create_launch_args()
+
+ server = self.connect_to_debug_monitor()
+ self.assertIsNotNone(server)
+
+ # Build the expected protocol stream
+ self.add_no_ack_remote_stream()
+ self.add_verified_launch_packets(launch_args)
+ self.add_register_info_collection_packets()
+
+ # Run the packet stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Gather register info entries.
+ reg_infos = self.parse_register_info_packets(context)
+
+ # Collect all register sets found.
+ register_sets = { reg_info['set']:1 for reg_info in reg_infos if 'set' in reg_info }
+ self.assertTrue(len(register_sets) >= 1)
+
+ @debugserver_test
+ def test_qRegisterInfo_contains_at_least_one_register_set_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.qRegisterInfo_contains_at_least_one_register_set()
+
+ @llgs_test
+ def test_qRegisterInfo_contains_at_least_one_register_set_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.qRegisterInfo_contains_at_least_one_register_set()
+
+ def targetHasAVX(self):
+ triple = self.dbg.GetSelectedPlatform().GetTriple()
+
+ # TODO other platforms, please implement this function
+ if not re.match(".*-.*-linux", triple):
+ return True
+
+ # Need to do something different for non-Linux/Android targets
+ if lldb.remote_platform:
+ self.runCmd('platform get-file "/proc/cpuinfo" "cpuinfo"')
+ cpuinfo_path = "cpuinfo"
+ self.addTearDownHook(lambda: os.unlink("cpuinfo"))
+ else:
+ cpuinfo_path = "/proc/cpuinfo"
+
+ f = open(cpuinfo_path, 'r')
+ cpuinfo = f.read()
+ f.close()
+ return " avx " in cpuinfo
+
+ def qRegisterInfo_contains_avx_registers(self):
+ launch_args = self.install_and_create_launch_args()
+
+ server = self.connect_to_debug_monitor()
+ self.assertIsNotNone(server)
+
+ # Build the expected protocol stream
+ self.add_no_ack_remote_stream()
+ self.add_verified_launch_packets(launch_args)
+ self.add_register_info_collection_packets()
+
+ # Run the packet stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Gather register info entries.
+ reg_infos = self.parse_register_info_packets(context)
+
+ # Collect all generics found.
+ register_sets = { reg_info['set']:1 for reg_info in reg_infos if 'set' in reg_info }
+ self.assertEqual(self.targetHasAVX(), "Advanced Vector Extensions" in register_sets)
+
+ @llgs_test
+ def test_qRegisterInfo_contains_avx_registers_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.qRegisterInfo_contains_avx_registers()
+
+ def qThreadInfo_contains_thread(self):
+ procs = self.prep_debug_monitor_and_inferior()
+ self.add_threadinfo_collection_packets()
+
+ # Run the packet stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Gather threadinfo entries.
+ threads = self.parse_threadinfo_packets(context)
+ self.assertIsNotNone(threads)
+
+ # We should have exactly one thread.
+ self.assertEqual(len(threads), 1)
+
+ @debugserver_test
+ def test_qThreadInfo_contains_thread_launch_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.qThreadInfo_contains_thread()
+
+ @llgs_test
+ def test_qThreadInfo_contains_thread_launch_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.qThreadInfo_contains_thread()
+
+ @debugserver_test
+ def test_qThreadInfo_contains_thread_attach_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_attach()
+ self.qThreadInfo_contains_thread()
+
+ @llgs_test
+ def test_qThreadInfo_contains_thread_attach_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_attach()
+ self.qThreadInfo_contains_thread()
+
+ def qThreadInfo_matches_qC(self):
+ procs = self.prep_debug_monitor_and_inferior()
+
+ self.add_threadinfo_collection_packets()
+ self.test_sequence.add_log_lines(
+ ["read packet: $qC#00",
+ { "direction":"send", "regex":r"^\$QC([0-9a-fA-F]+)#", "capture":{1:"thread_id"} }
+ ], True)
+
+ # Run the packet stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Gather threadinfo entries.
+ threads = self.parse_threadinfo_packets(context)
+ self.assertIsNotNone(threads)
+
+ # We should have exactly one thread from threadinfo.
+ self.assertEqual(len(threads), 1)
+
+ # We should have a valid thread_id from $QC.
+ QC_thread_id_hex = context.get("thread_id")
+ self.assertIsNotNone(QC_thread_id_hex)
+ QC_thread_id = int(QC_thread_id_hex, 16)
+
+ # Those two should be the same.
+ self.assertEqual(threads[0], QC_thread_id)
+
+ @debugserver_test
+ def test_qThreadInfo_matches_qC_launch_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.qThreadInfo_matches_qC()
+
+ @llgs_test
+ def test_qThreadInfo_matches_qC_launch_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.qThreadInfo_matches_qC()
+
+ @debugserver_test
+ def test_qThreadInfo_matches_qC_attach_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_attach()
+ self.qThreadInfo_matches_qC()
+
+ @llgs_test
+ def test_qThreadInfo_matches_qC_attach_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_attach()
+ self.qThreadInfo_matches_qC()
+
+ def p_returns_correct_data_size_for_each_qRegisterInfo(self):
+ procs = self.prep_debug_monitor_and_inferior()
+ self.add_register_info_collection_packets()
+
+ # Run the packet stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Gather register info entries.
+ reg_infos = self.parse_register_info_packets(context)
+ self.assertIsNotNone(reg_infos)
+ self.assertTrue(len(reg_infos) > 0)
+
+ # Read value for each register.
+ reg_index = 0
+ for reg_info in reg_infos:
+ # Skip registers that don't have a register set. For x86, these are
+ # the DRx registers, which have no LLDB-kind register number and thus
+ # cannot be read via normal NativeRegisterContext::ReadRegister(reg_info,...) calls.
+ if not "set" in reg_info:
+ continue
+
+ # Clear existing packet expectations.
+ self.reset_test_sequence()
+
+ # Run the register query
+ self.test_sequence.add_log_lines(
+ ["read packet: $p{0:x}#00".format(reg_index),
+ { "direction":"send", "regex":r"^\$([0-9a-fA-F]+)#", "capture":{1:"p_response"} }],
+ True)
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Verify the response length.
+ p_response = context.get("p_response")
+ self.assertIsNotNone(p_response)
+ self.assertEqual(len(p_response), 2 * int(reg_info["bitsize"]) / 8)
+
+ # Increment loop
+ reg_index += 1
+
+ @debugserver_test
+ def test_p_returns_correct_data_size_for_each_qRegisterInfo_launch_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.p_returns_correct_data_size_for_each_qRegisterInfo()
+
+ @llgs_test
+ def test_p_returns_correct_data_size_for_each_qRegisterInfo_launch_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.p_returns_correct_data_size_for_each_qRegisterInfo()
+
+ @debugserver_test
+ def test_p_returns_correct_data_size_for_each_qRegisterInfo_attach_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_attach()
+ self.p_returns_correct_data_size_for_each_qRegisterInfo()
+
+ @llgs_test
+ def test_p_returns_correct_data_size_for_each_qRegisterInfo_attach_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_attach()
+ self.p_returns_correct_data_size_for_each_qRegisterInfo()
+
+ def Hg_switches_to_3_threads(self):
+ # Startup the inferior with three threads (main + 2 new ones).
+ procs = self.prep_debug_monitor_and_inferior(inferior_args=["thread:new", "thread:new"])
+
+ # Let the inferior process have a few moments to start up the thread when launched. (The launch scenario has no time to run, so threads won't be there yet.)
+ self.run_process_then_stop(run_seconds=1)
+
+ # Wait at most x seconds for 3 threads to be present.
+ threads = self.wait_for_thread_count(3, timeout_seconds=5)
+ self.assertEqual(len(threads), 3)
+
+ # verify we can $H to each thead, and $qC matches the thread we set.
+ for thread in threads:
+ # Change to each thread, verify current thread id.
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines(
+ ["read packet: $Hg{0:x}#00".format(thread), # Set current thread.
+ "send packet: $OK#00",
+ "read packet: $qC#00",
+ { "direction":"send", "regex":r"^\$QC([0-9a-fA-F]+)#", "capture":{1:"thread_id"} }],
+ True)
+
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Verify the thread id.
+ self.assertIsNotNone(context.get("thread_id"))
+ self.assertEqual(int(context.get("thread_id"), 16), thread)
+
+ @debugserver_test
+ def test_Hg_switches_to_3_threads_launch_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.Hg_switches_to_3_threads()
+
+ @llgs_test
+ def test_Hg_switches_to_3_threads_launch_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.Hg_switches_to_3_threads()
+
+ @debugserver_test
+ def test_Hg_switches_to_3_threads_attach_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_attach()
+ self.Hg_switches_to_3_threads()
+
+ @llgs_test
+ def test_Hg_switches_to_3_threads_attach_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_attach()
+ self.Hg_switches_to_3_threads()
+
+ def Hc_then_Csignal_signals_correct_thread(self, segfault_signo):
+ # NOTE only run this one in inferior-launched mode: we can't grab inferior stdout when running attached,
+ # and the test requires getting stdout from the exe.
+
+ NUM_THREADS = 3
+
+ # Startup the inferior with three threads (main + NUM_THREADS-1 worker threads).
+ # inferior_args=["thread:print-ids"]
+ inferior_args=["thread:segfault"]
+ for i in range(NUM_THREADS - 1):
+ # if i > 0:
+ # Give time between thread creation/segfaulting for the handler to work.
+ # inferior_args.append("sleep:1")
+ inferior_args.append("thread:new")
+ inferior_args.append("sleep:10")
+
+ # Launch/attach. (In our case, this should only ever be launched since we need inferior stdout/stderr).
+ procs = self.prep_debug_monitor_and_inferior(inferior_args=inferior_args)
+ self.test_sequence.add_log_lines(["read packet: $c#63"], True)
+ context = self.expect_gdbremote_sequence()
+
+ # Let the inferior process have a few moments to start up the thread when launched.
+ # context = self.run_process_then_stop(run_seconds=1)
+
+ # Wait at most x seconds for all threads to be present.
+ # threads = self.wait_for_thread_count(NUM_THREADS, timeout_seconds=5)
+ # self.assertEquals(len(threads), NUM_THREADS)
+
+ signaled_tids = {}
+ print_thread_ids = {}
+
+ # Switch to each thread, deliver a signal, and verify signal delivery
+ for i in range(NUM_THREADS - 1):
+ # Run until SIGSEGV comes in.
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines(
+ [{"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"signo", 2:"thread_id"} }
+ ], True)
+
+ context = self.expect_gdbremote_sequence(timeout_seconds=10)
+ self.assertIsNotNone(context)
+ signo = context.get("signo")
+ self.assertEqual(int(signo, 16), segfault_signo)
+
+ # Ensure we haven't seen this tid yet.
+ thread_id = int(context.get("thread_id"), 16)
+ self.assertFalse(thread_id in signaled_tids)
+ signaled_tids[thread_id] = 1
+
+ # Send SIGUSR1 to the thread that signaled the SIGSEGV.
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines(
+ [
+ # Set the continue thread.
+ "read packet: $Hc{0:x}#00".format(thread_id), # Set current thread.
+ "send packet: $OK#00",
+
+ # Continue sending the signal number to the continue thread.
+ # The commented out packet is a way to do this same operation without using
+ # a $Hc (but this test is testing $Hc, so we'll stick with the former).
+ "read packet: $C{0:x}#00".format(lldbutil.get_signal_number('SIGUSR1')),
+ # "read packet: $vCont;C{0:x}:{1:x};c#00".format(lldbutil.get_signal_number('SIGUSR1'), thread_id),
+
+ # FIXME: Linux does not report the thread stop on the delivered signal (SIGUSR1 here). MacOSX debugserver does.
+ # But MacOSX debugserver isn't guaranteeing the thread the signal handler runs on, so currently its an XFAIL.
+ # Need to rectify behavior here. The linux behavior is more intuitive to me since we're essentially swapping out
+ # an about-to-be-delivered signal (for which we already sent a stop packet) to a different signal.
+ # {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} },
+ # "read packet: $c#63",
+ { "type":"output_match", "regex":r"^received SIGUSR1 on thread id: ([0-9a-fA-F]+)\r\nthread ([0-9a-fA-F]+): past SIGSEGV\r\n", "capture":{ 1:"print_thread_id", 2:"post_handle_thread_id" } },
+ ],
+ True)
+
+ # Run the sequence.
+ context = self.expect_gdbremote_sequence(timeout_seconds=10)
+ self.assertIsNotNone(context)
+
+ # Ensure the stop signal is the signal we delivered.
+ # stop_signo = context.get("stop_signo")
+ # self.assertIsNotNone(stop_signo)
+ # self.assertEquals(int(stop_signo,16), lldbutil.get_signal_number('SIGUSR1'))
+
+ # Ensure the stop thread is the thread to which we delivered the signal.
+ # stop_thread_id = context.get("stop_thread_id")
+ # self.assertIsNotNone(stop_thread_id)
+ # self.assertEquals(int(stop_thread_id,16), thread_id)
+
+ # Ensure we haven't seen this thread id yet. The inferior's self-obtained thread ids are not guaranteed to match the stub tids (at least on MacOSX).
+ print_thread_id = context.get("print_thread_id")
+ self.assertIsNotNone(print_thread_id)
+ print_thread_id = int(print_thread_id, 16)
+ self.assertFalse(print_thread_id in print_thread_ids)
+
+ # Now remember this print (i.e. inferior-reflected) thread id and ensure we don't hit it again.
+ print_thread_ids[print_thread_id] = 1
+
+ # Ensure post signal-handle thread id matches the thread that initially raised the SIGSEGV.
+ post_handle_thread_id = context.get("post_handle_thread_id")
+ self.assertIsNotNone(post_handle_thread_id)
+ post_handle_thread_id = int(post_handle_thread_id, 16)
+ self.assertEqual(post_handle_thread_id, print_thread_id)
+
+ @unittest2.expectedFailure()
+ @debugserver_test
+ def test_Hc_then_Csignal_signals_correct_thread_launch_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ # Darwin debugserver translates some signals like SIGSEGV into some gdb expectations about fixed signal numbers.
+ self.Hc_then_Csignal_signals_correct_thread(self.TARGET_EXC_BAD_ACCESS)
+
+ @llgs_test
+ def test_Hc_then_Csignal_signals_correct_thread_launch_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.Hc_then_Csignal_signals_correct_thread(lldbutil.get_signal_number('SIGSEGV'))
+
+ def m_packet_reads_memory(self):
+ # This is the memory we will write into the inferior and then ensure we can read back with $m.
+ MEMORY_CONTENTS = "Test contents 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"
+
+ # Start up the inferior.
+ procs = self.prep_debug_monitor_and_inferior(
+ inferior_args=["set-message:%s" % MEMORY_CONTENTS, "get-data-address-hex:g_message", "sleep:5"])
+
+ # Run the process
+ self.test_sequence.add_log_lines(
+ [
+ # Start running after initial stop.
+ "read packet: $c#63",
+ # Match output line that prints the memory address of the message buffer within the inferior.
+ # Note we require launch-only testing so we can get inferior otuput.
+ { "type":"output_match", "regex":r"^data address: 0x([0-9a-fA-F]+)\r\n$", "capture":{ 1:"message_address"} },
+ # Now stop the inferior.
+ "read packet: {}".format(chr(3)),
+ # And wait for the stop notification.
+ {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} }],
+ True)
+
+ # Run the packet stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Grab the message address.
+ self.assertIsNotNone(context.get("message_address"))
+ message_address = int(context.get("message_address"), 16)
+
+ # Grab contents from the inferior.
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines(
+ ["read packet: $m{0:x},{1:x}#00".format(message_address, len(MEMORY_CONTENTS)),
+ {"direction":"send", "regex":r"^\$(.+)#[0-9a-fA-F]{2}$", "capture":{1:"read_contents"} }],
+ True)
+
+ # Run the packet stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Ensure what we read from inferior memory is what we wrote.
+ self.assertIsNotNone(context.get("read_contents"))
+ read_contents = context.get("read_contents").decode("hex")
+ self.assertEqual(read_contents, MEMORY_CONTENTS)
+
+ @debugserver_test
+ def test_m_packet_reads_memory_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.m_packet_reads_memory()
+
+ @llgs_test
+ def test_m_packet_reads_memory_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.m_packet_reads_memory()
+
+ def qMemoryRegionInfo_is_supported(self):
+ # Start up the inferior.
+ procs = self.prep_debug_monitor_and_inferior()
+
+ # Ask if it supports $qMemoryRegionInfo.
+ self.test_sequence.add_log_lines(
+ ["read packet: $qMemoryRegionInfo#00",
+ "send packet: $OK#00"
+ ], True)
+ self.expect_gdbremote_sequence()
+
+ @debugserver_test
+ def test_qMemoryRegionInfo_is_supported_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.qMemoryRegionInfo_is_supported()
+
+ @llgs_test
+ def test_qMemoryRegionInfo_is_supported_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.qMemoryRegionInfo_is_supported()
+
+ def qMemoryRegionInfo_reports_code_address_as_executable(self):
+ # Start up the inferior.
+ procs = self.prep_debug_monitor_and_inferior(
+ inferior_args=["get-code-address-hex:hello", "sleep:5"])
+
+ # Run the process
+ self.test_sequence.add_log_lines(
+ [
+ # Start running after initial stop.
+ "read packet: $c#63",
+ # Match output line that prints the memory address of the message buffer within the inferior.
+ # Note we require launch-only testing so we can get inferior otuput.
+ { "type":"output_match", "regex":r"^code address: 0x([0-9a-fA-F]+)\r\n$", "capture":{ 1:"code_address"} },
+ # Now stop the inferior.
+ "read packet: {}".format(chr(3)),
+ # And wait for the stop notification.
+ {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} }],
+ True)
+
+ # Run the packet stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Grab the code address.
+ self.assertIsNotNone(context.get("code_address"))
+ code_address = int(context.get("code_address"), 16)
+
+ # Grab memory region info from the inferior.
+ self.reset_test_sequence()
+ self.add_query_memory_region_packets(code_address)
+
+ # Run the packet stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+ mem_region_dict = self.parse_memory_region_packet(context)
+
+ # Ensure there are no errors reported.
+ self.assertFalse("error" in mem_region_dict)
+
+ # Ensure code address is readable and executable.
+ self.assertTrue("permissions" in mem_region_dict)
+ self.assertTrue("r" in mem_region_dict["permissions"])
+ self.assertTrue("x" in mem_region_dict["permissions"])
+
+ # Ensure the start address and size encompass the address we queried.
+ self.assert_address_within_memory_region(code_address, mem_region_dict)
+
+ @debugserver_test
+ def test_qMemoryRegionInfo_reports_code_address_as_executable_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.qMemoryRegionInfo_reports_code_address_as_executable()
+
+ @llgs_test
+ def test_qMemoryRegionInfo_reports_code_address_as_executable_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.qMemoryRegionInfo_reports_code_address_as_executable()
+
+ def qMemoryRegionInfo_reports_stack_address_as_readable_writeable(self):
+ # Start up the inferior.
+ procs = self.prep_debug_monitor_and_inferior(
+ inferior_args=["get-stack-address-hex:", "sleep:5"])
+
+ # Run the process
+ self.test_sequence.add_log_lines(
+ [
+ # Start running after initial stop.
+ "read packet: $c#63",
+ # Match output line that prints the memory address of the message buffer within the inferior.
+ # Note we require launch-only testing so we can get inferior otuput.
+ { "type":"output_match", "regex":r"^stack address: 0x([0-9a-fA-F]+)\r\n$", "capture":{ 1:"stack_address"} },
+ # Now stop the inferior.
+ "read packet: {}".format(chr(3)),
+ # And wait for the stop notification.
+ {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} }],
+ True)
+
+ # Run the packet stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Grab the address.
+ self.assertIsNotNone(context.get("stack_address"))
+ stack_address = int(context.get("stack_address"), 16)
+
+ # Grab memory region info from the inferior.
+ self.reset_test_sequence()
+ self.add_query_memory_region_packets(stack_address)
+
+ # Run the packet stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+ mem_region_dict = self.parse_memory_region_packet(context)
+
+ # Ensure there are no errors reported.
+ self.assertFalse("error" in mem_region_dict)
+
+ # Ensure address is readable and executable.
+ self.assertTrue("permissions" in mem_region_dict)
+ self.assertTrue("r" in mem_region_dict["permissions"])
+ self.assertTrue("w" in mem_region_dict["permissions"])
+
+ # Ensure the start address and size encompass the address we queried.
+ self.assert_address_within_memory_region(stack_address, mem_region_dict)
+
+ @debugserver_test
+ def test_qMemoryRegionInfo_reports_stack_address_as_readable_writeable_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.qMemoryRegionInfo_reports_stack_address_as_readable_writeable()
+
+ @llgs_test
+ def test_qMemoryRegionInfo_reports_stack_address_as_readable_writeable_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.qMemoryRegionInfo_reports_stack_address_as_readable_writeable()
+
+ def qMemoryRegionInfo_reports_heap_address_as_readable_writeable(self):
+ # Start up the inferior.
+ procs = self.prep_debug_monitor_and_inferior(
+ inferior_args=["get-heap-address-hex:", "sleep:5"])
+
+ # Run the process
+ self.test_sequence.add_log_lines(
+ [
+ # Start running after initial stop.
+ "read packet: $c#63",
+ # Match output line that prints the memory address of the message buffer within the inferior.
+ # Note we require launch-only testing so we can get inferior otuput.
+ { "type":"output_match", "regex":r"^heap address: 0x([0-9a-fA-F]+)\r\n$", "capture":{ 1:"heap_address"} },
+ # Now stop the inferior.
+ "read packet: {}".format(chr(3)),
+ # And wait for the stop notification.
+ {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} }],
+ True)
+
+ # Run the packet stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Grab the address.
+ self.assertIsNotNone(context.get("heap_address"))
+ heap_address = int(context.get("heap_address"), 16)
+
+ # Grab memory region info from the inferior.
+ self.reset_test_sequence()
+ self.add_query_memory_region_packets(heap_address)
+
+ # Run the packet stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+ mem_region_dict = self.parse_memory_region_packet(context)
+
+ # Ensure there are no errors reported.
+ self.assertFalse("error" in mem_region_dict)
+
+ # Ensure address is readable and executable.
+ self.assertTrue("permissions" in mem_region_dict)
+ self.assertTrue("r" in mem_region_dict["permissions"])
+ self.assertTrue("w" in mem_region_dict["permissions"])
+
+ # Ensure the start address and size encompass the address we queried.
+ self.assert_address_within_memory_region(heap_address, mem_region_dict)
+
+
+ @debugserver_test
+ def test_qMemoryRegionInfo_reports_heap_address_as_readable_writeable_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.qMemoryRegionInfo_reports_heap_address_as_readable_writeable()
+
+ @llgs_test
+ def test_qMemoryRegionInfo_reports_heap_address_as_readable_writeable_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.qMemoryRegionInfo_reports_heap_address_as_readable_writeable()
+
+ def software_breakpoint_set_and_remove_work(self):
+ # Start up the inferior.
+ procs = self.prep_debug_monitor_and_inferior(
+ inferior_args=["get-code-address-hex:hello", "sleep:1", "call-function:hello"])
+
+ # Run the process
+ self.add_register_info_collection_packets()
+ self.add_process_info_collection_packets()
+ self.test_sequence.add_log_lines(
+ [# Start running after initial stop.
+ "read packet: $c#63",
+ # Match output line that prints the memory address of the function call entry point.
+ # Note we require launch-only testing so we can get inferior otuput.
+ { "type":"output_match", "regex":r"^code address: 0x([0-9a-fA-F]+)\r\n$", "capture":{ 1:"function_address"} },
+ # Now stop the inferior.
+ "read packet: {}".format(chr(3)),
+ # And wait for the stop notification.
+ {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} }],
+ True)
+
+ # Run the packet stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Gather process info - we need endian of target to handle register value conversions.
+ process_info = self.parse_process_info_response(context)
+ endian = process_info.get("endian")
+ self.assertIsNotNone(endian)
+
+ # Gather register info entries.
+ reg_infos = self.parse_register_info_packets(context)
+ (pc_lldb_reg_index, pc_reg_info) = self.find_pc_reg_info(reg_infos)
+ self.assertIsNotNone(pc_lldb_reg_index)
+ self.assertIsNotNone(pc_reg_info)
+
+ # Grab the function address.
+ self.assertIsNotNone(context.get("function_address"))
+ function_address = int(context.get("function_address"), 16)
+
+ # Set the breakpoint.
+ if self.getArchitecture() == "arm":
+ # TODO: Handle case when setting breakpoint in thumb code
+ BREAKPOINT_KIND = 4
+ else:
+ BREAKPOINT_KIND = 1
+ self.reset_test_sequence()
+ self.add_set_breakpoint_packets(function_address, do_continue=True, breakpoint_kind=BREAKPOINT_KIND)
+
+ # Run the packet stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Verify the stop signal reported was the breakpoint signal number.
+ stop_signo = context.get("stop_signo")
+ self.assertIsNotNone(stop_signo)
+ self.assertEqual(int(stop_signo,16), lldbutil.get_signal_number('SIGTRAP'))
+
+ # Ensure we did not receive any output. If the breakpoint was not set, we would
+ # see output (from a launched process with captured stdio) printing a hello, world message.
+ # That would indicate the breakpoint didn't take.
+ self.assertEqual(len(context["O_content"]), 0)
+
+ # Verify that the PC for the main thread is where we expect it - right at the breakpoint address.
+ # This acts as a another validation on the register reading code.
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines(
+ [
+ # Print the PC. This should match the breakpoint address.
+ "read packet: $p{0:x}#00".format(pc_lldb_reg_index),
+ # Capture $p results.
+ { "direction":"send", "regex":r"^\$([0-9a-fA-F]+)#", "capture":{1:"p_response"} },
+ ], True)
+
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Verify the PC is where we expect. Note response is in endianness of the inferior.
+ p_response = context.get("p_response")
+ self.assertIsNotNone(p_response)
+
+ # Convert from target endian to int.
+ returned_pc = lldbgdbserverutils.unpack_register_hex_unsigned(endian, p_response)
+ self.assertEqual(returned_pc, function_address)
+
+ # Verify that a breakpoint remove and continue gets us the expected output.
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines(
+ [
+ # Remove the breakpoint.
+ "read packet: $z0,{0:x},{1}#00".format(function_address, BREAKPOINT_KIND),
+ # Verify the stub could unset it.
+ "send packet: $OK#00",
+ # Continue running.
+ "read packet: $c#63",
+ # We should now receive the output from the call.
+ { "type":"output_match", "regex":r"^hello, world\r\n$" },
+ # And wait for program completion.
+ {"direction":"send", "regex":r"^\$W00(.*)#[0-9a-fA-F]{2}$" },
+ ], True)
+
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ @debugserver_test
+ def test_software_breakpoint_set_and_remove_work_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.software_breakpoint_set_and_remove_work()
+
+ @llgs_test
+ def test_software_breakpoint_set_and_remove_work_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.software_breakpoint_set_and_remove_work()
+
+ def qSupported_returns_known_stub_features(self):
+ # Start up the stub and start/prep the inferior.
+ procs = self.prep_debug_monitor_and_inferior()
+ self.add_qSupported_packets()
+
+ # Run the packet stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Retrieve the qSupported features.
+ supported_dict = self.parse_qSupported_response(context)
+ self.assertIsNotNone(supported_dict)
+ self.assertTrue(len(supported_dict) > 0)
+
+ @debugserver_test
+ def test_qSupported_returns_known_stub_features_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.qSupported_returns_known_stub_features()
+
+ @llgs_test
+ def test_qSupported_returns_known_stub_features_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.qSupported_returns_known_stub_features()
+
+ def written_M_content_reads_back_correctly(self):
+ TEST_MESSAGE = "Hello, memory"
+
+ # Start up the stub and start/prep the inferior.
+ procs = self.prep_debug_monitor_and_inferior(inferior_args=["set-message:xxxxxxxxxxxxxX", "get-data-address-hex:g_message", "sleep:1", "print-message:"])
+ self.test_sequence.add_log_lines(
+ [
+ # Start running after initial stop.
+ "read packet: $c#63",
+ # Match output line that prints the memory address of the message buffer within the inferior.
+ # Note we require launch-only testing so we can get inferior otuput.
+ { "type":"output_match", "regex":r"^data address: 0x([0-9a-fA-F]+)\r\n$", "capture":{ 1:"message_address"} },
+ # Now stop the inferior.
+ "read packet: {}".format(chr(3)),
+ # And wait for the stop notification.
+ {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} }],
+ True)
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Grab the message address.
+ self.assertIsNotNone(context.get("message_address"))
+ message_address = int(context.get("message_address"), 16)
+
+ # Hex-encode the test message, adding null termination.
+ hex_encoded_message = TEST_MESSAGE.encode("hex")
+
+ # Write the message to the inferior.
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines(
+ ["read packet: $M{0:x},{1:x}:{2}#00".format(message_address, len(hex_encoded_message)/2, hex_encoded_message),
+ "send packet: $OK#00",
+ "read packet: $c#63",
+ { "type":"output_match", "regex":r"^message: (.+)\r\n$", "capture":{ 1:"printed_message"} },
+ "send packet: $W00#00",
+ ], True)
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Ensure what we read from inferior memory is what we wrote.
+ printed_message = context.get("printed_message")
+ self.assertIsNotNone(printed_message)
+ self.assertEqual(printed_message, TEST_MESSAGE + "X")
+
+ @debugserver_test
+ def test_written_M_content_reads_back_correctly_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.written_M_content_reads_back_correctly()
+
+ @llgs_test
+ def test_written_M_content_reads_back_correctly_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.written_M_content_reads_back_correctly()
+
+ def P_writes_all_gpr_registers(self):
+ # Start inferior debug session, grab all register info.
+ procs = self.prep_debug_monitor_and_inferior(inferior_args=["sleep:2"])
+ self.add_register_info_collection_packets()
+ self.add_process_info_collection_packets()
+
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Process register infos.
+ reg_infos = self.parse_register_info_packets(context)
+ self.assertIsNotNone(reg_infos)
+ self.add_lldb_register_index(reg_infos)
+
+ # Process endian.
+ process_info = self.parse_process_info_response(context)
+ endian = process_info.get("endian")
+ self.assertIsNotNone(endian)
+
+ # Pull out the register infos that we think we can bit flip successfully,.
+ gpr_reg_infos = [reg_info for reg_info in reg_infos if self.is_bit_flippable_register(reg_info)]
+ self.assertTrue(len(gpr_reg_infos) > 0)
+
+ # Write flipped bit pattern of existing value to each register.
+ (successful_writes, failed_writes) = self.flip_all_bits_in_each_register_value(gpr_reg_infos, endian)
+ # print("successful writes: {}, failed writes: {}".format(successful_writes, failed_writes))
+ self.assertTrue(successful_writes > 0)
+
+ # Note: as of this moment, a hefty number of the GPR writes are failing with E32 (everything except rax-rdx, rdi, rsi, rbp).
+ # Come back to this. I have the test rigged to verify that at least some of the bit-flip writes work.
+ @debugserver_test
+ def test_P_writes_all_gpr_registers_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.P_writes_all_gpr_registers()
+
+ @llgs_test
+ def test_P_writes_all_gpr_registers_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.P_writes_all_gpr_registers()
+
+ def P_and_p_thread_suffix_work(self):
+ # Startup the inferior with three threads.
+ procs = self.prep_debug_monitor_and_inferior(inferior_args=["thread:new", "thread:new"])
+ self.add_thread_suffix_request_packets()
+ self.add_register_info_collection_packets()
+ self.add_process_info_collection_packets()
+
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ process_info = self.parse_process_info_response(context)
+ self.assertIsNotNone(process_info)
+ endian = process_info.get("endian")
+ self.assertIsNotNone(endian)
+
+ reg_infos = self.parse_register_info_packets(context)
+ self.assertIsNotNone(reg_infos)
+ self.add_lldb_register_index(reg_infos)
+
+ reg_index = self.select_modifiable_register(reg_infos)
+ self.assertIsNotNone(reg_index)
+ reg_byte_size = int(reg_infos[reg_index]["bitsize"]) / 8
+ self.assertTrue(reg_byte_size > 0)
+
+ # Run the process a bit so threads can start up, and collect register info.
+ context = self.run_process_then_stop(run_seconds=1)
+ self.assertIsNotNone(context)
+
+ # Wait for 3 threads to be present.
+ threads = self.wait_for_thread_count(3, timeout_seconds=5)
+ self.assertEqual(len(threads), 3)
+
+ expected_reg_values = []
+ register_increment = 1
+ next_value = None
+
+ # Set the same register in each of 3 threads to a different value.
+ # Verify each one has the unique value.
+ for thread in threads:
+ # If we don't have a next value yet, start it with the initial read value + 1
+ if not next_value:
+ # Read pre-existing register value.
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines(
+ ["read packet: $p{0:x};thread:{1:x}#00".format(reg_index, thread),
+ { "direction":"send", "regex":r"^\$([0-9a-fA-F]+)#", "capture":{1:"p_response"} },
+ ], True)
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Set the next value to use for writing as the increment plus current value.
+ p_response = context.get("p_response")
+ self.assertIsNotNone(p_response)
+ next_value = lldbgdbserverutils.unpack_register_hex_unsigned(endian, p_response)
+
+ # Set new value using P and thread suffix.
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines(
+ ["read packet: $P{0:x}={1};thread:{2:x}#00".format(reg_index, lldbgdbserverutils.pack_register_hex(endian, next_value, byte_size=reg_byte_size), thread),
+ "send packet: $OK#00",
+ ], True)
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Save the value we set.
+ expected_reg_values.append(next_value)
+
+ # Increment value for next thread to use (we want them all different so we can verify they wrote to each thread correctly next.)
+ next_value += register_increment
+
+ # Revisit each thread and verify they have the expected value set for the register we wrote.
+ thread_index = 0
+ for thread in threads:
+ # Read pre-existing register value.
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines(
+ ["read packet: $p{0:x};thread:{1:x}#00".format(reg_index, thread),
+ { "direction":"send", "regex":r"^\$([0-9a-fA-F]+)#", "capture":{1:"p_response"} },
+ ], True)
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Get the register value.
+ p_response = context.get("p_response")
+ self.assertIsNotNone(p_response)
+ read_value = lldbgdbserverutils.unpack_register_hex_unsigned(endian, p_response)
+
+ # Make sure we read back what we wrote.
+ self.assertEqual(read_value, expected_reg_values[thread_index])
+ thread_index += 1
+
+ # Note: as of this moment, a hefty number of the GPR writes are failing with E32 (everything except rax-rdx, rdi, rsi, rbp).
+ @debugserver_test
+ def test_P_and_p_thread_suffix_work_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.P_and_p_thread_suffix_work()
+
+ @llgs_test
+ def test_P_and_p_thread_suffix_work_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.set_inferior_startup_launch()
+ self.P_and_p_thread_suffix_work()
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubReverseConnect.py b/packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubReverseConnect.py
new file mode 100644
index 000000000000..9035237b982a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubReverseConnect.py
@@ -0,0 +1,87 @@
+from __future__ import print_function
+
+import gdbremote_testcase
+import lldbgdbserverutils
+import re
+import select
+import socket
+import time
+from lldbsuite.test.lldbtest import *
+
+class TestStubReverseConnect(gdbremote_testcase.GdbRemoteTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ _DEFAULT_TIMEOUT = 20
+
+ def setUp(self):
+ # Set up the test.
+ gdbremote_testcase.GdbRemoteTestCaseBase.setUp(self)
+
+ # Create a listener on a local port.
+ self.listener_socket = self.create_listener_socket()
+ self.assertIsNotNone(self.listener_socket)
+ self.listener_port = self.listener_socket.getsockname()[1]
+
+ def create_listener_socket(self, timeout_seconds=_DEFAULT_TIMEOUT):
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ self.assertIsNotNone(sock)
+
+ sock.settimeout(timeout_seconds)
+ sock.bind(("127.0.0.1",0))
+ sock.listen(1)
+
+ def tear_down_listener():
+ try:
+ sock.shutdown(socket.SHUT_RDWR)
+ except:
+ # ignore
+ None
+
+ self.addTearDownHook(tear_down_listener)
+ return sock
+
+ def reverse_connect_works(self):
+ # Indicate stub startup should do a reverse connect.
+ appended_stub_args = ["--reverse-connect"]
+ if self.debug_monitor_extra_args:
+ self.debug_monitor_extra_args += appended_stub_args
+ else:
+ self.debug_monitor_extra_args = appended_stub_args
+
+ self.stub_hostname = "127.0.0.1"
+ self.port = self.listener_port
+
+ triple = self.dbg.GetSelectedPlatform().GetTriple()
+ if re.match(".*-.*-.*-android", triple):
+ self.forward_adb_port(self.port, self.port, "reverse", self.stub_device)
+
+ # Start the stub.
+ server = self.launch_debug_monitor(logfile=sys.stdout)
+ self.assertIsNotNone(server)
+ self.assertTrue(lldbgdbserverutils.process_is_running(server.pid, True))
+
+ # Listen for the stub's connection to us.
+ (stub_socket, address) = self.listener_socket.accept()
+ self.assertIsNotNone(stub_socket)
+ self.assertIsNotNone(address)
+ print("connected to stub {} on {}".format(address, stub_socket.getsockname()))
+
+ # Verify we can do the handshake. If that works, we'll call it good.
+ self.do_handshake(stub_socket, timeout_seconds=self._DEFAULT_TIMEOUT)
+
+ # Clean up.
+ stub_socket.shutdown(socket.SHUT_RDWR)
+
+ @debugserver_test
+ def test_reverse_connect_works_debugserver(self):
+ self.init_debugserver_test(use_named_pipe=False)
+ self.set_inferior_startup_launch()
+ self.reverse_connect_works()
+
+ @llgs_test
+ @skipIfRemote # reverse connect is not a supported use case for now
+ def test_reverse_connect_works_llgs(self):
+ self.init_llgs_test(use_named_pipe=False)
+ self.set_inferior_startup_launch()
+ self.reverse_connect_works()
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubSetSID.py b/packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubSetSID.py
new file mode 100644
index 000000000000..2b2b0e82379b
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/commandline/TestStubSetSID.py
@@ -0,0 +1,82 @@
+from __future__ import print_function
+
+
+
+import gdbremote_testcase
+import lldbgdbserverutils
+import os
+import select
+import tempfile
+import time
+from lldbsuite.test.lldbtest import *
+
+class TestStubSetSIDTestCase(gdbremote_testcase.GdbRemoteTestCaseBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def get_stub_sid(self, extra_stub_args=None):
+ # Launch debugserver
+ if extra_stub_args:
+ self.debug_monitor_extra_args += extra_stub_args
+
+ server = self.launch_debug_monitor()
+ self.assertIsNotNone(server)
+ self.assertTrue(lldbgdbserverutils.process_is_running(server.pid, True))
+
+ # Get the process id for the stub.
+ return os.getsid(server.pid)
+
+ def sid_is_same_without_setsid(self):
+ stub_sid = self.get_stub_sid()
+ self.assertEqual(stub_sid, os.getsid(0))
+
+ def sid_is_different_with_setsid(self):
+ stub_sid = self.get_stub_sid(["--setsid"])
+ self.assertNotEqual(stub_sid, os.getsid(0))
+
+ def sid_is_different_with_S(self):
+ stub_sid = self.get_stub_sid(["-S"])
+ self.assertNotEqual(stub_sid, os.getsid(0))
+
+ @debugserver_test
+ @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target
+ def test_sid_is_same_without_setsid_debugserver(self):
+ self.init_debugserver_test()
+ self.set_inferior_startup_launch()
+ self.sid_is_same_without_setsid()
+
+ @llgs_test
+ @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target
+ @expectedFailureFreeBSD()
+ def test_sid_is_same_without_setsid_llgs(self):
+ self.init_llgs_test()
+ self.set_inferior_startup_launch()
+ self.sid_is_same_without_setsid()
+
+ @debugserver_test
+ @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target
+ def test_sid_is_different_with_setsid_debugserver(self):
+ self.init_debugserver_test()
+ self.set_inferior_startup_launch()
+ self.sid_is_different_with_setsid()
+
+ @llgs_test
+ @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target
+ def test_sid_is_different_with_setsid_llgs(self):
+ self.init_llgs_test()
+ self.set_inferior_startup_launch()
+ self.sid_is_different_with_setsid()
+
+ @debugserver_test
+ @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target
+ def test_sid_is_different_with_S_debugserver(self):
+ self.init_debugserver_test()
+ self.set_inferior_startup_launch()
+ self.sid_is_different_with_S()
+
+ @llgs_test
+ @skipIfRemote # --setsid not used on remote platform and currently it is also impossible to get the sid of lldb-platform running on a remote target
+ def test_sid_is_different_with_S_llgs(self):
+ self.init_llgs_test()
+ self.set_inferior_startup_launch()
+ self.sid_is_different_with_S()
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py b/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py
new file mode 100644
index 000000000000..113e01e36ba7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py
@@ -0,0 +1,1299 @@
+"""
+Base class for gdb-remote test cases.
+"""
+
+from __future__ import print_function
+
+
+
+import errno
+import os
+import os.path
+import platform
+import random
+import re
+import select
+import signal
+import socket
+import subprocess
+import sys
+import tempfile
+import time
+from lldbsuite.test import configuration
+from lldbsuite.test.lldbtest import *
+from lldbgdbserverutils import *
+import logging
+
+class GdbRemoteTestCaseBase(TestBase):
+
+ _TIMEOUT_SECONDS = 5
+
+ _GDBREMOTE_KILL_PACKET = "$k#6b"
+
+ _LOGGING_LEVEL = logging.WARNING
+ # _LOGGING_LEVEL = logging.DEBUG
+
+ # Start the inferior separately, attach to the inferior on the stub command line.
+ _STARTUP_ATTACH = "attach"
+ # Start the inferior separately, start the stub without attaching, allow the test to attach to the inferior however it wants (e.g. $vAttach;pid).
+ _STARTUP_ATTACH_MANUALLY = "attach_manually"
+ # Start the stub, and launch the inferior with an $A packet via the initial packet stream.
+ _STARTUP_LAUNCH = "launch"
+
+ # GDB Signal numbers that are not target-specific used for common exceptions
+ TARGET_EXC_BAD_ACCESS = 0x91
+ TARGET_EXC_BAD_INSTRUCTION = 0x92
+ TARGET_EXC_ARITHMETIC = 0x93
+ TARGET_EXC_EMULATION = 0x94
+ TARGET_EXC_SOFTWARE = 0x95
+ TARGET_EXC_BREAKPOINT = 0x96
+
+ def setUp(self):
+ TestBase.setUp(self)
+ FORMAT = '%(asctime)-15s %(levelname)-8s %(message)s'
+ logging.basicConfig(format=FORMAT)
+ self.logger = logging.getLogger(__name__)
+ self.logger.setLevel(self._LOGGING_LEVEL)
+ self.test_sequence = GdbRemoteTestSequence(self.logger)
+ self.set_inferior_startup_launch()
+ self.port = self.get_next_port()
+ self.named_pipe_path = None
+ self.named_pipe = None
+ self.named_pipe_fd = None
+ self.stub_sends_two_stop_notifications_on_kill = False
+ if configuration.lldb_platform_url:
+ if configuration.lldb_platform_url.startswith('unix-'):
+ url_pattern = '(.+)://\[?(.+?)\]?/.*'
+ else:
+ url_pattern = '(.+)://(.+):\d+'
+ scheme, host = re.match(url_pattern, configuration.lldb_platform_url).groups()
+ if configuration.lldb_platform_name == 'remote-android' and host != 'localhost':
+ self.stub_device = host
+ self.stub_hostname = 'localhost'
+ else:
+ self.stub_device = None
+ self.stub_hostname = host
+ else:
+ self.stub_hostname = "localhost"
+
+ def get_next_port(self):
+ return 12000 + random.randint(0,3999)
+
+ def reset_test_sequence(self):
+ self.test_sequence = GdbRemoteTestSequence(self.logger)
+
+ def create_named_pipe(self):
+ # Create a temp dir and name for a pipe.
+ temp_dir = tempfile.mkdtemp()
+ named_pipe_path = os.path.join(temp_dir, "stub_port_number")
+
+ # Create the named pipe.
+ os.mkfifo(named_pipe_path)
+
+ # Open the read side of the pipe in non-blocking mode. This will return right away, ready or not.
+ named_pipe_fd = os.open(named_pipe_path, os.O_RDONLY | os.O_NONBLOCK)
+
+ # Create the file for the named pipe. Note this will follow semantics of
+ # a non-blocking read side of a named pipe, which has different semantics
+ # than a named pipe opened for read in non-blocking mode.
+ named_pipe = os.fdopen(named_pipe_fd, "r")
+ self.assertIsNotNone(named_pipe)
+
+ def shutdown_named_pipe():
+ # Close the pipe.
+ try:
+ named_pipe.close()
+ except:
+ print("failed to close named pipe")
+ None
+
+ # Delete the pipe.
+ try:
+ os.remove(named_pipe_path)
+ except:
+ print("failed to delete named pipe: {}".format(named_pipe_path))
+ None
+
+ # Delete the temp directory.
+ try:
+ os.rmdir(temp_dir)
+ except:
+ print("failed to delete temp dir: {}, directory contents: '{}'".format(temp_dir, os.listdir(temp_dir)))
+ None
+
+ # Add the shutdown hook to clean up the named pipe.
+ self.addTearDownHook(shutdown_named_pipe)
+
+ # Clear the port so the stub selects a port number.
+ self.port = 0
+
+ return (named_pipe_path, named_pipe, named_pipe_fd)
+
+ def get_stub_port_from_named_socket(self, read_timeout_seconds=5):
+ # Wait for something to read with a max timeout.
+ (ready_readers, _, _) = select.select([self.named_pipe_fd], [], [], read_timeout_seconds)
+ self.assertIsNotNone(ready_readers, "write side of pipe has not written anything - stub isn't writing to pipe.")
+ self.assertNotEqual(len(ready_readers), 0, "write side of pipe has not written anything - stub isn't writing to pipe.")
+
+ # Read the port from the named pipe.
+ stub_port_raw = self.named_pipe.read()
+ self.assertIsNotNone(stub_port_raw)
+ self.assertNotEqual(len(stub_port_raw), 0, "no content to read on pipe")
+
+ # Trim null byte, convert to int.
+ stub_port_raw = stub_port_raw[:-1]
+ stub_port = int(stub_port_raw)
+ self.assertTrue(stub_port > 0)
+
+ return stub_port
+
+ def run_shell_cmd(self, cmd):
+ platform = self.dbg.GetSelectedPlatform()
+ shell_cmd = lldb.SBPlatformShellCommand(cmd)
+ err = platform.Run(shell_cmd)
+ if err.Fail() or shell_cmd.GetStatus():
+ m = "remote_platform.RunShellCommand('%s') failed:\n" % cmd
+ m += ">>> return code: %d\n" % shell_cmd.GetStatus()
+ if err.Fail():
+ m += ">>> %s\n" % str(err).strip()
+ m += ">>> %s\n" % (shell_cmd.GetOutput() or
+ "Command generated no output.")
+ raise Exception(m)
+ return shell_cmd.GetOutput().strip()
+
+ def init_llgs_test(self, use_named_pipe=True):
+ if lldb.remote_platform:
+ # Remote platforms don't support named pipe based port negotiation
+ use_named_pipe = False
+
+ # Grab the ppid from /proc/[shell pid]/stat
+ shell_stat = self.run_shell_cmd("cat /proc/$$/stat")
+ # [pid] ([executable]) [state] [*ppid*]
+ pid = re.match(r"^\d+ \(.+\) . (\d+)", shell_stat).group(1)
+ ls_output = self.run_shell_cmd("ls -l /proc/%s/exe" % pid)
+ exe = ls_output.split()[-1]
+
+ # If the binary has been deleted, the link name has " (deleted)" appended.
+ # Remove if it's there.
+ self.debug_monitor_exe = re.sub(r' \(deleted\)$', '', exe)
+ else:
+ self.debug_monitor_exe = get_lldb_server_exe()
+ if not self.debug_monitor_exe:
+ self.skipTest("lldb-server exe not found")
+
+ self.debug_monitor_extra_args = ["gdbserver"]
+
+ if len(lldbtest_config.channels) > 0:
+ self.debug_monitor_extra_args.append("--log-file={}-server.log".format(self.log_basename))
+ self.debug_monitor_extra_args.append("--log-channels={}".format(":".join(lldbtest_config.channels)))
+
+ if use_named_pipe:
+ (self.named_pipe_path, self.named_pipe, self.named_pipe_fd) = self.create_named_pipe()
+
+ def init_debugserver_test(self, use_named_pipe=True):
+ self.debug_monitor_exe = get_debugserver_exe()
+ if not self.debug_monitor_exe:
+ self.skipTest("debugserver exe not found")
+ self.debug_monitor_extra_args = ["--log-file={}-server.log".format(self.log_basename), "--log-flags=0x800000"]
+ if use_named_pipe:
+ (self.named_pipe_path, self.named_pipe, self.named_pipe_fd) = self.create_named_pipe()
+ # The debugserver stub has a race on handling the 'k' command, so it sends an X09 right away, then sends the real X notification
+ # when the process truly dies.
+ self.stub_sends_two_stop_notifications_on_kill = True
+
+ def forward_adb_port(self, source, target, direction, device):
+ adb = [ 'adb' ] + ([ '-s', device ] if device else []) + [ direction ]
+ def remove_port_forward():
+ subprocess.call(adb + [ "--remove", "tcp:%d" % source])
+
+ subprocess.call(adb + [ "tcp:%d" % source, "tcp:%d" % target])
+ self.addTearDownHook(remove_port_forward)
+
+ def create_socket(self):
+ sock = socket.socket()
+ logger = self.logger
+
+ triple = self.dbg.GetSelectedPlatform().GetTriple()
+ if re.match(".*-.*-.*-android", triple):
+ self.forward_adb_port(self.port, self.port, "forward", self.stub_device)
+
+ connect_info = (self.stub_hostname, self.port)
+ sock.connect(connect_info)
+
+ def shutdown_socket():
+ if sock:
+ try:
+ # send the kill packet so lldb-server shuts down gracefully
+ sock.sendall(GdbRemoteTestCaseBase._GDBREMOTE_KILL_PACKET)
+ except:
+ logger.warning("failed to send kill packet to debug monitor: {}; ignoring".format(sys.exc_info()[0]))
+
+ try:
+ sock.close()
+ except:
+ logger.warning("failed to close socket to debug monitor: {}; ignoring".format(sys.exc_info()[0]))
+
+ self.addTearDownHook(shutdown_socket)
+
+ return sock
+
+ def set_inferior_startup_launch(self):
+ self._inferior_startup = self._STARTUP_LAUNCH
+
+ def set_inferior_startup_attach(self):
+ self._inferior_startup = self._STARTUP_ATTACH
+
+ def set_inferior_startup_attach_manually(self):
+ self._inferior_startup = self._STARTUP_ATTACH_MANUALLY
+
+ def get_debug_monitor_command_line_args(self, attach_pid=None):
+ if lldb.remote_platform:
+ commandline_args = self.debug_monitor_extra_args + ["*:{}".format(self.port)]
+ else:
+ commandline_args = self.debug_monitor_extra_args + ["localhost:{}".format(self.port)]
+
+ if attach_pid:
+ commandline_args += ["--attach=%d" % attach_pid]
+ if self.named_pipe_path:
+ commandline_args += ["--named-pipe", self.named_pipe_path]
+ return commandline_args
+
+ def run_platform_command(self, cmd):
+ platform = self.dbg.GetSelectedPlatform()
+ shell_command = lldb.SBPlatformShellCommand(cmd)
+ err = platform.Run(shell_command)
+ return (err, shell_command.GetOutput())
+
+ def launch_debug_monitor(self, attach_pid=None, logfile=None):
+ # Create the command line.
+ commandline_args = self.get_debug_monitor_command_line_args(attach_pid=attach_pid)
+
+ # Start the server.
+ server = self.spawnSubprocess(self.debug_monitor_exe, commandline_args, install_remote=False)
+ self.addTearDownHook(self.cleanupSubprocesses)
+ self.assertIsNotNone(server)
+
+ # If we're receiving the stub's listening port from the named pipe, do that here.
+ if self.named_pipe:
+ self.port = self.get_stub_port_from_named_socket()
+
+ return server
+
+ def connect_to_debug_monitor(self, attach_pid=None):
+ if self.named_pipe:
+ # Create the stub.
+ server = self.launch_debug_monitor(attach_pid=attach_pid)
+ self.assertIsNotNone(server)
+
+ def shutdown_debug_monitor():
+ try:
+ server.terminate()
+ except:
+ logger.warning("failed to terminate server for debug monitor: {}; ignoring".format(sys.exc_info()[0]))
+ self.addTearDownHook(shutdown_debug_monitor)
+
+ # Schedule debug monitor to be shut down during teardown.
+ logger = self.logger
+
+ # Attach to the stub and return a socket opened to it.
+ self.sock = self.create_socket()
+ return server
+
+ # We're using a random port algorithm to try not to collide with other ports,
+ # and retry a max # times.
+ attempts = 0
+ MAX_ATTEMPTS = 20
+
+ while attempts < MAX_ATTEMPTS:
+ server = self.launch_debug_monitor(attach_pid=attach_pid)
+
+ # Schedule debug monitor to be shut down during teardown.
+ logger = self.logger
+ def shutdown_debug_monitor():
+ try:
+ server.terminate()
+ except:
+ logger.warning("failed to terminate server for debug monitor: {}; ignoring".format(sys.exc_info()[0]))
+ self.addTearDownHook(shutdown_debug_monitor)
+
+ connect_attemps = 0
+ MAX_CONNECT_ATTEMPTS = 10
+
+ while connect_attemps < MAX_CONNECT_ATTEMPTS:
+ # Create a socket to talk to the server
+ try:
+ self.sock = self.create_socket()
+ return server
+ except socket.error as serr:
+ # We're only trying to handle connection refused.
+ if serr.errno != errno.ECONNREFUSED:
+ raise serr
+ time.sleep(0.5)
+ connect_attemps += 1
+
+ # We should close the server here to be safe.
+ server.terminate()
+
+ # Increment attempts.
+ print("connect to debug monitor on port %d failed, attempt #%d of %d" % (self.port, attempts + 1, MAX_ATTEMPTS))
+ attempts += 1
+
+ # And wait a random length of time before next attempt, to avoid collisions.
+ time.sleep(random.randint(1,5))
+
+ # Now grab a new port number.
+ self.port = self.get_next_port()
+
+ raise Exception("failed to create a socket to the launched debug monitor after %d tries" % attempts)
+
+ def launch_process_for_attach(self, inferior_args=None, sleep_seconds=3, exe_path=None):
+ # We're going to start a child process that the debug monitor stub can later attach to.
+ # This process needs to be started so that it just hangs around for a while. We'll
+ # have it sleep.
+ if not exe_path:
+ exe_path = os.path.abspath("a.out")
+
+ args = []
+ if inferior_args:
+ args.extend(inferior_args)
+ if sleep_seconds:
+ args.append("sleep:%d" % sleep_seconds)
+
+ inferior = self.spawnSubprocess(exe_path, args)
+ def shutdown_process_for_attach():
+ try:
+ inferior.terminate()
+ except:
+ logger.warning("failed to terminate inferior process for attach: {}; ignoring".format(sys.exc_info()[0]))
+ self.addTearDownHook(shutdown_process_for_attach)
+ return inferior
+
+ def prep_debug_monitor_and_inferior(self, inferior_args=None, inferior_sleep_seconds=3, inferior_exe_path=None):
+ """Prep the debug monitor, the inferior, and the expected packet stream.
+
+ Handle the separate cases of using the debug monitor in attach-to-inferior mode
+ and in launch-inferior mode.
+
+ For attach-to-inferior mode, the inferior process is first started, then
+ the debug monitor is started in attach to pid mode (using --attach on the
+ stub command line), and the no-ack-mode setup is appended to the packet
+ stream. The packet stream is not yet executed, ready to have more expected
+ packet entries added to it.
+
+ For launch-inferior mode, the stub is first started, then no ack mode is
+ setup on the expected packet stream, then the verified launch packets are added
+ to the expected socket stream. The packet stream is not yet executed, ready
+ to have more expected packet entries added to it.
+
+ The return value is:
+ {inferior:<inferior>, server:<server>}
+ """
+ inferior = None
+ attach_pid = None
+
+ if self._inferior_startup == self._STARTUP_ATTACH or self._inferior_startup == self._STARTUP_ATTACH_MANUALLY:
+ # Launch the process that we'll use as the inferior.
+ inferior = self.launch_process_for_attach(inferior_args=inferior_args, sleep_seconds=inferior_sleep_seconds, exe_path=inferior_exe_path)
+ self.assertIsNotNone(inferior)
+ self.assertTrue(inferior.pid > 0)
+ if self._inferior_startup == self._STARTUP_ATTACH:
+ # In this case, we want the stub to attach via the command line, so set the command line attach pid here.
+ attach_pid = inferior.pid
+
+ if self._inferior_startup == self._STARTUP_LAUNCH:
+ # Build launch args
+ if not inferior_exe_path:
+ inferior_exe_path = os.path.abspath("a.out")
+
+ if lldb.remote_platform:
+ remote_path = lldbutil.append_to_process_working_directory(os.path.basename(inferior_exe_path))
+ remote_file_spec = lldb.SBFileSpec(remote_path, False)
+ err = lldb.remote_platform.Install(lldb.SBFileSpec(inferior_exe_path, True), remote_file_spec)
+ if err.Fail():
+ raise Exception("remote_platform.Install('%s', '%s') failed: %s" % (inferior_exe_path, remote_path, err))
+ inferior_exe_path = remote_path
+
+ launch_args = [inferior_exe_path]
+ if inferior_args:
+ launch_args.extend(inferior_args)
+
+ # Launch the debug monitor stub, attaching to the inferior.
+ server = self.connect_to_debug_monitor(attach_pid=attach_pid)
+ self.assertIsNotNone(server)
+
+ # Build the expected protocol stream
+ self.add_no_ack_remote_stream()
+ if self._inferior_startup == self._STARTUP_LAUNCH:
+ self.add_verified_launch_packets(launch_args)
+
+ return {"inferior":inferior, "server":server}
+
+ def expect_socket_recv(self, sock, expected_content_regex, timeout_seconds):
+ response = ""
+ timeout_time = time.time() + timeout_seconds
+
+ while not expected_content_regex.match(response) and time.time() < timeout_time:
+ can_read, _, _ = select.select([sock], [], [], timeout_seconds)
+ if can_read and sock in can_read:
+ recv_bytes = sock.recv(4096)
+ if recv_bytes:
+ response += recv_bytes
+
+ self.assertTrue(expected_content_regex.match(response))
+
+ def expect_socket_send(self, sock, content, timeout_seconds):
+ request_bytes_remaining = content
+ timeout_time = time.time() + timeout_seconds
+
+ while len(request_bytes_remaining) > 0 and time.time() < timeout_time:
+ _, can_write, _ = select.select([], [sock], [], timeout_seconds)
+ if can_write and sock in can_write:
+ written_byte_count = sock.send(request_bytes_remaining)
+ request_bytes_remaining = request_bytes_remaining[written_byte_count:]
+ self.assertEqual(len(request_bytes_remaining), 0)
+
+ def do_handshake(self, stub_socket, timeout_seconds=5):
+ # Write the ack.
+ self.expect_socket_send(stub_socket, "+", timeout_seconds)
+
+ # Send the start no ack mode packet.
+ NO_ACK_MODE_REQUEST = "$QStartNoAckMode#b0"
+ bytes_sent = stub_socket.send(NO_ACK_MODE_REQUEST)
+ self.assertEqual(bytes_sent, len(NO_ACK_MODE_REQUEST))
+
+ # Receive the ack and "OK"
+ self.expect_socket_recv(stub_socket, re.compile(r"^\+\$OK#[0-9a-fA-F]{2}$"), timeout_seconds)
+
+ # Send the final ack.
+ self.expect_socket_send(stub_socket, "+", timeout_seconds)
+
+ def add_no_ack_remote_stream(self):
+ self.test_sequence.add_log_lines(
+ ["read packet: +",
+ "read packet: $QStartNoAckMode#b0",
+ "send packet: +",
+ "send packet: $OK#9a",
+ "read packet: +"],
+ True)
+
+ def add_verified_launch_packets(self, launch_args):
+ self.test_sequence.add_log_lines(
+ ["read packet: %s" % build_gdbremote_A_packet(launch_args),
+ "send packet: $OK#00",
+ "read packet: $qLaunchSuccess#a5",
+ "send packet: $OK#00"],
+ True)
+
+ def add_thread_suffix_request_packets(self):
+ self.test_sequence.add_log_lines(
+ ["read packet: $QThreadSuffixSupported#e4",
+ "send packet: $OK#00",
+ ], True)
+
+ def add_process_info_collection_packets(self):
+ self.test_sequence.add_log_lines(
+ ["read packet: $qProcessInfo#dc",
+ { "direction":"send", "regex":r"^\$(.+)#[0-9a-fA-F]{2}$", "capture":{1:"process_info_raw"} }],
+ True)
+
+ _KNOWN_PROCESS_INFO_KEYS = [
+ "pid",
+ "parent-pid",
+ "real-uid",
+ "real-gid",
+ "effective-uid",
+ "effective-gid",
+ "cputype",
+ "cpusubtype",
+ "ostype",
+ "triple",
+ "vendor",
+ "endian",
+ "ptrsize"
+ ]
+
+ def parse_process_info_response(self, context):
+ # Ensure we have a process info response.
+ self.assertIsNotNone(context)
+ process_info_raw = context.get("process_info_raw")
+ self.assertIsNotNone(process_info_raw)
+
+ # Pull out key:value; pairs.
+ process_info_dict = { match.group(1):match.group(2) for match in re.finditer(r"([^:]+):([^;]+);", process_info_raw) }
+
+ # Validate keys are known.
+ for (key, val) in list(process_info_dict.items()):
+ self.assertTrue(key in self._KNOWN_PROCESS_INFO_KEYS)
+ self.assertIsNotNone(val)
+
+ return process_info_dict
+
+ def add_register_info_collection_packets(self):
+ self.test_sequence.add_log_lines(
+ [ { "type":"multi_response", "query":"qRegisterInfo", "append_iteration_suffix":True,
+ "end_regex":re.compile(r"^\$(E\d+)?#[0-9a-fA-F]{2}$"),
+ "save_key":"reg_info_responses" } ],
+ True)
+
+ def parse_register_info_packets(self, context):
+ """Return an array of register info dictionaries, one per register info."""
+ reg_info_responses = context.get("reg_info_responses")
+ self.assertIsNotNone(reg_info_responses)
+
+ # Parse register infos.
+ return [parse_reg_info_response(reg_info_response) for reg_info_response in reg_info_responses]
+
+ def expect_gdbremote_sequence(self, timeout_seconds=None):
+ if not timeout_seconds:
+ timeout_seconds = self._TIMEOUT_SECONDS
+ return expect_lldb_gdbserver_replay(self, self.sock, self.test_sequence, timeout_seconds, self.logger)
+
+ _KNOWN_REGINFO_KEYS = [
+ "name",
+ "alt-name",
+ "bitsize",
+ "offset",
+ "encoding",
+ "format",
+ "set",
+ "ehframe",
+ "dwarf",
+ "generic",
+ "container-regs",
+ "invalidate-regs"
+ ]
+
+ def assert_valid_reg_info(self, reg_info):
+ # Assert we know about all the reginfo keys parsed.
+ for key in reg_info:
+ self.assertTrue(key in self._KNOWN_REGINFO_KEYS)
+
+ # Check the bare-minimum expected set of register info keys.
+ self.assertTrue("name" in reg_info)
+ self.assertTrue("bitsize" in reg_info)
+ self.assertTrue("offset" in reg_info)
+ self.assertTrue("encoding" in reg_info)
+ self.assertTrue("format" in reg_info)
+
+ def find_pc_reg_info(self, reg_infos):
+ lldb_reg_index = 0
+ for reg_info in reg_infos:
+ if ("generic" in reg_info) and (reg_info["generic"] == "pc"):
+ return (lldb_reg_index, reg_info)
+ lldb_reg_index += 1
+
+ return (None, None)
+
+ def add_lldb_register_index(self, reg_infos):
+ """Add a "lldb_register_index" key containing the 0-baed index of each reg_infos entry.
+
+ We'll use this when we want to call packets like P/p with a register index but do so
+ on only a subset of the full register info set.
+ """
+ self.assertIsNotNone(reg_infos)
+
+ reg_index = 0
+ for reg_info in reg_infos:
+ reg_info["lldb_register_index"] = reg_index
+ reg_index += 1
+
+ def add_query_memory_region_packets(self, address):
+ self.test_sequence.add_log_lines(
+ ["read packet: $qMemoryRegionInfo:{0:x}#00".format(address),
+ {"direction":"send", "regex":r"^\$(.+)#[0-9a-fA-F]{2}$", "capture":{1:"memory_region_response"} }],
+ True)
+
+ def parse_key_val_dict(self, key_val_text, allow_dupes=True):
+ self.assertIsNotNone(key_val_text)
+ kv_dict = {}
+ for match in re.finditer(r";?([^:]+):([^;]+)", key_val_text):
+ key = match.group(1)
+ val = match.group(2)
+ if key in kv_dict:
+ if allow_dupes:
+ if type(kv_dict[key]) == list:
+ kv_dict[key].append(val)
+ else:
+ # Promote to list
+ kv_dict[key] = [kv_dict[key], val]
+ else:
+ self.fail("key '{}' already present when attempting to add value '{}' (text='{}', dict={})".format(key, val, key_val_text, kv_dict))
+ else:
+ kv_dict[key] = val
+ return kv_dict
+
+ def parse_memory_region_packet(self, context):
+ # Ensure we have a context.
+ self.assertIsNotNone(context.get("memory_region_response"))
+
+ # Pull out key:value; pairs.
+ mem_region_dict = self.parse_key_val_dict(context.get("memory_region_response"))
+
+ # Validate keys are known.
+ for (key, val) in list(mem_region_dict.items()):
+ self.assertTrue(key in ["start", "size", "permissions", "error"])
+ self.assertIsNotNone(val)
+
+ # Return the dictionary of key-value pairs for the memory region.
+ return mem_region_dict
+
+ def assert_address_within_memory_region(self, test_address, mem_region_dict):
+ self.assertIsNotNone(mem_region_dict)
+ self.assertTrue("start" in mem_region_dict)
+ self.assertTrue("size" in mem_region_dict)
+
+ range_start = int(mem_region_dict["start"], 16)
+ range_size = int(mem_region_dict["size"], 16)
+ range_end = range_start + range_size
+
+ if test_address < range_start:
+ self.fail("address 0x{0:x} comes before range 0x{1:x} - 0x{2:x} (size 0x{3:x})".format(test_address, range_start, range_end, range_size))
+ elif test_address >= range_end:
+ self.fail("address 0x{0:x} comes after range 0x{1:x} - 0x{2:x} (size 0x{3:x})".format(test_address, range_start, range_end, range_size))
+
+ def add_threadinfo_collection_packets(self):
+ self.test_sequence.add_log_lines(
+ [ { "type":"multi_response", "first_query":"qfThreadInfo", "next_query":"qsThreadInfo",
+ "append_iteration_suffix":False, "end_regex":re.compile(r"^\$(l)?#[0-9a-fA-F]{2}$"),
+ "save_key":"threadinfo_responses" } ],
+ True)
+
+ def parse_threadinfo_packets(self, context):
+ """Return an array of thread ids (decimal ints), one per thread."""
+ threadinfo_responses = context.get("threadinfo_responses")
+ self.assertIsNotNone(threadinfo_responses)
+
+ thread_ids = []
+ for threadinfo_response in threadinfo_responses:
+ new_thread_infos = parse_threadinfo_response(threadinfo_response)
+ thread_ids.extend(new_thread_infos)
+ return thread_ids
+
+ def wait_for_thread_count(self, thread_count, timeout_seconds=3):
+ start_time = time.time()
+ timeout_time = start_time + timeout_seconds
+
+ actual_thread_count = 0
+ while actual_thread_count < thread_count:
+ self.reset_test_sequence()
+ self.add_threadinfo_collection_packets()
+
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ threads = self.parse_threadinfo_packets(context)
+ self.assertIsNotNone(threads)
+
+ actual_thread_count = len(threads)
+
+ if time.time() > timeout_time:
+ raise Exception(
+ 'timed out after {} seconds while waiting for theads: waiting for at least {} threads, found {}'.format(
+ timeout_seconds, thread_count, actual_thread_count))
+
+ return threads
+
+ def add_set_breakpoint_packets(self, address, do_continue=True, breakpoint_kind=1):
+ self.test_sequence.add_log_lines(
+ [# Set the breakpoint.
+ "read packet: $Z0,{0:x},{1}#00".format(address, breakpoint_kind),
+ # Verify the stub could set it.
+ "send packet: $OK#00",
+ ], True)
+
+ if (do_continue):
+ self.test_sequence.add_log_lines(
+ [# Continue the inferior.
+ "read packet: $c#63",
+ # Expect a breakpoint stop report.
+ {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} },
+ ], True)
+
+ def add_remove_breakpoint_packets(self, address, breakpoint_kind=1):
+ self.test_sequence.add_log_lines(
+ [# Remove the breakpoint.
+ "read packet: $z0,{0:x},{1}#00".format(address, breakpoint_kind),
+ # Verify the stub could unset it.
+ "send packet: $OK#00",
+ ], True)
+
+ def add_qSupported_packets(self):
+ self.test_sequence.add_log_lines(
+ ["read packet: $qSupported#00",
+ {"direction":"send", "regex":r"^\$(.*)#[0-9a-fA-F]{2}", "capture":{1: "qSupported_response"}},
+ ], True)
+
+ _KNOWN_QSUPPORTED_STUB_FEATURES = [
+ "augmented-libraries-svr4-read",
+ "PacketSize",
+ "QStartNoAckMode",
+ "QThreadSuffixSupported",
+ "QListThreadsInStopReply",
+ "qXfer:auxv:read",
+ "qXfer:libraries:read",
+ "qXfer:libraries-svr4:read",
+ "qXfer:features:read",
+ "qEcho"
+ ]
+
+ def parse_qSupported_response(self, context):
+ self.assertIsNotNone(context)
+
+ raw_response = context.get("qSupported_response")
+ self.assertIsNotNone(raw_response)
+
+ # For values with key=val, the dict key and vals are set as expected. For feature+, feature- and feature?, the
+ # +,-,? is stripped from the key and set as the value.
+ supported_dict = {}
+ for match in re.finditer(r";?([^=;]+)(=([^;]+))?", raw_response):
+ key = match.group(1)
+ val = match.group(3)
+
+ # key=val: store as is
+ if val and len(val) > 0:
+ supported_dict[key] = val
+ else:
+ if len(key) < 2:
+ raise Exception("singular stub feature is too short: must be stub_feature{+,-,?}")
+ supported_type = key[-1]
+ key = key[:-1]
+ if not supported_type in ["+", "-", "?"]:
+ raise Exception("malformed stub feature: final character {} not in expected set (+,-,?)".format(supported_type))
+ supported_dict[key] = supported_type
+ # Ensure we know the supported element
+ if not key in self._KNOWN_QSUPPORTED_STUB_FEATURES:
+ raise Exception("unknown qSupported stub feature reported: %s" % key)
+
+ return supported_dict
+
+ def run_process_then_stop(self, run_seconds=1):
+ # Tell the stub to continue.
+ self.test_sequence.add_log_lines(
+ ["read packet: $vCont;c#a8"],
+ True)
+ context = self.expect_gdbremote_sequence()
+
+ # Wait for run_seconds.
+ time.sleep(run_seconds)
+
+ # Send an interrupt, capture a T response.
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines(
+ ["read packet: {}".format(chr(3)),
+ {"direction":"send", "regex":r"^\$T([0-9a-fA-F]+)([^#]+)#[0-9a-fA-F]{2}$", "capture":{1:"stop_result"} }],
+ True)
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+ self.assertIsNotNone(context.get("stop_result"))
+
+ return context
+
+ def select_modifiable_register(self, reg_infos):
+ """Find a register that can be read/written freely."""
+ PREFERRED_REGISTER_NAMES = set(["rax",])
+
+ # First check for the first register from the preferred register name set.
+ alternative_register_index = None
+
+ self.assertIsNotNone(reg_infos)
+ for reg_info in reg_infos:
+ if ("name" in reg_info) and (reg_info["name"] in PREFERRED_REGISTER_NAMES):
+ # We found a preferred register. Use it.
+ return reg_info["lldb_register_index"]
+ if ("generic" in reg_info) and (reg_info["generic"] == "fp"):
+ # A frame pointer register will do as a register to modify temporarily.
+ alternative_register_index = reg_info["lldb_register_index"]
+
+ # We didn't find a preferred register. Return whatever alternative register
+ # we found, if any.
+ return alternative_register_index
+
+ def extract_registers_from_stop_notification(self, stop_key_vals_text):
+ self.assertIsNotNone(stop_key_vals_text)
+ kv_dict = self.parse_key_val_dict(stop_key_vals_text)
+
+ registers = {}
+ for (key, val) in list(kv_dict.items()):
+ if re.match(r"^[0-9a-fA-F]+$", key):
+ registers[int(key, 16)] = val
+ return registers
+
+ def gather_register_infos(self):
+ self.reset_test_sequence()
+ self.add_register_info_collection_packets()
+
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ reg_infos = self.parse_register_info_packets(context)
+ self.assertIsNotNone(reg_infos)
+ self.add_lldb_register_index(reg_infos)
+
+ return reg_infos
+
+ def find_generic_register_with_name(self, reg_infos, generic_name):
+ self.assertIsNotNone(reg_infos)
+ for reg_info in reg_infos:
+ if ("generic" in reg_info) and (reg_info["generic"] == generic_name):
+ return reg_info
+ return None
+
+ def decode_gdbremote_binary(self, encoded_bytes):
+ decoded_bytes = ""
+ i = 0
+ while i < len(encoded_bytes):
+ if encoded_bytes[i] == "}":
+ # Handle escaped char.
+ self.assertTrue(i + 1 < len(encoded_bytes))
+ decoded_bytes += chr(ord(encoded_bytes[i+1]) ^ 0x20)
+ i +=2
+ elif encoded_bytes[i] == "*":
+ # Handle run length encoding.
+ self.assertTrue(len(decoded_bytes) > 0)
+ self.assertTrue(i + 1 < len(encoded_bytes))
+ repeat_count = ord(encoded_bytes[i+1]) - 29
+ decoded_bytes += decoded_bytes[-1] * repeat_count
+ i += 2
+ else:
+ decoded_bytes += encoded_bytes[i]
+ i += 1
+ return decoded_bytes
+
+ def build_auxv_dict(self, endian, word_size, auxv_data):
+ self.assertIsNotNone(endian)
+ self.assertIsNotNone(word_size)
+ self.assertIsNotNone(auxv_data)
+
+ auxv_dict = {}
+
+ while len(auxv_data) > 0:
+ # Chop off key.
+ raw_key = auxv_data[:word_size]
+ auxv_data = auxv_data[word_size:]
+
+ # Chop of value.
+ raw_value = auxv_data[:word_size]
+ auxv_data = auxv_data[word_size:]
+
+ # Convert raw text from target endian.
+ key = unpack_endian_binary_string(endian, raw_key)
+ value = unpack_endian_binary_string(endian, raw_value)
+
+ # Handle ending entry.
+ if key == 0:
+ self.assertEqual(value, 0)
+ return auxv_dict
+
+ # The key should not already be present.
+ self.assertFalse(key in auxv_dict)
+ auxv_dict[key] = value
+
+ self.fail("should not reach here - implies required double zero entry not found")
+ return auxv_dict
+
+ def read_binary_data_in_chunks(self, command_prefix, chunk_length):
+ """Collect command_prefix{offset:x},{chunk_length:x} until a single 'l' or 'l' with data is returned."""
+ offset = 0
+ done = False
+ decoded_data = ""
+
+ while not done:
+ # Grab the next iteration of data.
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines([
+ "read packet: ${}{:x},{:x}:#00".format(command_prefix, offset, chunk_length),
+ {"direction":"send", "regex":re.compile(r"^\$([^E])(.*)#[0-9a-fA-F]{2}$", re.MULTILINE|re.DOTALL), "capture":{1:"response_type", 2:"content_raw"} }
+ ], True)
+
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ response_type = context.get("response_type")
+ self.assertIsNotNone(response_type)
+ self.assertTrue(response_type in ["l", "m"])
+
+ # Move offset along.
+ offset += chunk_length
+
+ # Figure out if we're done. We're done if the response type is l.
+ done = response_type == "l"
+
+ # Decode binary data.
+ content_raw = context.get("content_raw")
+ if content_raw and len(content_raw) > 0:
+ self.assertIsNotNone(content_raw)
+ decoded_data += self.decode_gdbremote_binary(content_raw)
+ return decoded_data
+
+ def add_interrupt_packets(self):
+ self.test_sequence.add_log_lines([
+ # Send the intterupt.
+ "read packet: {}".format(chr(3)),
+ # And wait for the stop notification.
+ {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})(.*)#[0-9a-fA-F]{2}$", "capture":{1:"stop_signo", 2:"stop_key_val_text" } },
+ ], True)
+
+ def parse_interrupt_packets(self, context):
+ self.assertIsNotNone(context.get("stop_signo"))
+ self.assertIsNotNone(context.get("stop_key_val_text"))
+ return (int(context["stop_signo"], 16), self.parse_key_val_dict(context["stop_key_val_text"]))
+
+ def add_QSaveRegisterState_packets(self, thread_id):
+ if thread_id:
+ # Use the thread suffix form.
+ request = "read packet: $QSaveRegisterState;thread:{:x}#00".format(thread_id)
+ else:
+ request = "read packet: $QSaveRegisterState#00"
+
+ self.test_sequence.add_log_lines([
+ request,
+ {"direction":"send", "regex":r"^\$(E?.*)#[0-9a-fA-F]{2}$", "capture":{1:"save_response" } },
+ ], True)
+
+ def parse_QSaveRegisterState_response(self, context):
+ self.assertIsNotNone(context)
+
+ save_response = context.get("save_response")
+ self.assertIsNotNone(save_response)
+
+ if len(save_response) < 1 or save_response[0] == "E":
+ # error received
+ return (False, None)
+ else:
+ return (True, int(save_response))
+
+ def add_QRestoreRegisterState_packets(self, save_id, thread_id=None):
+ if thread_id:
+ # Use the thread suffix form.
+ request = "read packet: $QRestoreRegisterState:{};thread:{:x}#00".format(save_id, thread_id)
+ else:
+ request = "read packet: $QRestoreRegisterState:{}#00".format(save_id)
+
+ self.test_sequence.add_log_lines([
+ request,
+ "send packet: $OK#00"
+ ], True)
+
+ def flip_all_bits_in_each_register_value(self, reg_infos, endian, thread_id=None):
+ self.assertIsNotNone(reg_infos)
+
+ successful_writes = 0
+ failed_writes = 0
+
+ for reg_info in reg_infos:
+ # Use the lldb register index added to the reg info. We're not necessarily
+ # working off a full set of register infos, so an inferred register index could be wrong.
+ reg_index = reg_info["lldb_register_index"]
+ self.assertIsNotNone(reg_index)
+
+ reg_byte_size = int(reg_info["bitsize"])/8
+ self.assertTrue(reg_byte_size > 0)
+
+ # Handle thread suffix.
+ if thread_id:
+ p_request = "read packet: $p{:x};thread:{:x}#00".format(reg_index, thread_id)
+ else:
+ p_request = "read packet: $p{:x}#00".format(reg_index)
+
+ # Read the existing value.
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines([
+ p_request,
+ { "direction":"send", "regex":r"^\$([0-9a-fA-F]+)#", "capture":{1:"p_response"} },
+ ], True)
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Verify the response length.
+ p_response = context.get("p_response")
+ self.assertIsNotNone(p_response)
+ initial_reg_value = unpack_register_hex_unsigned(endian, p_response)
+
+ # Flip the value by xoring with all 1s
+ all_one_bits_raw = "ff" * (int(reg_info["bitsize"]) / 8)
+ flipped_bits_int = initial_reg_value ^ int(all_one_bits_raw, 16)
+ # print("reg (index={}, name={}): val={}, flipped bits (int={}, hex={:x})".format(reg_index, reg_info["name"], initial_reg_value, flipped_bits_int, flipped_bits_int))
+
+ # Handle thread suffix for P.
+ if thread_id:
+ P_request = "read packet: $P{:x}={};thread:{:x}#00".format(reg_index, pack_register_hex(endian, flipped_bits_int, byte_size=reg_byte_size), thread_id)
+ else:
+ P_request = "read packet: $P{:x}={}#00".format(reg_index, pack_register_hex(endian, flipped_bits_int, byte_size=reg_byte_size))
+
+ # Write the flipped value to the register.
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines([
+ P_request,
+ { "direction":"send", "regex":r"^\$(OK|E[0-9a-fA-F]+)#[0-9a-fA-F]{2}", "capture":{1:"P_response"} },
+ ], True)
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Determine if the write succeeded. There are a handful of registers that can fail, or partially fail
+ # (e.g. flags, segment selectors, etc.) due to register value restrictions. Don't worry about them
+ # all flipping perfectly.
+ P_response = context.get("P_response")
+ self.assertIsNotNone(P_response)
+ if P_response == "OK":
+ successful_writes += 1
+ else:
+ failed_writes += 1
+ # print("reg (index={}, name={}) write FAILED (error: {})".format(reg_index, reg_info["name"], P_response))
+
+ # Read back the register value, ensure it matches the flipped value.
+ if P_response == "OK":
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines([
+ p_request,
+ { "direction":"send", "regex":r"^\$([0-9a-fA-F]+)#", "capture":{1:"p_response"} },
+ ], True)
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ verify_p_response_raw = context.get("p_response")
+ self.assertIsNotNone(verify_p_response_raw)
+ verify_bits = unpack_register_hex_unsigned(endian, verify_p_response_raw)
+
+ if verify_bits != flipped_bits_int:
+ # Some registers, like mxcsrmask and others, will permute what's written. Adjust succeed/fail counts.
+ # print("reg (index={}, name={}): read verify FAILED: wrote {:x}, verify read back {:x}".format(reg_index, reg_info["name"], flipped_bits_int, verify_bits))
+ successful_writes -= 1
+ failed_writes +=1
+
+ return (successful_writes, failed_writes)
+
+ def is_bit_flippable_register(self, reg_info):
+ if not reg_info:
+ return False
+ if not "set" in reg_info:
+ return False
+ if reg_info["set"] != "General Purpose Registers":
+ return False
+ if ("container-regs" in reg_info) and (len(reg_info["container-regs"]) > 0):
+ # Don't try to bit flip registers contained in another register.
+ return False
+ if re.match("^.s$", reg_info["name"]):
+ # This is a 2-letter register name that ends in "s", like a segment register.
+ # Don't try to bit flip these.
+ return False
+ if re.match("^(c|)psr$", reg_info["name"]):
+ # This is an ARM program status register; don't flip it.
+ return False
+ # Okay, this looks fine-enough.
+ return True
+
+ def read_register_values(self, reg_infos, endian, thread_id=None):
+ self.assertIsNotNone(reg_infos)
+ values = {}
+
+ for reg_info in reg_infos:
+ # We append a register index when load reg infos so we can work with subsets.
+ reg_index = reg_info.get("lldb_register_index")
+ self.assertIsNotNone(reg_index)
+
+ # Handle thread suffix.
+ if thread_id:
+ p_request = "read packet: $p{:x};thread:{:x}#00".format(reg_index, thread_id)
+ else:
+ p_request = "read packet: $p{:x}#00".format(reg_index)
+
+ # Read it with p.
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines([
+ p_request,
+ { "direction":"send", "regex":r"^\$([0-9a-fA-F]+)#", "capture":{1:"p_response"} },
+ ], True)
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Convert value from target endian to integral.
+ p_response = context.get("p_response")
+ self.assertIsNotNone(p_response)
+ self.assertTrue(len(p_response) > 0)
+ self.assertFalse(p_response[0] == "E")
+
+ values[reg_index] = unpack_register_hex_unsigned(endian, p_response)
+
+ return values
+
+ def add_vCont_query_packets(self):
+ self.test_sequence.add_log_lines([
+ "read packet: $vCont?#49",
+ {"direction":"send", "regex":r"^\$(vCont)?(.*)#[0-9a-fA-F]{2}$", "capture":{2:"vCont_query_response" } },
+ ], True)
+
+ def parse_vCont_query_response(self, context):
+ self.assertIsNotNone(context)
+ vCont_query_response = context.get("vCont_query_response")
+
+ # Handle case of no vCont support at all - in which case the capture group will be none or zero length.
+ if not vCont_query_response or len(vCont_query_response) == 0:
+ return {}
+
+ return {key:1 for key in vCont_query_response.split(";") if key and len(key) > 0}
+
+ def count_single_steps_until_true(self, thread_id, predicate, args, max_step_count=100, use_Hc_packet=True, step_instruction="s"):
+ """Used by single step test that appears in a few different contexts."""
+ single_step_count = 0
+
+ while single_step_count < max_step_count:
+ self.assertIsNotNone(thread_id)
+
+ # Build the packet for the single step instruction. We replace {thread}, if present, with the thread_id.
+ step_packet = "read packet: ${}#00".format(re.sub(r"{thread}", "{:x}".format(thread_id), step_instruction))
+ # print("\nstep_packet created: {}\n".format(step_packet))
+
+ # Single step.
+ self.reset_test_sequence()
+ if use_Hc_packet:
+ self.test_sequence.add_log_lines(
+ [# Set the continue thread.
+ "read packet: $Hc{0:x}#00".format(thread_id),
+ "send packet: $OK#00",
+ ], True)
+ self.test_sequence.add_log_lines([
+ # Single step.
+ step_packet,
+ # "read packet: $vCont;s:{0:x}#00".format(thread_id),
+ # Expect a breakpoint stop report.
+ {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} },
+ ], True)
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+ self.assertIsNotNone(context.get("stop_signo"))
+ self.assertEqual(int(context.get("stop_signo"), 16),
+ lldbutil.get_signal_number('SIGTRAP'))
+
+ single_step_count += 1
+
+ # See if the predicate is true. If so, we're done.
+ if predicate(args):
+ return (True, single_step_count)
+
+ # The predicate didn't return true within the runaway step count.
+ return (False, single_step_count)
+
+ def g_c1_c2_contents_are(self, args):
+ """Used by single step test that appears in a few different contexts."""
+ g_c1_address = args["g_c1_address"]
+ g_c2_address = args["g_c2_address"]
+ expected_g_c1 = args["expected_g_c1"]
+ expected_g_c2 = args["expected_g_c2"]
+
+ # Read g_c1 and g_c2 contents.
+ self.reset_test_sequence()
+ self.test_sequence.add_log_lines(
+ ["read packet: $m{0:x},{1:x}#00".format(g_c1_address, 1),
+ {"direction":"send", "regex":r"^\$(.+)#[0-9a-fA-F]{2}$", "capture":{1:"g_c1_contents"} },
+ "read packet: $m{0:x},{1:x}#00".format(g_c2_address, 1),
+ {"direction":"send", "regex":r"^\$(.+)#[0-9a-fA-F]{2}$", "capture":{1:"g_c2_contents"} }],
+ True)
+
+ # Run the packet stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Check if what we read from inferior memory is what we are expecting.
+ self.assertIsNotNone(context.get("g_c1_contents"))
+ self.assertIsNotNone(context.get("g_c2_contents"))
+
+ return (context.get("g_c1_contents").decode("hex") == expected_g_c1) and (context.get("g_c2_contents").decode("hex") == expected_g_c2)
+
+ def single_step_only_steps_one_instruction(self, use_Hc_packet=True, step_instruction="s"):
+ """Used by single step test that appears in a few different contexts."""
+ # Start up the inferior.
+ procs = self.prep_debug_monitor_and_inferior(
+ inferior_args=["get-code-address-hex:swap_chars", "get-data-address-hex:g_c1", "get-data-address-hex:g_c2", "sleep:1", "call-function:swap_chars", "sleep:5"])
+
+ # Run the process
+ self.test_sequence.add_log_lines(
+ [# Start running after initial stop.
+ "read packet: $c#63",
+ # Match output line that prints the memory address of the function call entry point.
+ # Note we require launch-only testing so we can get inferior otuput.
+ { "type":"output_match", "regex":r"^code address: 0x([0-9a-fA-F]+)\r\ndata address: 0x([0-9a-fA-F]+)\r\ndata address: 0x([0-9a-fA-F]+)\r\n$",
+ "capture":{ 1:"function_address", 2:"g_c1_address", 3:"g_c2_address"} },
+ # Now stop the inferior.
+ "read packet: {}".format(chr(3)),
+ # And wait for the stop notification.
+ {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} }],
+ True)
+
+ # Run the packet stream.
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Grab the main thread id.
+ self.assertIsNotNone(context.get("stop_thread_id"))
+ main_thread_id = int(context.get("stop_thread_id"), 16)
+
+ # Grab the function address.
+ self.assertIsNotNone(context.get("function_address"))
+ function_address = int(context.get("function_address"), 16)
+
+ # Grab the data addresses.
+ self.assertIsNotNone(context.get("g_c1_address"))
+ g_c1_address = int(context.get("g_c1_address"), 16)
+
+ self.assertIsNotNone(context.get("g_c2_address"))
+ g_c2_address = int(context.get("g_c2_address"), 16)
+
+ # Set a breakpoint at the given address.
+ if self.getArchitecture() == "arm":
+ # TODO: Handle case when setting breakpoint in thumb code
+ BREAKPOINT_KIND = 4
+ else:
+ BREAKPOINT_KIND = 1
+ self.reset_test_sequence()
+ self.add_set_breakpoint_packets(function_address, do_continue=True, breakpoint_kind=BREAKPOINT_KIND)
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Remove the breakpoint.
+ self.reset_test_sequence()
+ self.add_remove_breakpoint_packets(function_address, breakpoint_kind=BREAKPOINT_KIND)
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ # Verify g_c1 and g_c2 match expected initial state.
+ args = {}
+ args["g_c1_address"] = g_c1_address
+ args["g_c2_address"] = g_c2_address
+ args["expected_g_c1"] = "0"
+ args["expected_g_c2"] = "1"
+
+ self.assertTrue(self.g_c1_c2_contents_are(args))
+
+ # Verify we take only a small number of steps to hit the first state. Might need to work through function entry prologue code.
+ args["expected_g_c1"] = "1"
+ args["expected_g_c2"] = "1"
+ (state_reached, step_count) = self.count_single_steps_until_true(main_thread_id, self.g_c1_c2_contents_are, args, max_step_count=25, use_Hc_packet=use_Hc_packet, step_instruction=step_instruction)
+ self.assertTrue(state_reached)
+
+ # Verify we hit the next state.
+ args["expected_g_c1"] = "1"
+ args["expected_g_c2"] = "0"
+ (state_reached, step_count) = self.count_single_steps_until_true(main_thread_id, self.g_c1_c2_contents_are, args, max_step_count=5, use_Hc_packet=use_Hc_packet, step_instruction=step_instruction)
+ self.assertTrue(state_reached)
+ expected_step_count = 1
+ arch = self.getArchitecture()
+
+ #MIPS required "3" (ADDIU, SB, LD) machine instructions for updation of variable value
+ if re.match("mips",arch):
+ expected_step_count = 3
+ self.assertEqual(step_count, expected_step_count)
+
+ # Verify we hit the next state.
+ args["expected_g_c1"] = "0"
+ args["expected_g_c2"] = "0"
+ (state_reached, step_count) = self.count_single_steps_until_true(main_thread_id, self.g_c1_c2_contents_are, args, max_step_count=5, use_Hc_packet=use_Hc_packet, step_instruction=step_instruction)
+ self.assertTrue(state_reached)
+ self.assertEqual(step_count, expected_step_count)
+
+ # Verify we hit the next state.
+ args["expected_g_c1"] = "0"
+ args["expected_g_c2"] = "1"
+ (state_reached, step_count) = self.count_single_steps_until_true(main_thread_id, self.g_c1_c2_contents_are, args, max_step_count=5, use_Hc_packet=use_Hc_packet, step_instruction=step_instruction)
+ self.assertTrue(state_reached)
+ self.assertEqual(step_count, expected_step_count)
+
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/Makefile b/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/Makefile
new file mode 100644
index 000000000000..a47e2797fd84
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/Makefile
@@ -0,0 +1,8 @@
+LEVEL = ../../../make
+
+CFLAGS_EXTRAS += -D__STDC_LIMIT_MACROS -D__STDC_FORMAT_MACROS -std=c++11
+# LD_EXTRAS := -lpthread
+CXX_SOURCES := main.cpp
+MAKE_DSYM :=NO
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteAbort.py b/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteAbort.py
new file mode 100644
index 000000000000..d13433252e12
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteAbort.py
@@ -0,0 +1,42 @@
+from __future__ import print_function
+
+
+
+import gdbremote_testcase
+import signal
+from lldbsuite.test.lldbtest import *
+
+class TestGdbRemoteAbort(gdbremote_testcase.GdbRemoteTestCaseBase):
+ mydir = TestBase.compute_mydir(__file__)
+
+ def inferior_abort_received(self):
+ procs = self.prep_debug_monitor_and_inferior(inferior_args=["abort"])
+ self.assertIsNotNone(procs)
+
+ self.test_sequence.add_log_lines([
+ "read packet: $vCont;c#a8",
+ {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2}).*#[0-9a-fA-F]{2}$", "capture":{ 1:"hex_exit_code"} },
+ ], True)
+
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ hex_exit_code = context.get("hex_exit_code")
+ self.assertIsNotNone(hex_exit_code)
+ self.assertEqual(int(hex_exit_code, 16),
+ lldbutil.get_signal_number('SIGABRT'))
+
+ @debugserver_test
+ def test_inferior_abort_received_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.inferior_abort_received()
+
+ @llgs_test
+ # std::abort() on <= API 16 raises SIGSEGV - b.android.com/179836
+ @expectedFailureAndroid(api_levels=list(range(16 + 1)))
+ def test_inferior_abort_received_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.inferior_abort_received()
+
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteSegFault.py b/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteSegFault.py
new file mode 100644
index 000000000000..6618d8f75fc9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/TestGdbRemoteSegFault.py
@@ -0,0 +1,40 @@
+from __future__ import print_function
+
+
+
+import gdbremote_testcase
+import signal
+from lldbsuite.test.lldbtest import *
+
+class TestGdbRemoteSegFault(gdbremote_testcase.GdbRemoteTestCaseBase):
+ mydir = TestBase.compute_mydir(__file__)
+
+ GDB_REMOTE_STOP_CODE_BAD_ACCESS = 0x91
+
+ def inferior_seg_fault_received(self, expected_signo):
+ procs = self.prep_debug_monitor_and_inferior(inferior_args=["segfault"])
+ self.assertIsNotNone(procs)
+
+ self.test_sequence.add_log_lines([
+ "read packet: $vCont;c#a8",
+ {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2}).*#[0-9a-fA-F]{2}$", "capture":{ 1:"hex_exit_code"} },
+ ], True)
+
+ context = self.expect_gdbremote_sequence()
+ self.assertIsNotNone(context)
+
+ hex_exit_code = context.get("hex_exit_code")
+ self.assertIsNotNone(hex_exit_code)
+ self.assertEqual(int(hex_exit_code, 16), expected_signo)
+
+ @debugserver_test
+ def test_inferior_seg_fault_received_debugserver(self):
+ self.init_debugserver_test()
+ self.build()
+ self.inferior_seg_fault_received(self.GDB_REMOTE_STOP_CODE_BAD_ACCESS)
+
+ @llgs_test
+ def test_inferior_seg_fault_received_llgs(self):
+ self.init_llgs_test()
+ self.build()
+ self.inferior_seg_fault_received(lldbutil.get_signal_number('SIGSEGV'))
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/main.cpp b/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/main.cpp
new file mode 100644
index 000000000000..69d60071aa45
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/inferior-crash/main.cpp
@@ -0,0 +1,39 @@
+#include <cstdlib>
+#include <cstring>
+#include <iostream>
+
+namespace
+{
+ const char *const SEGFAULT_COMMAND = "segfault";
+ const char *const ABORT_COMMAND = "abort";
+}
+
+int main (int argc, char **argv)
+{
+ if (argc < 2)
+ {
+ std::cout << "expected at least one command provided on the command line" << std::endl;
+ }
+
+ // Process command line args.
+ for (int i = 1; i < argc; ++i)
+ {
+ const char *const command = argv[i];
+ if (std::strstr (command, SEGFAULT_COMMAND))
+ {
+ // Perform a null pointer access.
+ int *const null_int_ptr = nullptr;
+ *null_int_ptr = 0xDEAD;
+ }
+ else if (std::strstr (command, ABORT_COMMAND))
+ {
+ std::abort();
+ }
+ else
+ {
+ std::cout << "Unsupported command: " << command << std::endl;
+ }
+ }
+
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/lldbgdbserverutils.py b/packages/Python/lldbsuite/test/tools/lldb-server/lldbgdbserverutils.py
new file mode 100644
index 000000000000..c0ea841e2a03
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/lldbgdbserverutils.py
@@ -0,0 +1,843 @@
+"""Module for supporting unit testing of the lldb-server debug monitor exe.
+"""
+
+from __future__ import print_function
+
+
+
+import os
+import os.path
+import platform
+import re
+import six
+import socket_packet_pump
+import subprocess
+import time
+from lldbsuite.test.lldbtest import *
+
+from six.moves import queue
+
+def _get_debug_monitor_from_lldb(lldb_exe, debug_monitor_basename):
+ """Return the debug monitor exe path given the lldb exe path.
+
+ This method attempts to construct a valid debug monitor exe name
+ from a given lldb exe name. It will return None if the synthesized
+ debug monitor name is not found to exist.
+
+ The debug monitor exe path is synthesized by taking the directory
+ of the lldb exe, and replacing the portion of the base name that
+ matches "lldb" (case insensitive) and replacing with the value of
+ debug_monitor_basename.
+
+ Args:
+ lldb_exe: the path to an lldb executable.
+
+ debug_monitor_basename: the base name portion of the debug monitor
+ that will replace 'lldb'.
+
+ Returns:
+ A path to the debug monitor exe if it is found to exist; otherwise,
+ returns None.
+
+ """
+ if not lldb_exe:
+ return None
+
+ exe_dir = os.path.dirname(lldb_exe)
+ exe_base = os.path.basename(lldb_exe)
+
+ # we'll rebuild the filename by replacing lldb with
+ # the debug monitor basename, keeping any prefix or suffix in place.
+ regex = re.compile(r"lldb", re.IGNORECASE)
+ new_base = regex.sub(debug_monitor_basename, exe_base)
+
+ debug_monitor_exe = os.path.join(exe_dir, new_base)
+ if os.path.exists(debug_monitor_exe):
+ return debug_monitor_exe
+
+ new_base = regex.sub( 'LLDB.framework/Versions/A/Resources/' + debug_monitor_basename, exe_base)
+ debug_monitor_exe = os.path.join(exe_dir, new_base)
+ if os.path.exists(debug_monitor_exe):
+ return debug_monitor_exe
+
+ return None
+
+
+def get_lldb_server_exe():
+ """Return the lldb-server exe path.
+
+ Returns:
+ A path to the lldb-server exe if it is found to exist; otherwise,
+ returns None.
+ """
+ if "LLDB_DEBUGSERVER_PATH" in os.environ:
+ return os.environ["LLDB_DEBUGSERVER_PATH"]
+
+ return _get_debug_monitor_from_lldb(lldbtest_config.lldbExec, "lldb-server")
+
+def get_debugserver_exe():
+ """Return the debugserver exe path.
+
+ Returns:
+ A path to the debugserver exe if it is found to exist; otherwise,
+ returns None.
+ """
+ if "LLDB_DEBUGSERVER_PATH" in os.environ:
+ return os.environ["LLDB_DEBUGSERVER_PATH"]
+
+ return _get_debug_monitor_from_lldb(lldbtest_config.lldbExec, "debugserver")
+
+_LOG_LINE_REGEX = re.compile(r'^(lldb-server|debugserver)\s+<\s*(\d+)>' +
+ '\s+(read|send)\s+packet:\s+(.+)$')
+
+
+def _is_packet_lldb_gdbserver_input(packet_type, llgs_input_is_read):
+ """Return whether a given packet is input for lldb-gdbserver.
+
+ Args:
+ packet_type: a string indicating 'send' or 'receive', from a
+ gdbremote packet protocol log.
+
+ llgs_input_is_read: true if lldb-gdbserver input (content sent to
+ lldb-gdbserver) is listed as 'read' or 'send' in the packet
+ log entry.
+
+ Returns:
+ True if the packet should be considered input for lldb-gdbserver; False
+ otherwise.
+ """
+ if packet_type == 'read':
+ # when llgs is the read side, then a read packet is meant for
+ # input to llgs (when captured from the llgs/debugserver exe).
+ return llgs_input_is_read
+ elif packet_type == 'send':
+ # when llgs is the send side, then a send packet is meant to
+ # be input to llgs (when captured from the lldb exe).
+ return not llgs_input_is_read
+ else:
+ # don't understand what type of packet this is
+ raise "Unknown packet type: {}".format(packet_type)
+
+
+def handle_O_packet(context, packet_contents, logger):
+ """Handle O packets."""
+ if (not packet_contents) or (len(packet_contents) < 1):
+ return False
+ elif packet_contents[0] != "O":
+ return False
+ elif packet_contents == "OK":
+ return False
+
+ new_text = gdbremote_hex_decode_string(packet_contents[1:])
+ context["O_content"] += new_text
+ context["O_count"] += 1
+
+ if logger:
+ logger.debug("text: new \"{}\", cumulative: \"{}\"".format(new_text, context["O_content"]))
+
+ return True
+
+_STRIP_CHECKSUM_REGEX = re.compile(r'#[0-9a-fA-F]{2}$')
+_STRIP_COMMAND_PREFIX_REGEX = re.compile(r"^\$")
+_STRIP_COMMAND_PREFIX_M_REGEX = re.compile(r"^\$m")
+
+
+def assert_packets_equal(asserter, actual_packet, expected_packet):
+ # strip off the checksum digits of the packet. When we're in
+ # no-ack mode, the # checksum is ignored, and should not be cause
+ # for a mismatched packet.
+ actual_stripped = _STRIP_CHECKSUM_REGEX.sub('', actual_packet)
+ expected_stripped = _STRIP_CHECKSUM_REGEX.sub('', expected_packet)
+ asserter.assertEqual(actual_stripped, expected_stripped)
+
+def expect_lldb_gdbserver_replay(
+ asserter,
+ sock,
+ test_sequence,
+ timeout_seconds,
+ logger=None):
+ """Replay socket communication with lldb-gdbserver and verify responses.
+
+ Args:
+ asserter: the object providing assertEqual(first, second, msg=None), e.g. TestCase instance.
+
+ sock: the TCP socket connected to the lldb-gdbserver exe.
+
+ test_sequence: a GdbRemoteTestSequence instance that describes
+ the messages sent to the gdb remote and the responses
+ expected from it.
+
+ timeout_seconds: any response taking more than this number of
+ seconds will cause an exception to be raised.
+
+ logger: a Python logger instance.
+
+ Returns:
+ The context dictionary from running the given gdbremote
+ protocol sequence. This will contain any of the capture
+ elements specified to any GdbRemoteEntry instances in
+ test_sequence.
+
+ The context will also contain an entry, context["O_content"]
+ which contains the text from the inferior received via $O
+ packets. $O packets should not attempt to be matched
+ directly since they are not entirely deterministic as to
+ how many arrive and how much text is in each one.
+
+ context["O_count"] will contain an integer of the number of
+ O packets received.
+ """
+
+ # Ensure we have some work to do.
+ if len(test_sequence.entries) < 1:
+ return {}
+
+ context = {"O_count":0, "O_content":""}
+ with socket_packet_pump.SocketPacketPump(sock, logger) as pump:
+ # Grab the first sequence entry.
+ sequence_entry = test_sequence.entries.pop(0)
+
+ # While we have an active sequence entry, send messages
+ # destined for the stub and collect/match/process responses
+ # expected from the stub.
+ while sequence_entry:
+ if sequence_entry.is_send_to_remote():
+ # This is an entry to send to the remote debug monitor.
+ send_packet = sequence_entry.get_send_packet()
+ if logger:
+ if len(send_packet) == 1 and send_packet[0] == chr(3):
+ packet_desc = "^C"
+ else:
+ packet_desc = send_packet
+ logger.info("sending packet to remote: {}".format(packet_desc))
+ sock.sendall(send_packet)
+ else:
+ # This is an entry expecting to receive content from the remote debug monitor.
+
+ # We'll pull from (and wait on) the queue appropriate for the type of matcher.
+ # We keep separate queues for process output (coming from non-deterministic
+ # $O packet division) and for all other packets.
+ if sequence_entry.is_output_matcher():
+ try:
+ # Grab next entry from the output queue.
+ content = pump.output_queue().get(True, timeout_seconds)
+ except queue.Empty:
+ if logger:
+ logger.warning("timeout waiting for stub output (accumulated output:{})".format(pump.get_accumulated_output()))
+ raise Exception("timed out while waiting for output match (accumulated output: {})".format(pump.get_accumulated_output()))
+ else:
+ try:
+ content = pump.packet_queue().get(True, timeout_seconds)
+ except queue.Empty:
+ if logger:
+ logger.warning("timeout waiting for packet match (receive buffer: {})".format(pump.get_receive_buffer()))
+ raise Exception("timed out while waiting for packet match (receive buffer: {})".format(pump.get_receive_buffer()))
+
+ # Give the sequence entry the opportunity to match the content.
+ # Output matchers might match or pass after more output accumulates.
+ # Other packet types generally must match.
+ asserter.assertIsNotNone(content)
+ context = sequence_entry.assert_match(asserter, content, context=context)
+
+ # Move on to next sequence entry as needed. Some sequence entries support executing multiple
+ # times in different states (for looping over query/response packets).
+ if sequence_entry.is_consumed():
+ if len(test_sequence.entries) > 0:
+ sequence_entry = test_sequence.entries.pop(0)
+ else:
+ sequence_entry = None
+
+ # Fill in the O_content entries.
+ context["O_count"] = 1
+ context["O_content"] = pump.get_accumulated_output()
+
+ return context
+
+def gdbremote_hex_encode_string(str):
+ output = ''
+ for c in str:
+ output += '{0:02x}'.format(ord(c))
+ return output
+
+def gdbremote_hex_decode_string(str):
+ return str.decode("hex")
+
+def gdbremote_packet_encode_string(str):
+ checksum = 0
+ for c in str:
+ checksum += ord(c)
+ return '$' + str + '#{0:02x}'.format(checksum % 256)
+
+def build_gdbremote_A_packet(args_list):
+ """Given a list of args, create a properly-formed $A packet containing each arg.
+ """
+ payload = "A"
+
+ # build the arg content
+ arg_index = 0
+ for arg in args_list:
+ # Comma-separate the args.
+ if arg_index > 0:
+ payload += ','
+
+ # Hex-encode the arg.
+ hex_arg = gdbremote_hex_encode_string(arg)
+
+ # Build the A entry.
+ payload += "{},{},{}".format(len(hex_arg), arg_index, hex_arg)
+
+ # Next arg index, please.
+ arg_index += 1
+
+ # return the packetized payload
+ return gdbremote_packet_encode_string(payload)
+
+
+def parse_reg_info_response(response_packet):
+ if not response_packet:
+ raise Exception("response_packet cannot be None")
+
+ # Strip off prefix $ and suffix #xx if present.
+ response_packet = _STRIP_COMMAND_PREFIX_REGEX.sub("", response_packet)
+ response_packet = _STRIP_CHECKSUM_REGEX.sub("", response_packet)
+
+ # Build keyval pairs
+ values = {}
+ for kv in response_packet.split(";"):
+ if len(kv) < 1:
+ continue
+ (key, val) = kv.split(':')
+ values[key] = val
+
+ return values
+
+
+def parse_threadinfo_response(response_packet):
+ if not response_packet:
+ raise Exception("response_packet cannot be None")
+
+ # Strip off prefix $ and suffix #xx if present.
+ response_packet = _STRIP_COMMAND_PREFIX_M_REGEX.sub("", response_packet)
+ response_packet = _STRIP_CHECKSUM_REGEX.sub("", response_packet)
+
+ # Return list of thread ids
+ return [int(thread_id_hex,16) for thread_id_hex in response_packet.split(",") if len(thread_id_hex) > 0]
+
+def unpack_endian_binary_string(endian, value_string):
+ """Unpack a gdb-remote binary (post-unescaped, i.e. not escaped) response to an unsigned int given endianness of the inferior."""
+ if not endian:
+ raise Exception("endian cannot be None")
+ if not value_string or len(value_string) < 1:
+ raise Exception("value_string cannot be None or empty")
+
+ if endian == 'little':
+ value = 0
+ i = 0
+ while len(value_string) > 0:
+ value += (ord(value_string[0]) << i)
+ value_string = value_string[1:]
+ i += 8
+ return value
+ elif endian == 'big':
+ value = 0
+ while len(value_string) > 0:
+ value = (value << 8) + ord(value_string[0])
+ value_string = value_string[1:]
+ return value
+ else:
+ # pdp is valid but need to add parse code once needed.
+ raise Exception("unsupported endian:{}".format(endian))
+
+def unpack_register_hex_unsigned(endian, value_string):
+ """Unpack a gdb-remote $p-style response to an unsigned int given endianness of inferior."""
+ if not endian:
+ raise Exception("endian cannot be None")
+ if not value_string or len(value_string) < 1:
+ raise Exception("value_string cannot be None or empty")
+
+ if endian == 'little':
+ value = 0
+ i = 0
+ while len(value_string) > 0:
+ value += (int(value_string[0:2], 16) << i)
+ value_string = value_string[2:]
+ i += 8
+ return value
+ elif endian == 'big':
+ return int(value_string, 16)
+ else:
+ # pdp is valid but need to add parse code once needed.
+ raise Exception("unsupported endian:{}".format(endian))
+
+def pack_register_hex(endian, value, byte_size=None):
+ """Unpack a gdb-remote $p-style response to an unsigned int given endianness of inferior."""
+ if not endian:
+ raise Exception("endian cannot be None")
+
+ if endian == 'little':
+ # Create the litt-endian return value.
+ retval = ""
+ while value != 0:
+ retval = retval + "{:02x}".format(value & 0xff)
+ value = value >> 8
+ if byte_size:
+ # Add zero-fill to the right/end (MSB side) of the value.
+ retval += "00" * (byte_size - len(retval)/2)
+ return retval
+
+ elif endian == 'big':
+ retval = value.encode("hex")
+ if byte_size:
+ # Add zero-fill to the left/front (MSB side) of the value.
+ retval = ("00" * (byte_size - len(retval)/2)) + retval
+ return retval
+
+ else:
+ # pdp is valid but need to add parse code once needed.
+ raise Exception("unsupported endian:{}".format(endian))
+
+class GdbRemoteEntryBase(object):
+ def is_output_matcher(self):
+ return False
+
+class GdbRemoteEntry(GdbRemoteEntryBase):
+
+ def __init__(self, is_send_to_remote=True, exact_payload=None, regex=None, capture=None, expect_captures=None):
+ """Create an entry representing one piece of the I/O to/from a gdb remote debug monitor.
+
+ Args:
+
+ is_send_to_remote: True if this entry is a message to be
+ sent to the gdbremote debug monitor; False if this
+ entry represents text to be matched against the reply
+ from the gdbremote debug monitor.
+
+ exact_payload: if not None, then this packet is an exact
+ send (when sending to the remote) or an exact match of
+ the response from the gdbremote. The checksums are
+ ignored on exact match requests since negotiation of
+ no-ack makes the checksum content essentially
+ undefined.
+
+ regex: currently only valid for receives from gdbremote.
+ When specified (and only if exact_payload is None),
+ indicates the gdbremote response must match the given
+ regex. Match groups in the regex can be used for two
+ different purposes: saving the match (see capture
+ arg), or validating that a match group matches a
+ previously established value (see expect_captures). It
+ is perfectly valid to have just a regex arg and to
+ specify neither capture or expect_captures args. This
+ arg only makes sense if exact_payload is not
+ specified.
+
+ capture: if specified, is a dictionary of regex match
+ group indices (should start with 1) to variable names
+ that will store the capture group indicated by the
+ index. For example, {1:"thread_id"} will store capture
+ group 1's content in the context dictionary where
+ "thread_id" is the key and the match group value is
+ the value. The value stored off can be used later in a
+ expect_captures expression. This arg only makes sense
+ when regex is specified.
+
+ expect_captures: if specified, is a dictionary of regex
+ match group indices (should start with 1) to variable
+ names, where the match group should match the value
+ existing in the context at the given variable name.
+ For example, {2:"thread_id"} indicates that the second
+ match group must match the value stored under the
+ context's previously stored "thread_id" key. This arg
+ only makes sense when regex is specified.
+ """
+ self._is_send_to_remote = is_send_to_remote
+ self.exact_payload = exact_payload
+ self.regex = regex
+ self.capture = capture
+ self.expect_captures = expect_captures
+
+ def is_send_to_remote(self):
+ return self._is_send_to_remote
+
+ def is_consumed(self):
+ # For now, all packets are consumed after first use.
+ return True
+
+ def get_send_packet(self):
+ if not self.is_send_to_remote():
+ raise Exception("get_send_packet() called on GdbRemoteEntry that is not a send-to-remote packet")
+ if not self.exact_payload:
+ raise Exception("get_send_packet() called on GdbRemoteEntry but it doesn't have an exact payload")
+ return self.exact_payload
+
+ def _assert_exact_payload_match(self, asserter, actual_packet):
+ assert_packets_equal(asserter, actual_packet, self.exact_payload)
+ return None
+
+ def _assert_regex_match(self, asserter, actual_packet, context):
+ # Ensure the actual packet matches from the start of the actual packet.
+ match = self.regex.match(actual_packet)
+ if not match:
+ asserter.fail("regex '{}' failed to match against content '{}'".format(self.regex.pattern, actual_packet))
+
+ if self.capture:
+ # Handle captures.
+ for group_index, var_name in list(self.capture.items()):
+ capture_text = match.group(group_index)
+ # It is okay for capture text to be None - which it will be if it is a group that can match nothing.
+ # The user must be okay with it since the regex itself matched above.
+ context[var_name] = capture_text
+
+ if self.expect_captures:
+ # Handle comparing matched groups to context dictionary entries.
+ for group_index, var_name in list(self.expect_captures.items()):
+ capture_text = match.group(group_index)
+ if not capture_text:
+ raise Exception("No content to expect for group index {}".format(group_index))
+ asserter.assertEqual(capture_text, context[var_name])
+
+ return context
+
+ def assert_match(self, asserter, actual_packet, context=None):
+ # This only makes sense for matching lines coming from the
+ # remote debug monitor.
+ if self.is_send_to_remote():
+ raise Exception("Attempted to match a packet being sent to the remote debug monitor, doesn't make sense.")
+
+ # Create a new context if needed.
+ if not context:
+ context = {}
+
+ # If this is an exact payload, ensure they match exactly,
+ # ignoring the packet checksum which is optional for no-ack
+ # mode.
+ if self.exact_payload:
+ self._assert_exact_payload_match(asserter, actual_packet)
+ return context
+ elif self.regex:
+ return self._assert_regex_match(asserter, actual_packet, context)
+ else:
+ raise Exception("Don't know how to match a remote-sent packet when exact_payload isn't specified.")
+
+class MultiResponseGdbRemoteEntry(GdbRemoteEntryBase):
+ """Represents a query/response style packet.
+
+ Assumes the first item is sent to the gdb remote.
+ An end sequence regex indicates the end of the query/response
+ packet sequence. All responses up through (but not including) the
+ end response are stored in a context variable.
+
+ Settings accepted from params:
+
+ next_query or query: required. The typical query packet without the $ prefix or #xx suffix.
+ If there is a special first packet to start the iteration query, see the
+ first_query key.
+
+ first_query: optional. If the first query requires a special query command, specify
+ it with this key. Do not specify the $ prefix or #xx suffix.
+
+ append_iteration_suffix: defaults to False. Specify True if the 0-based iteration
+ index should be appended as a suffix to the command. e.g. qRegisterInfo with
+ this key set true will generate query packets of qRegisterInfo0, qRegisterInfo1,
+ etc.
+
+ end_regex: required. Specifies a compiled regex object that will match the full text
+ of any response that signals an end to the iteration. It must include the
+ initial $ and ending #xx and must match the whole packet.
+
+ save_key: required. Specifies the key within the context where an array will be stored.
+ Each packet received from the gdb remote that does not match the end_regex will get
+ appended to the array stored within the context at that key.
+
+ runaway_response_count: optional. Defaults to 10000. If this many responses are retrieved,
+ assume there is something wrong with either the response collection or the ending
+ detection regex and throw an exception.
+ """
+ def __init__(self, params):
+ self._next_query = params.get("next_query", params.get("query"))
+ if not self._next_query:
+ raise "either next_query or query key must be specified for MultiResponseGdbRemoteEntry"
+
+ self._first_query = params.get("first_query", self._next_query)
+ self._append_iteration_suffix = params.get("append_iteration_suffix", False)
+ self._iteration = 0
+ self._end_regex = params["end_regex"]
+ self._save_key = params["save_key"]
+ self._runaway_response_count = params.get("runaway_response_count", 10000)
+ self._is_send_to_remote = True
+ self._end_matched = False
+
+ def is_send_to_remote(self):
+ return self._is_send_to_remote
+
+ def get_send_packet(self):
+ if not self.is_send_to_remote():
+ raise Exception("get_send_packet() called on MultiResponseGdbRemoteEntry that is not in the send state")
+ if self._end_matched:
+ raise Exception("get_send_packet() called on MultiResponseGdbRemoteEntry but end of query/response sequence has already been seen.")
+
+ # Choose the first or next query for the base payload.
+ if self._iteration == 0 and self._first_query:
+ payload = self._first_query
+ else:
+ payload = self._next_query
+
+ # Append the suffix as needed.
+ if self._append_iteration_suffix:
+ payload += "%x" % self._iteration
+
+ # Keep track of the iteration.
+ self._iteration += 1
+
+ # Now that we've given the query packet, flip the mode to receive/match.
+ self._is_send_to_remote = False
+
+ # Return the result, converted to packet form.
+ return gdbremote_packet_encode_string(payload)
+
+ def is_consumed(self):
+ return self._end_matched
+
+ def assert_match(self, asserter, actual_packet, context=None):
+ # This only makes sense for matching lines coming from the remote debug monitor.
+ if self.is_send_to_remote():
+ raise Exception("assert_match() called on MultiResponseGdbRemoteEntry but state is set to send a query packet.")
+
+ if self._end_matched:
+ raise Exception("assert_match() called on MultiResponseGdbRemoteEntry but end of query/response sequence has already been seen.")
+
+ # Set up a context as needed.
+ if not context:
+ context = {}
+
+ # Check if the packet matches the end condition.
+ match = self._end_regex.match(actual_packet)
+ if match:
+ # We're done iterating.
+ self._end_matched = True
+ return context
+
+ # Not done iterating - save the packet.
+ context[self._save_key] = context.get(self._save_key, [])
+ context[self._save_key].append(actual_packet)
+
+ # Check for a runaway response cycle.
+ if len(context[self._save_key]) >= self._runaway_response_count:
+ raise Exception("runaway query/response cycle detected: %d responses captured so far. Last response: %s" %
+ (len(context[self._save_key]), context[self._save_key][-1]))
+
+ # Flip the mode to send for generating the query.
+ self._is_send_to_remote = True
+ return context
+
+class MatchRemoteOutputEntry(GdbRemoteEntryBase):
+ """Waits for output from the debug monitor to match a regex or time out.
+
+ This entry type tries to match each time new gdb remote output is accumulated
+ using a provided regex. If the output does not match the regex within the
+ given timeframe, the command fails the playback session. If the regex does
+ match, any capture fields are recorded in the context.
+
+ Settings accepted from params:
+
+ regex: required. Specifies a compiled regex object that must either succeed
+ with re.match or re.search (see regex_mode below) within the given timeout
+ (see timeout_seconds below) or cause the playback to fail.
+
+ regex_mode: optional. Available values: "match" or "search". If "match", the entire
+ stub output as collected so far must match the regex. If search, then the regex
+ must match starting somewhere within the output text accumulated thus far.
+ Default: "match" (i.e. the regex must match the entirety of the accumulated output
+ buffer, so unexpected text will generally fail the match).
+
+ capture: optional. If specified, is a dictionary of regex match group indices (should start
+ with 1) to variable names that will store the capture group indicated by the
+ index. For example, {1:"thread_id"} will store capture group 1's content in the
+ context dictionary where "thread_id" is the key and the match group value is
+ the value. The value stored off can be used later in a expect_captures expression.
+ This arg only makes sense when regex is specified.
+ """
+ def __init__(self, regex=None, regex_mode="match", capture=None):
+ self._regex = regex
+ self._regex_mode = regex_mode
+ self._capture = capture
+ self._matched = False
+
+ if not self._regex:
+ raise Exception("regex cannot be None")
+
+ if not self._regex_mode in ["match", "search"]:
+ raise Exception("unsupported regex mode \"{}\": must be \"match\" or \"search\"".format(self._regex_mode))
+
+ def is_output_matcher(self):
+ return True
+
+ def is_send_to_remote(self):
+ # This is always a "wait for remote" command.
+ return False
+
+ def is_consumed(self):
+ return self._matched
+
+ def assert_match(self, asserter, accumulated_output, context):
+ # Validate args.
+ if not accumulated_output:
+ raise Exception("accumulated_output cannot be none")
+ if not context:
+ raise Exception("context cannot be none")
+
+ # Validate that we haven't already matched.
+ if self._matched:
+ raise Exception("invalid state - already matched, attempting to match again")
+
+ # If we don't have any content yet, we don't match.
+ if len(accumulated_output) < 1:
+ return context
+
+ # Check if we match
+ if self._regex_mode == "match":
+ match = self._regex.match(accumulated_output)
+ elif self._regex_mode == "search":
+ match = self._regex.search(accumulated_output)
+ else:
+ raise Exception("Unexpected regex mode: {}".format(self._regex_mode))
+
+ # If we don't match, wait to try again after next $O content, or time out.
+ if not match:
+ # print("re pattern \"{}\" did not match against \"{}\"".format(self._regex.pattern, accumulated_output))
+ return context
+
+ # We do match.
+ self._matched = True
+ # print("re pattern \"{}\" matched against \"{}\"".format(self._regex.pattern, accumulated_output))
+
+ # Collect up any captures into the context.
+ if self._capture:
+ # Handle captures.
+ for group_index, var_name in list(self._capture.items()):
+ capture_text = match.group(group_index)
+ if not capture_text:
+ raise Exception("No content for group index {}".format(group_index))
+ context[var_name] = capture_text
+
+ return context
+
+
+class GdbRemoteTestSequence(object):
+
+ _LOG_LINE_REGEX = re.compile(r'^.*(read|send)\s+packet:\s+(.+)$')
+
+ def __init__(self, logger):
+ self.entries = []
+ self.logger = logger
+
+ def add_log_lines(self, log_lines, remote_input_is_read):
+ for line in log_lines:
+ if type(line) == str:
+ # Handle log line import
+ # if self.logger:
+ # self.logger.debug("processing log line: {}".format(line))
+ match = self._LOG_LINE_REGEX.match(line)
+ if match:
+ playback_packet = match.group(2)
+ direction = match.group(1)
+ if _is_packet_lldb_gdbserver_input(direction, remote_input_is_read):
+ # Handle as something to send to the remote debug monitor.
+ # if self.logger:
+ # self.logger.info("processed packet to send to remote: {}".format(playback_packet))
+ self.entries.append(GdbRemoteEntry(is_send_to_remote=True, exact_payload=playback_packet))
+ else:
+ # Log line represents content to be expected from the remote debug monitor.
+ # if self.logger:
+ # self.logger.info("receiving packet from llgs, should match: {}".format(playback_packet))
+ self.entries.append(GdbRemoteEntry(is_send_to_remote=False,exact_payload=playback_packet))
+ else:
+ raise Exception("failed to interpret log line: {}".format(line))
+ elif type(line) == dict:
+ entry_type = line.get("type", "regex_capture")
+ if entry_type == "regex_capture":
+ # Handle more explicit control over details via dictionary.
+ direction = line.get("direction", None)
+ regex = line.get("regex", None)
+ capture = line.get("capture", None)
+ expect_captures = line.get("expect_captures", None)
+
+ # Compile the regex.
+ if regex and (type(regex) == str):
+ regex = re.compile(regex)
+
+ if _is_packet_lldb_gdbserver_input(direction, remote_input_is_read):
+ # Handle as something to send to the remote debug monitor.
+ # if self.logger:
+ # self.logger.info("processed dict sequence to send to remote")
+ self.entries.append(GdbRemoteEntry(is_send_to_remote=True, regex=regex, capture=capture, expect_captures=expect_captures))
+ else:
+ # Log line represents content to be expected from the remote debug monitor.
+ # if self.logger:
+ # self.logger.info("processed dict sequence to match receiving from remote")
+ self.entries.append(GdbRemoteEntry(is_send_to_remote=False, regex=regex, capture=capture, expect_captures=expect_captures))
+ elif entry_type == "multi_response":
+ self.entries.append(MultiResponseGdbRemoteEntry(line))
+ elif entry_type == "output_match":
+
+ regex = line.get("regex", None)
+ # Compile the regex.
+ if regex and (type(regex) == str):
+ regex = re.compile(regex)
+
+ regex_mode = line.get("regex_mode", "match")
+ capture = line.get("capture", None)
+ self.entries.append(MatchRemoteOutputEntry(regex=regex, regex_mode=regex_mode, capture=capture))
+ else:
+ raise Exception("unknown entry type \"%s\"" % entry_type)
+
+def process_is_running(pid, unknown_value=True):
+ """If possible, validate that the given pid represents a running process on the local system.
+
+ Args:
+
+ pid: an OS-specific representation of a process id. Should be an integral value.
+
+ unknown_value: value used when we cannot determine how to check running local
+ processes on the OS.
+
+ Returns:
+
+ If we can figure out how to check running process ids on the given OS:
+ return True if the process is running, or False otherwise.
+
+ If we don't know how to check running process ids on the given OS:
+ return the value provided by the unknown_value arg.
+ """
+ if not isinstance(pid, six.integer_types):
+ raise Exception("pid must be an integral type (actual type: %s)" % str(type(pid)))
+
+ process_ids = []
+
+ if lldb.remote_platform:
+ # Don't know how to get list of running process IDs on a remote
+ # platform
+ return unknown_value
+ elif platform.system() in ['Darwin', 'Linux', 'FreeBSD', 'NetBSD']:
+ # Build the list of running process ids
+ output = subprocess.check_output("ps ax | awk '{ print $1; }'", shell=True)
+ text_process_ids = output.split('\n')[1:]
+ # Convert text pids to ints
+ process_ids = [int(text_pid) for text_pid in text_process_ids if text_pid != '']
+ # elif {your_platform_here}:
+ # fill in process_ids as a list of int type process IDs running on
+ # the local system.
+ else:
+ # Don't know how to get list of running process IDs on this
+ # OS, so return the "don't know" value.
+ return unknown_value
+
+ # Check if the pid is in the process_ids
+ return pid in process_ids
+
+if __name__ == '__main__':
+ EXE_PATH = get_lldb_server_exe()
+ if EXE_PATH:
+ print("lldb-server path detected: {}".format(EXE_PATH))
+ else:
+ print("lldb-server could not be found")
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/main.cpp b/packages/Python/lldbsuite/test/tools/lldb-server/main.cpp
new file mode 100644
index 000000000000..c65b22571596
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/main.cpp
@@ -0,0 +1,404 @@
+#include <cstdlib>
+#include <cstring>
+#include <errno.h>
+#include <inttypes.h>
+#include <memory>
+#include <pthread.h>
+#include <setjmp.h>
+#include <signal.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+#include <vector>
+
+#if defined(__APPLE__)
+__OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_2)
+int pthread_threadid_np(pthread_t,__uint64_t*);
+#elif defined(__linux__)
+#include <sys/syscall.h>
+#endif
+
+#if defined(__linux__)
+#include <sys/prctl.h>
+#endif
+
+static const char *const RETVAL_PREFIX = "retval:";
+static const char *const SLEEP_PREFIX = "sleep:";
+static const char *const STDERR_PREFIX = "stderr:";
+static const char *const SET_MESSAGE_PREFIX = "set-message:";
+static const char *const PRINT_MESSAGE_COMMAND = "print-message:";
+static const char *const GET_DATA_ADDRESS_PREFIX = "get-data-address-hex:";
+static const char *const GET_STACK_ADDRESS_COMMAND = "get-stack-address-hex:";
+static const char *const GET_HEAP_ADDRESS_COMMAND = "get-heap-address-hex:";
+
+static const char *const GET_CODE_ADDRESS_PREFIX = "get-code-address-hex:";
+static const char *const CALL_FUNCTION_PREFIX = "call-function:";
+
+static const char *const THREAD_PREFIX = "thread:";
+static const char *const THREAD_COMMAND_NEW = "new";
+static const char *const THREAD_COMMAND_PRINT_IDS = "print-ids";
+static const char *const THREAD_COMMAND_SEGFAULT = "segfault";
+
+static bool g_print_thread_ids = false;
+static pthread_mutex_t g_print_mutex = PTHREAD_MUTEX_INITIALIZER;
+static bool g_threads_do_segfault = false;
+
+static pthread_mutex_t g_jump_buffer_mutex = PTHREAD_MUTEX_INITIALIZER;
+static jmp_buf g_jump_buffer;
+static bool g_is_segfaulting = false;
+
+static char g_message[256];
+
+static volatile char g_c1 = '0';
+static volatile char g_c2 = '1';
+
+static void
+print_thread_id ()
+{
+ // Put in the right magic here for your platform to spit out the thread id (tid) that debugserver/lldb-gdbserver would see as a TID.
+ // Otherwise, let the else clause print out the unsupported text so that the unit test knows to skip verifying thread ids.
+#if defined(__APPLE__)
+ __uint64_t tid = 0;
+ pthread_threadid_np(pthread_self(), &tid);
+ printf ("%" PRIx64, tid);
+#elif defined (__linux__)
+ // This is a call to gettid() via syscall.
+ printf ("%" PRIx64, static_cast<uint64_t> (syscall (__NR_gettid)));
+#else
+ printf("{no-tid-support}");
+#endif
+}
+
+static void
+signal_handler (int signo)
+{
+ const char *signal_name = nullptr;
+ switch (signo)
+ {
+ case SIGUSR1: signal_name = "SIGUSR1"; break;
+ case SIGSEGV: signal_name = "SIGSEGV"; break;
+ default: signal_name = nullptr;
+ }
+
+ // Print notice that we received the signal on a given thread.
+ pthread_mutex_lock (&g_print_mutex);
+ if (signal_name)
+ printf ("received %s on thread id: ", signal_name);
+ else
+ printf ("received signo %d (%s) on thread id: ", signo, strsignal (signo));
+ print_thread_id ();
+ printf ("\n");
+ pthread_mutex_unlock (&g_print_mutex);
+
+ // Reset the signal handler if we're one of the expected signal handlers.
+ switch (signo)
+ {
+ case SIGSEGV:
+ if (g_is_segfaulting)
+ {
+ // Fix up the pointer we're writing to. This needs to happen if nothing intercepts the SIGSEGV
+ // (i.e. if somebody runs this from the command line).
+ longjmp(g_jump_buffer, 1);
+ }
+ break;
+ case SIGUSR1:
+ if (g_is_segfaulting)
+ {
+ // Fix up the pointer we're writing to. This is used to test gdb remote signal delivery.
+ // A SIGSEGV will be raised when the thread is created, switched out for a SIGUSR1, and
+ // then this code still needs to fix the seg fault.
+ // (i.e. if somebody runs this from the command line).
+ longjmp(g_jump_buffer, 1);
+ }
+ break;
+ }
+
+ // Reset the signal handler.
+ sig_t sig_result = signal (signo, signal_handler);
+ if (sig_result == SIG_ERR)
+ {
+ fprintf(stderr, "failed to set signal handler: errno=%d\n", errno);
+ exit (1);
+ }
+}
+
+static void
+swap_chars ()
+{
+ g_c1 = '1';
+ g_c2 = '0';
+
+ g_c1 = '0';
+ g_c2 = '1';
+}
+
+static void
+hello ()
+{
+ pthread_mutex_lock (&g_print_mutex);
+ printf ("hello, world\n");
+ pthread_mutex_unlock (&g_print_mutex);
+}
+
+static void*
+thread_func (void *arg)
+{
+ static pthread_mutex_t s_thread_index_mutex = PTHREAD_MUTEX_INITIALIZER;
+ static int s_thread_index = 1;
+
+ pthread_mutex_lock (&s_thread_index_mutex);
+ const int this_thread_index = s_thread_index++;
+ pthread_mutex_unlock (&s_thread_index_mutex);
+
+ if (g_print_thread_ids)
+ {
+ pthread_mutex_lock (&g_print_mutex);
+ printf ("thread %d id: ", this_thread_index);
+ print_thread_id ();
+ printf ("\n");
+ pthread_mutex_unlock (&g_print_mutex);
+ }
+
+ if (g_threads_do_segfault)
+ {
+ // Sleep for a number of seconds based on the thread index.
+ // TODO add ability to send commands to test exe so we can
+ // handle timing more precisely. This is clunky. All we're
+ // trying to do is add predictability as to the timing of
+ // signal generation by created threads.
+ int sleep_seconds = 2 * (this_thread_index - 1);
+ while (sleep_seconds > 0)
+ sleep_seconds = sleep(sleep_seconds);
+
+ // Test creating a SEGV.
+ pthread_mutex_lock (&g_jump_buffer_mutex);
+ g_is_segfaulting = true;
+ int *bad_p = nullptr;
+ if (setjmp(g_jump_buffer) == 0)
+ {
+ // Force a seg fault signal on this thread.
+ *bad_p = 0;
+ }
+ else
+ {
+ // Tell the system we're no longer seg faulting.
+ // Used by the SIGUSR1 signal handler that we inject
+ // in place of the SIGSEGV so it only tries to
+ // recover from the SIGSEGV if this seg fault code
+ // was in play.
+ g_is_segfaulting = false;
+ }
+ pthread_mutex_unlock (&g_jump_buffer_mutex);
+
+ pthread_mutex_lock (&g_print_mutex);
+ printf ("thread ");
+ print_thread_id ();
+ printf (": past SIGSEGV\n");
+ pthread_mutex_unlock (&g_print_mutex);
+ }
+
+ int sleep_seconds_remaining = 60;
+ while (sleep_seconds_remaining > 0)
+ {
+ sleep_seconds_remaining = sleep (sleep_seconds_remaining);
+ }
+
+ return nullptr;
+}
+
+int main (int argc, char **argv)
+{
+#if defined(__linux__)
+ // Immediately enable any ptracer so that we can allow the stub attach
+ // operation to succeed. Some Linux kernels are locked down so that
+ // only an ancestor can be a ptracer of a process. This disables that
+ // restriction. Without it, attach-related stub tests will fail.
+#if defined(PR_SET_PTRACER) && defined(PR_SET_PTRACER_ANY)
+ const int prctl_result = prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
+ static_cast<void> (prctl_result);
+#endif
+#endif
+
+ std::vector<pthread_t> threads;
+ std::unique_ptr<uint8_t[]> heap_array_up;
+ int return_value = 0;
+
+ // Set the signal handler.
+ sig_t sig_result = signal (SIGALRM, signal_handler);
+ if (sig_result == SIG_ERR)
+ {
+ fprintf(stderr, "failed to set SIGALRM signal handler: errno=%d\n", errno);
+ exit (1);
+ }
+
+ sig_result = signal (SIGUSR1, signal_handler);
+ if (sig_result == SIG_ERR)
+ {
+ fprintf(stderr, "failed to set SIGUSR1 handler: errno=%d\n", errno);
+ exit (1);
+ }
+
+ sig_result = signal (SIGSEGV, signal_handler);
+ if (sig_result == SIG_ERR)
+ {
+ fprintf(stderr, "failed to set SIGUSR1 handler: errno=%d\n", errno);
+ exit (1);
+ }
+
+ // Process command line args.
+ for (int i = 1; i < argc; ++i)
+ {
+ if (std::strstr (argv[i], STDERR_PREFIX))
+ {
+ // Treat remainder as text to go to stderr.
+ fprintf (stderr, "%s\n", (argv[i] + strlen (STDERR_PREFIX)));
+ }
+ else if (std::strstr (argv[i], RETVAL_PREFIX))
+ {
+ // Treat as the return value for the program.
+ return_value = std::atoi (argv[i] + strlen (RETVAL_PREFIX));
+ }
+ else if (std::strstr (argv[i], SLEEP_PREFIX))
+ {
+ // Treat as the amount of time to have this process sleep (in seconds).
+ int sleep_seconds_remaining = std::atoi (argv[i] + strlen (SLEEP_PREFIX));
+
+ // Loop around, sleeping until all sleep time is used up. Note that
+ // signals will cause sleep to end early with the number of seconds remaining.
+ for (int i = 0; sleep_seconds_remaining > 0; ++i)
+ {
+ sleep_seconds_remaining = sleep (sleep_seconds_remaining);
+ // std::cout << "sleep result (call " << i << "): " << sleep_seconds_remaining << std::endl;
+ }
+ }
+ else if (std::strstr (argv[i], SET_MESSAGE_PREFIX))
+ {
+ // Copy the contents after "set-message:" to the g_message buffer.
+ // Used for reading inferior memory and verifying contents match expectations.
+ strncpy (g_message, argv[i] + strlen (SET_MESSAGE_PREFIX), sizeof (g_message));
+
+ // Ensure we're null terminated.
+ g_message[sizeof (g_message) - 1] = '\0';
+
+ }
+ else if (std::strstr (argv[i], PRINT_MESSAGE_COMMAND))
+ {
+ pthread_mutex_lock (&g_print_mutex);
+ printf ("message: %s\n", g_message);
+ pthread_mutex_unlock (&g_print_mutex);
+ }
+ else if (std::strstr (argv[i], GET_DATA_ADDRESS_PREFIX))
+ {
+ volatile void *data_p = nullptr;
+
+ if (std::strstr (argv[i] + strlen (GET_DATA_ADDRESS_PREFIX), "g_message"))
+ data_p = &g_message[0];
+ else if (std::strstr (argv[i] + strlen (GET_DATA_ADDRESS_PREFIX), "g_c1"))
+ data_p = &g_c1;
+ else if (std::strstr (argv[i] + strlen (GET_DATA_ADDRESS_PREFIX), "g_c2"))
+ data_p = &g_c2;
+
+ pthread_mutex_lock (&g_print_mutex);
+ printf ("data address: %p\n", data_p);
+ pthread_mutex_unlock (&g_print_mutex);
+ }
+ else if (std::strstr (argv[i], GET_HEAP_ADDRESS_COMMAND))
+ {
+ // Create a byte array if not already present.
+ if (!heap_array_up)
+ heap_array_up.reset (new uint8_t[32]);
+
+ pthread_mutex_lock (&g_print_mutex);
+ printf ("heap address: %p\n", heap_array_up.get ());
+ pthread_mutex_unlock (&g_print_mutex);
+ }
+ else if (std::strstr (argv[i], GET_STACK_ADDRESS_COMMAND))
+ {
+ pthread_mutex_lock (&g_print_mutex);
+ printf ("stack address: %p\n", &return_value);
+ pthread_mutex_unlock (&g_print_mutex);
+ }
+ else if (std::strstr (argv[i], GET_CODE_ADDRESS_PREFIX))
+ {
+ void (*func_p)() = nullptr;
+
+ if (std::strstr (argv[i] + strlen (GET_CODE_ADDRESS_PREFIX), "hello"))
+ func_p = hello;
+ else if (std::strstr (argv[i] + strlen (GET_CODE_ADDRESS_PREFIX), "swap_chars"))
+ func_p = swap_chars;
+
+ pthread_mutex_lock (&g_print_mutex);
+ printf ("code address: %p\n", func_p);
+ pthread_mutex_unlock (&g_print_mutex);
+ }
+ else if (std::strstr (argv[i], CALL_FUNCTION_PREFIX))
+ {
+ // Defaut to providing the address of main.
+ if (std::strcmp (argv[i] + strlen (CALL_FUNCTION_PREFIX), "hello") == 0)
+ hello();
+ else if (std::strcmp (argv[i] + strlen (CALL_FUNCTION_PREFIX), "swap_chars") == 0)
+ swap_chars();
+ else
+ {
+ pthread_mutex_lock (&g_print_mutex);
+ printf ("unknown function: %s\n", argv[i] + strlen (CALL_FUNCTION_PREFIX));
+ pthread_mutex_unlock (&g_print_mutex);
+ }
+ }
+ else if (std::strstr (argv[i], THREAD_PREFIX))
+ {
+ // Check if we're creating a new thread.
+ if (std::strstr (argv[i] + strlen(THREAD_PREFIX), THREAD_COMMAND_NEW))
+ {
+ // Create a new thread.
+ pthread_t new_thread;
+ const int err = ::pthread_create (&new_thread, nullptr, thread_func, nullptr);
+ if (err)
+ {
+ fprintf (stderr, "pthread_create() failed with error code %d\n", err);
+ exit (err);
+ }
+ threads.push_back (new_thread);
+ }
+ else if (std::strstr (argv[i] + strlen(THREAD_PREFIX), THREAD_COMMAND_PRINT_IDS))
+ {
+ // Turn on thread id announcing.
+ g_print_thread_ids = true;
+
+ // And announce us.
+ pthread_mutex_lock (&g_print_mutex);
+ printf ("thread 0 id: ");
+ print_thread_id ();
+ printf ("\n");
+ pthread_mutex_unlock (&g_print_mutex);
+ }
+ else if (std::strstr (argv[i] + strlen(THREAD_PREFIX), THREAD_COMMAND_SEGFAULT))
+ {
+ g_threads_do_segfault = true;
+ }
+ else
+ {
+ // At this point we don't do anything else with threads.
+ // Later use thread index and send command to thread.
+ }
+ }
+ else
+ {
+ // Treat the argument as text for stdout.
+ printf("%s\n", argv[i]);
+ }
+ }
+
+ // If we launched any threads, join them
+ for (std::vector<pthread_t>::iterator it = threads.begin (); it != threads.end (); ++it)
+ {
+ void *thread_retval = nullptr;
+ const int err = ::pthread_join (*it, &thread_retval);
+ if (err != 0)
+ fprintf (stderr, "pthread_join() failed with error code %d\n", err);
+ }
+
+ return return_value;
+}
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/Makefile b/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/Makefile
new file mode 100644
index 000000000000..314f1cb2f077
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/TestPlatformProcessConnect.py b/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/TestPlatformProcessConnect.py
new file mode 100644
index 000000000000..b50a03015462
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/TestPlatformProcessConnect.py
@@ -0,0 +1,56 @@
+from __future__ import print_function
+
+import gdbremote_testcase
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+class TestPlatformProcessConnect(gdbremote_testcase.GdbRemoteTestCaseBase):
+ mydir = TestBase.compute_mydir(__file__)
+
+ @llgs_test
+ @no_debug_info_test
+ @skipIf(remote=False)
+ @expectedFailureAll(hostoslist=["windows"], triple='.*-android')
+ def test_platform_process_connect(self):
+ self.build()
+ self.init_llgs_test(False)
+
+ working_dir = lldb.remote_platform.GetWorkingDirectory()
+ err = lldb.remote_platform.Put(lldb.SBFileSpec(os.path.join(os.getcwd(), "a.out")),
+ lldb.SBFileSpec(os.path.join(working_dir, "a.out")))
+ if err.Fail():
+ raise RuntimeError("Unable copy '%s' to '%s'.\n>>> %s" % (f, wd, err.GetCString()))
+
+ port_file = "%s/port" % working_dir
+ commandline_args = ["platform", "--listen", "*:0", "--socket-file", port_file, "--", "%s/a.out" % working_dir, "foo"]
+ self.spawnSubprocess(self.debug_monitor_exe, commandline_args, install_remote=False)
+ self.addTearDownHook(self.cleanupSubprocesses)
+ new_port = self.run_shell_cmd("while [ ! -f %s ]; do sleep 0.25; done && cat %s" % (port_file, port_file))
+
+ new_debugger = lldb.SBDebugger.Create()
+ new_debugger.SetAsync(False)
+ def del_debugger(new_debugger=new_debugger):
+ del new_debugger
+ self.addTearDownHook(del_debugger)
+
+ new_platform = lldb.SBPlatform(lldb.remote_platform.GetName())
+ new_debugger.SetSelectedPlatform(new_platform)
+ new_interpreter = new_debugger.GetCommandInterpreter()
+
+ m = re.search("(.*):[0-9]+", configuration.lldb_platform_url)
+ command = "platform connect %s:%s" % (m.group(1), new_port)
+ result = lldb.SBCommandReturnObject()
+ new_interpreter.HandleCommand(command, result)
+ self.assertTrue(result.Succeeded(), "platform process connect failed: %s" % result.GetOutput())
+
+ target = new_debugger.GetSelectedTarget()
+ process = target.GetProcess()
+ thread = process.GetThreadAtIndex(0)
+
+ breakpoint = target.BreakpointCreateByName("main")
+ process.Continue()
+
+ frame = thread.GetFrameAtIndex(0)
+ self.assertEqual(frame.GetFunction().GetName(), "main")
+ self.assertEqual(frame.FindVariable("argc").GetValueAsSigned(), 2)
+ process.Continue()
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/main.cpp b/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/main.cpp
new file mode 100644
index 000000000000..70ae5094fde7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/platform-process-connect/main.cpp
@@ -0,0 +1,7 @@
+#include <cstdio>
+
+int main (int argc, char **argv)
+{
+ printf("argc: %d\n", argc);
+ return argv[0][0];
+}
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/socket_packet_pump.py b/packages/Python/lldbsuite/test/tools/lldb-server/socket_packet_pump.py
new file mode 100644
index 000000000000..795a8c6652d0
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/socket_packet_pump.py
@@ -0,0 +1,187 @@
+
+from __future__ import print_function
+
+
+
+import re
+import select
+import threading
+import traceback
+import codecs
+
+from six.moves import queue
+
+def _handle_output_packet_string(packet_contents):
+ if (not packet_contents) or (len(packet_contents) < 1):
+ return None
+ elif packet_contents[0] != "O":
+ return None
+ elif packet_contents == "OK":
+ return None
+ else:
+ return packet_contents[1:].decode("hex")
+
+def _dump_queue(the_queue):
+ while not the_queue.empty():
+ print(codecs.encode(the_queue.get(True), "string_escape"))
+ print("\n")
+
+class SocketPacketPump(object):
+ """A threaded packet reader that partitions packets into two streams.
+
+ All incoming $O packet content is accumulated with the current accumulation
+ state put into the OutputQueue.
+
+ All other incoming packets are placed in the packet queue.
+
+ A select thread can be started and stopped, and runs to place packet
+ content into the two queues.
+ """
+
+ _GDB_REMOTE_PACKET_REGEX = re.compile(r'^\$([^\#]*)#[0-9a-fA-F]{2}')
+
+ def __init__(self, pump_socket, logger=None):
+ if not pump_socket:
+ raise Exception("pump_socket cannot be None")
+
+ self._output_queue = queue.Queue()
+ self._packet_queue = queue.Queue()
+ self._thread = None
+ self._stop_thread = False
+ self._socket = pump_socket
+ self._logger = logger
+ self._receive_buffer = ""
+ self._accumulated_output = ""
+
+ def __enter__(self):
+ """Support the python 'with' statement.
+
+ Start the pump thread."""
+ self.start_pump_thread()
+ return self
+
+ def __exit__(self, exit_type, value, the_traceback):
+ """Support the python 'with' statement.
+
+ Shut down the pump thread."""
+ self.stop_pump_thread()
+
+ # Warn if there is any content left in any of the queues.
+ # That would represent unmatched packets.
+ if not self.output_queue().empty():
+ print("warning: output queue entries still exist:")
+ _dump_queue(self.output_queue())
+ print("from here:")
+ traceback.print_stack()
+
+ if not self.packet_queue().empty():
+ print("warning: packet queue entries still exist:")
+ _dump_queue(self.packet_queue())
+ print("from here:")
+ traceback.print_stack()
+
+ def start_pump_thread(self):
+ if self._thread:
+ raise Exception("pump thread is already running")
+ self._stop_thread = False
+ self._thread = threading.Thread(target=self._run_method)
+ self._thread.start()
+
+ def stop_pump_thread(self):
+ self._stop_thread = True
+ if self._thread:
+ self._thread.join()
+
+ def output_queue(self):
+ return self._output_queue
+
+ def packet_queue(self):
+ return self._packet_queue
+
+ def _process_new_bytes(self, new_bytes):
+ if not new_bytes:
+ return
+ if len(new_bytes) < 1:
+ return
+
+ # Add new bytes to our accumulated unprocessed packet bytes.
+ self._receive_buffer += new_bytes
+
+ # Parse fully-formed packets into individual packets.
+ has_more = len(self._receive_buffer) > 0
+ while has_more:
+ if len(self._receive_buffer) <= 0:
+ has_more = False
+ # handle '+' ack
+ elif self._receive_buffer[0] == "+":
+ self._packet_queue.put("+")
+ self._receive_buffer = self._receive_buffer[1:]
+ if self._logger:
+ self._logger.debug(
+ "parsed packet from stub: +\n" +
+ "new receive_buffer: {}".format(
+ self._receive_buffer))
+ else:
+ packet_match = self._GDB_REMOTE_PACKET_REGEX.match(
+ self._receive_buffer)
+ if packet_match:
+ # Our receive buffer matches a packet at the
+ # start of the receive buffer.
+ new_output_content = _handle_output_packet_string(
+ packet_match.group(1))
+ if new_output_content:
+ # This was an $O packet with new content.
+ self._accumulated_output += new_output_content
+ self._output_queue.put(self._accumulated_output)
+ else:
+ # Any packet other than $O.
+ self._packet_queue.put(packet_match.group(0))
+
+ # Remove the parsed packet from the receive
+ # buffer.
+ self._receive_buffer = self._receive_buffer[
+ len(packet_match.group(0)):]
+ if self._logger:
+ self._logger.debug(
+ "parsed packet from stub: " +
+ packet_match.group(0))
+ self._logger.debug(
+ "new receive_buffer: " +
+ self._receive_buffer)
+ else:
+ # We don't have enough in the receive bufferto make a full
+ # packet. Stop trying until we read more.
+ has_more = False
+
+ def _run_method(self):
+ self._receive_buffer = ""
+ self._accumulated_output = ""
+
+ if self._logger:
+ self._logger.info("socket pump starting")
+
+ # Keep looping around until we're asked to stop the thread.
+ while not self._stop_thread:
+ can_read, _, _ = select.select([self._socket], [], [], 0)
+ if can_read and self._socket in can_read:
+ try:
+ new_bytes = self._socket.recv(4096)
+ if self._logger and new_bytes and len(new_bytes) > 0:
+ self._logger.debug(
+ "pump received bytes: {}".format(new_bytes))
+ except:
+ # Likely a closed socket. Done with the pump thread.
+ if self._logger:
+ self._logger.debug(
+ "socket read failed, stopping pump read thread")
+ break
+ self._process_new_bytes(new_bytes)
+
+ if self._logger:
+ self._logger.info("socket pump exiting")
+
+ def get_accumulated_output(self):
+ return self._accumulated_output
+
+ def get_receive_buffer(self):
+ return self._receive_buffer
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/test/test_lldbgdbserverutils.py b/packages/Python/lldbsuite/test/tools/lldb-server/test/test_lldbgdbserverutils.py
new file mode 100644
index 000000000000..8b3b6b68cf02
--- /dev/null
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/test/test_lldbgdbserverutils.py
@@ -0,0 +1,49 @@
+from __future__ import print_function
+
+
+
+import unittest2
+import os.path
+import re
+import sys
+
+from lldbgdbserverutils import *
+
+
+class TestLldbGdbServerUtils(unittest2.TestCase):
+ def test_entry_exact_payload_match(self):
+ entry = GdbRemoteEntry(is_send_to_remote=False, exact_payload="$OK#9a")
+ entry.assert_match(self, "$OK#9a")
+
+ def test_entry_exact_payload_match_ignores_checksum(self):
+ entry = GdbRemoteEntry(is_send_to_remote=False, exact_payload="$OK#9a")
+ entry.assert_match(self, "$OK#00")
+
+ def test_entry_creates_context(self):
+ entry = GdbRemoteEntry(is_send_to_remote=False, exact_payload="$OK#9a")
+ context = entry.assert_match(self, "$OK#9a")
+ self.assertIsNotNone(context)
+
+ def test_entry_regex_matches(self):
+ entry = GdbRemoteEntry(is_send_to_remote=False, regex=re.compile(r"^\$QC([0-9a-fA-F]+)#"), capture={ 1:"thread_id" })
+ context = entry.assert_match(self, "$QC980#00")
+
+ def test_entry_regex_saves_match(self):
+ entry = GdbRemoteEntry(is_send_to_remote=False, regex=re.compile(r"^\$QC([0-9a-fA-F]+)#"), capture={ 1:"thread_id" })
+ context = entry.assert_match(self, "$QC980#00")
+ self.assertEqual(context["thread_id"], "980")
+
+ def test_entry_regex_expect_captures_success(self):
+ context = { "thread_id":"980" }
+ entry = GdbRemoteEntry(is_send_to_remote=False, regex=re.compile(r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+)"), expect_captures={ 2:"thread_id" })
+ entry.assert_match(self, "$T11thread:980;", context=context)
+
+ def test_entry_regex_expect_captures_raises_on_fail(self):
+ context = { "thread_id":"980" }
+ entry = GdbRemoteEntry(is_send_to_remote=False, regex=re.compile(r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+)"), expect_captures={ 2:"thread_id" })
+ try:
+ entry.assert_match(self, "$T11thread:970;", context=context)
+ self.fail()
+ except AssertionError:
+ # okay
+ return None
diff --git a/packages/Python/lldbsuite/test/types/AbstractBase.py b/packages/Python/lldbsuite/test/types/AbstractBase.py
new file mode 100644
index 000000000000..dd09c91f4d02
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/AbstractBase.py
@@ -0,0 +1,259 @@
+"""
+Abstract base class of basic types provides a generic type tester method.
+"""
+
+from __future__ import print_function
+
+import os, time
+import re
+import lldb
+from lldbsuite.test.lldbtest import *
+import lldbsuite.test.lldbutil as lldbutil
+
+def Msg(var, val, using_frame_variable):
+ return "'%s %s' matches the output (from compiled code): %s" % (
+ 'frame variable --show-types' if using_frame_variable else 'expression' ,var, val)
+
+class GenericTester(TestBase):
+
+ # This is the pattern by design to match the " var = 'value'" output from
+ # printf() stmts (see basic_type.cpp).
+ pattern = re.compile(" (\*?a[^=]*) = '([^=]*)'$")
+
+ # Assert message.
+ DATA_TYPE_GROKKED = "Data type from expr parser output is parsed correctly"
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # We'll use the test method name as the exe_name.
+ # 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.exe_name = self.testMethodName
+ self.golden_filename = os.path.join(os.getcwd(), "golden-output.txt")
+
+ def tearDown(self):
+ """Cleanup the test byproducts."""
+ #print("Removing golden-output.txt...")
+ if os.path.exists(self.golden_filename):
+ os.remove(self.golden_filename)
+ TestBase.tearDown(self)
+
+ #==========================================================================#
+ # Functions build_and_run() and build_and_run_expr() are generic functions #
+ # which are called from the Test*Types*.py test cases. The API client is #
+ # responsible for supplying two mandatory arguments: the source file, e.g.,#
+ # 'int.cpp', and the atoms, e.g., set(['unsigned', 'long long']) to the #
+ # functions. There are also three optional keyword arguments of interest, #
+ # as follows: #
+ # #
+ # bc -> blockCaptured (defaulted to False) #
+ # True: testing vars of various basic types from inside a block #
+ # False: testing vars of various basic types from a function #
+ # qd -> quotedDisplay (defaulted to False) #
+ # True: the output from 'frame var' or 'expr var' contains a pair #
+ # of single quotes around the value #
+ # False: no single quotes are to be found around the value of #
+ # variable #
+ #==========================================================================#
+
+ def build_and_run(self, source, atoms, bc=False, qd=False):
+ self.build_and_run_with_source_atoms_expr(source, atoms, expr=False, bc=bc, qd=qd)
+
+ def build_and_run_expr(self, source, atoms, bc=False, qd=False):
+ self.build_and_run_with_source_atoms_expr(source, atoms, expr=True, bc=bc, qd=qd)
+
+ def build_and_run_with_source_atoms_expr(self, source, atoms, expr, bc=False, qd=False):
+ # See also Makefile and basic_type.cpp:177.
+ if bc:
+ d = {'CXX_SOURCES': source, 'EXE': self.exe_name, 'CFLAGS_EXTRAS': '-DTEST_BLOCK_CAPTURED_VARS'}
+ else:
+ d = {'CXX_SOURCES': source, 'EXE': self.exe_name}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ if expr:
+ self.generic_type_expr_tester(self.exe_name, atoms, blockCaptured=bc, quotedDisplay=qd)
+ else:
+ self.generic_type_tester(self.exe_name, atoms, blockCaptured=bc, quotedDisplay=qd)
+
+ def process_launch_o(self, localPath):
+ # process launch command output redirect always goes to host the process is running on
+ if lldb.remote_platform:
+ # process launch -o requires a path that is valid on the target
+ self.assertIsNotNone(lldb.remote_platform.GetWorkingDirectory())
+ remote_path = lldbutil.append_to_process_working_directory("lldb-stdout-redirect.txt")
+ self.runCmd('process launch -o {remote}'.format(remote=remote_path))
+ # copy remote_path to local host
+ self.runCmd('platform get-file {remote} "{local}"'.format(
+ remote=remote_path, local=self.golden_filename))
+ else:
+ self.runCmd('process launch -o "{local}"'.format(local=self.golden_filename))
+
+ def generic_type_tester(self, exe_name, atoms, quotedDisplay=False, blockCaptured=False):
+ """Test that variables with basic types are displayed correctly."""
+
+ self.runCmd("file %s" % exe_name, CURRENT_EXECUTABLE_SET)
+
+ # First, capture the golden output emitted by the oracle, i.e., the
+ # series of printf statements.
+
+ self.process_launch_o(self.golden_filename)
+
+ with open(self.golden_filename) as f:
+ go = f.read()
+
+ # This golden list contains a list of (variable, value) pairs extracted
+ # from the golden output.
+ gl = []
+
+ # Scan the golden output line by line, looking for the pattern:
+ #
+ # variable = 'value'
+ #
+ for line in go.split(os.linesep):
+ # We'll ignore variables of array types from inside a block.
+ if blockCaptured and '[' in line:
+ continue
+ match = self.pattern.search(line)
+ if match:
+ var, val = match.group(1), match.group(2)
+ gl.append((var, val))
+ #print("golden list:", gl)
+
+ # This test uses a #include of "basic_type.cpp" so we need to enable
+ # always setting inlined breakpoints.
+ self.runCmd('settings set target.inline-breakpoint-strategy always')
+ # And add hooks to restore the settings during tearDown().
+ self.addTearDownHook(
+ lambda: self.runCmd("settings set target.inline-breakpoint-strategy headers"))
+
+ # Bring the program to the point where we can issue a series of
+ # 'frame variable --show-types' command.
+ if blockCaptured:
+ break_line = line_number ("basic_type.cpp", "// Break here to test block captured variables.")
+ else:
+ break_line = line_number ("basic_type.cpp", "// Here is the line we will break on to check variables.")
+ lldbutil.run_break_set_by_file_and_line (self, "basic_type.cpp", break_line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+ self.expect("process status", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = [" at basic_type.cpp:%d" % break_line,
+ "stop reason = breakpoint"])
+
+ #self.runCmd("frame variable --show-types")
+
+ # Now iterate through the golden list, comparing against the output from
+ # 'frame variable --show-types var'.
+ for var, val in gl:
+ self.runCmd("frame variable --show-types %s" % var)
+ output = self.res.GetOutput()
+
+ # The input type is in a canonical form as a set of named atoms.
+ # The display type string must contain each and every element.
+ #
+ # Example:
+ # runCmd: frame variable --show-types a_array_bounded[0]
+ # output: (char) a_array_bounded[0] = 'a'
+ #
+ try:
+ dt = re.match("^\((.*)\)", output).group(1)
+ except:
+ self.fail(self.DATA_TYPE_GROKKED)
+
+ # Expect the display type string to contain each and every atoms.
+ self.expect(dt,
+ "Display type: '%s' must contain the type atoms: '%s'" %
+ (dt, atoms),
+ exe=False,
+ substrs = list(atoms))
+
+ # The (var, val) pair must match, too.
+ nv = ("%s = '%s'" if quotedDisplay else "%s = %s") % (var, val)
+ self.expect(output, Msg(var, val, True), exe=False,
+ substrs = [nv])
+ pass
+
+ def generic_type_expr_tester(self, exe_name, atoms, quotedDisplay=False, blockCaptured=False):
+ """Test that variable expressions with basic types are evaluated correctly."""
+
+ self.runCmd("file %s" % exe_name, CURRENT_EXECUTABLE_SET)
+
+ # First, capture the golden output emitted by the oracle, i.e., the
+ # series of printf statements.
+
+ self.process_launch_o(self.golden_filename)
+
+ with open(self.golden_filename) as f:
+ go = f.read()
+
+ # This golden list contains a list of (variable, value) pairs extracted
+ # from the golden output.
+ gl = []
+
+ # Scan the golden output line by line, looking for the pattern:
+ #
+ # variable = 'value'
+ #
+ for line in go.split(os.linesep):
+ # We'll ignore variables of array types from inside a block.
+ if blockCaptured and '[' in line:
+ continue
+ match = self.pattern.search(line)
+ if match:
+ var, val = match.group(1), match.group(2)
+ gl.append((var, val))
+ #print("golden list:", gl)
+
+ # This test uses a #include of "basic_type.cpp" so we need to enable
+ # always setting inlined breakpoints.
+ self.runCmd('settings set target.inline-breakpoint-strategy always')
+ # And add hooks to restore the settings during tearDown().
+ self.addTearDownHook(
+ lambda: self.runCmd("settings set target.inline-breakpoint-strategy headers"))
+
+ # Bring the program to the point where we can issue a series of
+ # 'expr' command.
+ if blockCaptured:
+ break_line = line_number ("basic_type.cpp", "// Break here to test block captured variables.")
+ else:
+ break_line = line_number ("basic_type.cpp", "// Here is the line we will break on to check variables.")
+ lldbutil.run_break_set_by_file_and_line (self, "basic_type.cpp", break_line, num_expected_locations=1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+ self.expect("process status", STOPPED_DUE_TO_BREAKPOINT,
+ substrs = [" at basic_type.cpp:%d" % break_line,
+ "stop reason = breakpoint"])
+
+ #self.runCmd("frame variable --show-types")
+
+ # Now iterate through the golden list, comparing against the output from
+ # 'expr var'.
+ for var, val in gl:
+ self.runCmd("expression %s" % var)
+ output = self.res.GetOutput()
+
+ # The input type is in a canonical form as a set of named atoms.
+ # The display type string must contain each and every element.
+ #
+ # Example:
+ # runCmd: expr a
+ # output: (double) $0 = 1100.12
+ #
+ try:
+ dt = re.match("^\((.*)\) \$[0-9]+ = ", output).group(1)
+ except:
+ self.fail(self.DATA_TYPE_GROKKED)
+
+ # Expect the display type string to contain each and every atoms.
+ self.expect(dt,
+ "Display type: '%s' must contain the type atoms: '%s'" %
+ (dt, atoms),
+ exe=False,
+ substrs = list(atoms))
+
+ # The val part must match, too.
+ valPart = ("'%s'" if quotedDisplay else "%s") % val
+ self.expect(output, Msg(var, val, False), exe=False,
+ substrs = [valPart])
+ pass
diff --git a/packages/Python/lldbsuite/test/types/HideTestFailures.py b/packages/Python/lldbsuite/test/types/HideTestFailures.py
new file mode 100644
index 000000000000..5818166ef5ee
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/HideTestFailures.py
@@ -0,0 +1,78 @@
+"""
+Test that variables of integer basic types are displayed correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import AbstractBase
+import sys
+import lldb
+from lldbsuite.test.lldbtest import *
+
+# rdar://problem/9649573
+# Capture the lldb and gdb-remote log files for test failures when run with no "-w" option
+class DebugIntegerTypesFailures(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # If we're lucky, test_long_type_with_dsym fails.
+ # Let's turn on logging just for that.
+ try:
+ if "test_long_type_with_dsym" in self.id():
+ self.runCmd(
+ "log enable -n -f %s lldb commands event process state" %
+ os.environ["DEBUG_LLDB_LOG"])
+ self.runCmd(
+ "log enable -n -f %s gdb-remote packets process" %
+ os.environ["DEBUG_GDB_REMOTE_LOG"])
+ except:
+ pass
+
+ def tearDown(self):
+ # If we're lucky, test_long_type_with_dsym fails.
+ # Let's turn off logging just for that.
+ if "test_long_type_with_dsym" in self.id():
+ self.runCmd("log disable lldb")
+ self.runCmd("log disable gdb-remote")
+ # Call super's tearDown().
+ TestBase.tearDown(self)
+
+ def test_char_type(self):
+ """Test that char-type variables are displayed correctly."""
+ d = {'CXX_SOURCES': 'char.cpp'}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ self.generic_type_tester(set(['char']), quotedDisplay=True)
+
+ def test_short_type(self):
+ """Test that short-type variables are displayed correctly."""
+ d = {'CXX_SOURCES': 'short.cpp'}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ self.generic_type_tester(set(['short']))
+
+ def test_int_type(self):
+ """Test that int-type variables are displayed correctly."""
+ d = {'CXX_SOURCES': 'int.cpp'}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ self.generic_type_tester(set(['int']))
+
+ def test_long_type(self):
+ """Test that long-type variables are displayed correctly."""
+ d = {'CXX_SOURCES': 'long.cpp'}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ self.generic_type_tester(set(['long']))
+
+ def test_long_long_type(self):
+ """Test that 'long long'-type variables are displayed correctly."""
+ d = {'CXX_SOURCES': 'long_long.cpp'}
+ self.build(dictionary=d)
+ self.setTearDownCleanup(dictionary=d)
+ self.generic_type_tester(set(['long long']))
diff --git a/packages/Python/lldbsuite/test/types/Makefile b/packages/Python/lldbsuite/test/types/Makefile
new file mode 100644
index 000000000000..c1b4cb32561d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/Makefile
@@ -0,0 +1,7 @@
+LEVEL = ../make
+
+# Example:
+#
+# CXX_SOURCES := int.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/types/TestFloatTypes.py b/packages/Python/lldbsuite/test/types/TestFloatTypes.py
new file mode 100644
index 000000000000..01fd4a267804
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/TestFloatTypes.py
@@ -0,0 +1,41 @@
+"""
+Test that variables of floating point types are displayed correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import AbstractBase
+import lldb
+import sys
+from lldbsuite.test.lldbtest import *
+
+class FloatTypesTestCase(AbstractBase.GenericTester):
+
+ mydir = AbstractBase.GenericTester.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ AbstractBase.GenericTester.setUp(self)
+ # disable "There is a running process, kill it and restart?" prompt
+ self.runCmd("settings set auto-confirm true")
+ self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm"))
+
+ def test_float_type(self):
+ """Test that float-type variables are displayed correctly."""
+ self.build_and_run('float.cpp', set(['float']))
+
+ @skipUnlessDarwin
+ def test_float_type_from_block(self):
+ """Test that float-type variables are displayed correctly from a block."""
+ self.build_and_run('float.cpp', set(['float']), bc=True)
+
+ def test_double_type(self):
+ """Test that double-type variables are displayed correctly."""
+ self.build_and_run('double.cpp', set(['double']))
+
+ @skipUnlessDarwin
+ def test_double_type_from_block(self):
+ """Test that double-type variables are displayed correctly from a block."""
+ self.build_and_run('double.cpp', set(['double']), bc=True)
diff --git a/packages/Python/lldbsuite/test/types/TestFloatTypesExpr.py b/packages/Python/lldbsuite/test/types/TestFloatTypesExpr.py
new file mode 100644
index 000000000000..a825a92c66cc
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/TestFloatTypesExpr.py
@@ -0,0 +1,44 @@
+"""
+Test that variable expressions of floating point types are evaluated correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import AbstractBase
+import lldb
+import sys
+from lldbsuite.test.lldbtest import *
+
+class FloatTypesExprTestCase(AbstractBase.GenericTester):
+
+ mydir = AbstractBase.GenericTester.compute_mydir(__file__)
+
+ # rdar://problem/8493023
+ # test/types failures for Test*TypesExpr.py: element offset computed wrong and sign error?
+
+ def setUp(self):
+ # Call super's setUp().
+ AbstractBase.GenericTester.setUp(self)
+ # disable "There is a running process, kill it and restart?" prompt
+ self.runCmd("settings set auto-confirm true")
+ self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm"))
+
+ def test_float_type(self):
+ """Test that float-type variable expressions are evaluated correctly."""
+ self.build_and_run_expr('float.cpp', set(['float']))
+
+ @skipUnlessDarwin
+ def test_float_type_from_block(self):
+ """Test that float-type variables are displayed correctly from a block."""
+ self.build_and_run_expr('float.cpp', set(['float']), bc=True)
+
+ def test_double_type(self):
+ """Test that double-type variable expressions are evaluated correctly."""
+ self.build_and_run_expr('double.cpp', set(['double']))
+
+ @skipUnlessDarwin
+ def test_double_type_from_block(self):
+ """Test that double-type variables are displayed correctly from a block."""
+ self.build_and_run_expr('double.cpp', set(['double']), bc=True)
diff --git a/packages/Python/lldbsuite/test/types/TestIntegerTypes.py b/packages/Python/lldbsuite/test/types/TestIntegerTypes.py
new file mode 100644
index 000000000000..4b979df51db3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/TestIntegerTypes.py
@@ -0,0 +1,113 @@
+"""
+Test that variables of integer basic types are displayed correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import AbstractBase
+import lldb
+import sys
+from lldbsuite.test.lldbtest import *
+
+class IntegerTypesTestCase(AbstractBase.GenericTester):
+
+ mydir = AbstractBase.GenericTester.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ AbstractBase.GenericTester.setUp(self)
+ # disable "There is a running process, kill it and restart?" prompt
+ self.runCmd("settings set auto-confirm true")
+ self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm"))
+
+ def test_char_type(self):
+ """Test that char-type variables are displayed correctly."""
+ self.build_and_run('char.cpp', set(['char']), qd=True)
+
+ @skipUnlessDarwin
+ def test_char_type_from_block(self):
+ """Test that char-type variables are displayed correctly from a block."""
+ self.build_and_run('char.cpp', set(['char']), bc=True, qd=True)
+
+ def test_unsigned_char_type(self):
+ """Test that 'unsigned_char'-type variables are displayed correctly."""
+ self.build_and_run('unsigned_char.cpp', set(['unsigned', 'char']), qd=True)
+
+ @skipUnlessDarwin
+ def test_unsigned_char_type_from_block(self):
+ """Test that 'unsigned char'-type variables are displayed correctly from a block."""
+ self.build_and_run('unsigned_char.cpp', set(['unsigned', 'char']), bc=True, qd=True)
+
+ def test_short_type(self):
+ """Test that short-type variables are displayed correctly."""
+ self.build_and_run('short.cpp', set(['short']))
+
+ @skipUnlessDarwin
+ def test_short_type_from_block(self):
+ """Test that short-type variables are displayed correctly from a block."""
+ self.build_and_run('short.cpp', set(['short']), bc=True)
+
+ def test_unsigned_short_type(self):
+ """Test that 'unsigned_short'-type variables are displayed correctly."""
+ self.build_and_run('unsigned_short.cpp', set(['unsigned', 'short']))
+
+ @skipUnlessDarwin
+ def test_unsigned_short_type_from_block(self):
+ """Test that 'unsigned short'-type variables are displayed correctly from a block."""
+ self.build_and_run('unsigned_short.cpp', set(['unsigned', 'short']), bc=True)
+
+ def test_int_type(self):
+ """Test that int-type variables are displayed correctly."""
+ self.build_and_run('int.cpp', set(['int']))
+
+ @skipUnlessDarwin
+ def test_int_type_from_block(self):
+ """Test that int-type variables are displayed correctly from a block."""
+ self.build_and_run('int.cpp', set(['int']))
+
+ def test_unsigned_int_type(self):
+ """Test that 'unsigned_int'-type variables are displayed correctly."""
+ self.build_and_run('unsigned_int.cpp', set(['unsigned', 'int']))
+
+ @skipUnlessDarwin
+ def test_unsigned_int_type_from_block(self):
+ """Test that 'unsigned int'-type variables are displayed correctly from a block."""
+ self.build_and_run('unsigned_int.cpp', set(['unsigned', 'int']), bc=True)
+
+ def test_long_type(self):
+ """Test that long-type variables are displayed correctly."""
+ self.build_and_run('long.cpp', set(['long']))
+
+ @skipUnlessDarwin
+ def test_long_type_from_block(self):
+ """Test that long-type variables are displayed correctly from a block."""
+ self.build_and_run('long.cpp', set(['long']), bc=True)
+
+ def test_unsigned_long_type(self):
+ """Test that 'unsigned long'-type variables are displayed correctly."""
+ self.build_and_run('unsigned_long.cpp', set(['unsigned', 'long']))
+
+ @skipUnlessDarwin
+ def test_unsigned_long_type_from_block(self):
+ """Test that 'unsigned_long'-type variables are displayed correctly from a block."""
+ self.build_and_run('unsigned_long.cpp', set(['unsigned', 'long']), bc=True)
+
+ def test_long_long_type(self):
+ """Test that 'long long'-type variables are displayed correctly."""
+ self.build_and_run('long_long.cpp', set(['long long']))
+
+ @skipUnlessDarwin
+ def test_long_long_type_from_block(self):
+ """Test that 'long_long'-type variables are displayed correctly from a block."""
+ self.build_and_run('long_long.cpp', set(['long long']), bc=True)
+
+ def test_unsigned_long_long_type(self):
+ """Test that 'unsigned long long'-type variables are displayed correctly."""
+ self.build_and_run('unsigned_long_long.cpp', set(['unsigned', 'long long']))
+
+ @skipUnlessDarwin
+ def test_unsigned_long_long_type_from_block(self):
+ """Test that 'unsigned_long_long'-type variables are displayed correctly from a block."""
+ self.build_and_run('unsigned_long_long.cpp', set(['unsigned', 'long long']), bc=True)
diff --git a/packages/Python/lldbsuite/test/types/TestIntegerTypesExpr.py b/packages/Python/lldbsuite/test/types/TestIntegerTypesExpr.py
new file mode 100644
index 000000000000..c6dda91ad13e
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/TestIntegerTypesExpr.py
@@ -0,0 +1,113 @@
+"""
+Test that variable expressions of integer basic types are evaluated correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import AbstractBase
+import lldb
+import sys
+from lldbsuite.test.lldbtest import *
+
+class IntegerTypesExprTestCase(AbstractBase.GenericTester):
+
+ mydir = AbstractBase.GenericTester.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ AbstractBase.GenericTester.setUp(self)
+ # disable "There is a running process, kill it and restart?" prompt
+ self.runCmd("settings set auto-confirm true")
+ self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm"))
+
+ def test_char_type(self):
+ """Test that char-type variable expressions are evaluated correctly."""
+ self.build_and_run_expr('char.cpp', set(['char']), qd=True)
+
+ @skipUnlessDarwin
+ def test_char_type_from_block(self):
+ """Test that char-type variables are displayed correctly from a block."""
+ self.build_and_run_expr('char.cpp', set(['char']), bc=True, qd=True)
+
+ def test_unsigned_char_type(self):
+ """Test that 'unsigned_char'-type variable expressions are evaluated correctly."""
+ self.build_and_run_expr('unsigned_char.cpp', set(['unsigned', 'char']), qd=True)
+
+ @skipUnlessDarwin
+ def test_unsigned_char_type_from_block(self):
+ """Test that 'unsigned char'-type variables are displayed correctly from a block."""
+ self.build_and_run_expr('unsigned_char.cpp', set(['unsigned', 'char']), bc=True, qd=True)
+
+ def test_short_type(self):
+ """Test that short-type variable expressions are evaluated correctly."""
+ self.build_and_run_expr('short.cpp', set(['short']))
+
+ @skipUnlessDarwin
+ def test_short_type_from_block(self):
+ """Test that short-type variables are displayed correctly from a block."""
+ self.build_and_run_expr('short.cpp', set(['short']), bc=True)
+
+ def test_unsigned_short_type(self):
+ """Test that 'unsigned_short'-type variable expressions are evaluated correctly."""
+ self.build_and_run_expr('unsigned_short.cpp', set(['unsigned', 'short']))
+
+ @skipUnlessDarwin
+ def test_unsigned_short_type_from_block(self):
+ """Test that 'unsigned short'-type variables are displayed correctly from a block."""
+ self.build_and_run_expr('unsigned_short.cpp', set(['unsigned', 'short']), bc=True)
+
+ def test_int_type(self):
+ """Test that int-type variable expressions are evaluated correctly."""
+ self.build_and_run_expr('int.cpp', set(['int']))
+
+ @skipUnlessDarwin
+ def test_int_type_from_block(self):
+ """Test that int-type variables are displayed correctly from a block."""
+ self.build_and_run_expr('int.cpp', set(['int']))
+
+ def test_unsigned_int_type(self):
+ """Test that 'unsigned_int'-type variable expressions are evaluated correctly."""
+ self.build_and_run_expr('unsigned_int.cpp', set(['unsigned', 'int']))
+
+ @skipUnlessDarwin
+ def test_unsigned_int_type_from_block(self):
+ """Test that 'unsigned int'-type variables are displayed correctly from a block."""
+ self.build_and_run_expr('unsigned_int.cpp', set(['unsigned', 'int']), bc=True)
+
+ def test_long_type(self):
+ """Test that long-type variable expressions are evaluated correctly."""
+ self.build_and_run_expr('long.cpp', set(['long']))
+
+ @skipUnlessDarwin
+ def test_long_type_from_block(self):
+ """Test that long-type variables are displayed correctly from a block."""
+ self.build_and_run_expr('long.cpp', set(['long']), bc=True)
+
+ def test_unsigned_long_type(self):
+ """Test that 'unsigned long'-type variable expressions are evaluated correctly."""
+ self.build_and_run_expr('unsigned_long.cpp', set(['unsigned', 'long']))
+
+ @skipUnlessDarwin
+ def test_unsigned_long_type_from_block(self):
+ """Test that 'unsigned_long'-type variables are displayed correctly from a block."""
+ self.build_and_run_expr('unsigned_long.cpp', set(['unsigned', 'long']), bc=True)
+
+ def test_long_long_type(self):
+ """Test that 'long long'-type variable expressions are evaluated correctly."""
+ self.build_and_run_expr('long_long.cpp', set(['long long']))
+
+ @skipUnlessDarwin
+ def test_long_long_type_from_block(self):
+ """Test that 'long_long'-type variables are displayed correctly from a block."""
+ self.build_and_run_expr('long_long.cpp', set(['long long']), bc=True)
+
+ def test_unsigned_long_long_type(self):
+ """Test that 'unsigned long long'-type variable expressions are evaluated correctly."""
+ self.build_and_run_expr('unsigned_long_long.cpp', set(['unsigned', 'long long']))
+
+ @skipUnlessDarwin
+ def test_unsigned_long_long_type_from_block(self):
+ """Test that 'unsigned_long_long'-type variables are displayed correctly from a block."""
+ self.build_and_run_expr('unsigned_long_long.cpp', set(['unsigned', 'long long']), bc=True)
diff --git a/packages/Python/lldbsuite/test/types/TestRecursiveTypes.py b/packages/Python/lldbsuite/test/types/TestRecursiveTypes.py
new file mode 100644
index 000000000000..0b60b5a4d63a
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/TestRecursiveTypes.py
@@ -0,0 +1,51 @@
+"""
+Test that recursive types are handled correctly.
+"""
+
+from __future__ import print_function
+
+
+
+import lldb
+import lldbsuite.test.lldbutil as lldbutil
+import sys
+from lldbsuite.test.lldbtest import *
+
+class RecursiveTypesTestCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ # Call super's setUp().
+ TestBase.setUp(self)
+ # disable "There is a running process, kill it and restart?" prompt
+ self.runCmd("settings set auto-confirm true")
+ self.addTearDownHook(lambda: self.runCmd("settings clear auto-confirm"))
+ # Find the line number to break for main.c.
+ self.line = line_number('recursive_type_main.cpp',
+ '// Test at this line.')
+
+ self.d1 = {'CXX_SOURCES': 'recursive_type_main.cpp recursive_type_1.cpp'}
+ self.d2 = {'CXX_SOURCES': 'recursive_type_main.cpp recursive_type_2.cpp'}
+
+ def test_recursive_type_1(self):
+ """Test that recursive structs are displayed correctly."""
+ self.build(dictionary=self.d1)
+ self.setTearDownCleanup(dictionary=self.d1)
+ self.print_struct()
+
+ def test_recursive_type_2(self):
+ """Test that recursive structs are displayed correctly."""
+ self.build(dictionary=self.d2)
+ self.setTearDownCleanup(dictionary=self.d2)
+ self.print_struct()
+
+ def print_struct(self):
+ self.runCmd("file a.out", CURRENT_EXECUTABLE_SET)
+
+ lldbutil.run_break_set_by_file_and_line (self, "recursive_type_main.cpp", self.line, num_expected_locations=-1, loc_exact=True)
+
+ self.runCmd("run", RUN_SUCCEEDED)
+
+ self.expect("print tpi", RUN_SUCCEEDED)
+ self.expect("print *tpi", RUN_SUCCEEDED)
diff --git a/packages/Python/lldbsuite/test/types/basic_type.cpp b/packages/Python/lldbsuite/test/types/basic_type.cpp
new file mode 100644
index 000000000000..1651815fa0ca
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/basic_type.cpp
@@ -0,0 +1,211 @@
+// This file must have the following defined before it is included:
+// T defined to the type to test (int, float, etc)
+// T_CSTR a C string representation of the type T ("int", "float")
+// T_VALUE_1 defined to a valid initializer value for TEST_TYPE (7 for int, 2.0 for float)
+// T_VALUE_2, T_VALUE_3, T_VALUE_4 defined to a valid initializer value for TEST_TYPE that is different from TEST_VALUE_1
+// T_PRINTF_FORMAT defined if T can be printed with printf
+//
+// An example for integers is below
+#if 0
+
+#define T int
+#define T_CSTR "int"
+#define T_VALUE_1 11001110
+#define T_VALUE_2 22002220
+#define T_VALUE_3 33003330
+#define T_VALUE_4 44044440
+#define T_PRINTF_FORMAT "%i"
+
+#include "basic_type.cpp"
+
+#endif
+
+#ifdef TEST_BLOCK_CAPTURED_VARS
+#include <dispatch/dispatch.h>
+#endif
+
+class a_class
+{
+public:
+ a_class (const T& a, const T& b) :
+ m_a (a),
+ m_b (b)
+ {
+ }
+
+ ~a_class ()
+ {
+ }
+
+ const T&
+ get_a() const
+ {
+ return m_a;
+ }
+
+ void
+ set_a (const T& a)
+ {
+ m_a = a;
+ }
+
+ const T&
+ get_b() const
+ {
+ return m_b;
+ }
+
+ void
+ set_b (const T& b)
+ {
+ m_b = b;
+ }
+
+protected:
+ T m_a;
+ T m_b;
+};
+
+typedef struct a_struct_tag {
+ T a;
+ T b;
+} a_struct_t;
+
+
+typedef union a_union_zero_tag {
+ T a;
+ double a_double;
+} a_union_zero_t;
+
+typedef struct a_union_nonzero_tag {
+ double a_double;
+ a_union_zero_t u;
+} a_union_nonzero_t;
+
+
+#include <stdint.h>
+#include <stdio.h>
+
+int
+main (int argc, char const *argv[])
+{
+ T a = T_VALUE_1;
+ T* a_ptr = &a;
+ T& a_ref = a;
+ T a_array_bounded[2] = { T_VALUE_1, T_VALUE_2 };
+ T a_array_unbounded[] = { T_VALUE_1, T_VALUE_2 };
+
+ a_class a_class_instance (T_VALUE_1, T_VALUE_2);
+ a_class *a_class_ptr = &a_class_instance;
+ a_class &a_class_ref = a_class_instance;
+
+ a_struct_t a_struct = { T_VALUE_1, T_VALUE_2 };
+ a_struct_t *a_struct_ptr = &a_struct;
+ a_struct_t &a_struct_ref = a_struct;
+
+ // Create a union with type T at offset zero
+ a_union_zero_t a_union_zero;
+ a_union_zero.a = T_VALUE_1;
+ a_union_zero_t *a_union_zero_ptr = &a_union_zero;
+ a_union_zero_t &a_union_zero_ref = a_union_zero;
+
+ // Create a union with type T at a non-zero offset
+ a_union_nonzero_t a_union_nonzero;
+ a_union_nonzero.u.a = T_VALUE_1;
+ a_union_nonzero_t *a_union_nonzero_ptr = &a_union_nonzero;
+ a_union_nonzero_t &a_union_nonzero_ref = a_union_nonzero;
+
+ a_struct_t a_struct_array_bounded[2] = {{ T_VALUE_1, T_VALUE_2 }, { T_VALUE_3, T_VALUE_4 }};
+ a_struct_t a_struct_array_unbounded[] = {{ T_VALUE_1, T_VALUE_2 }, { T_VALUE_3, T_VALUE_4 }};
+ a_union_zero_t a_union_zero_array_bounded[2];
+ a_union_zero_array_bounded[0].a = T_VALUE_1;
+ a_union_zero_array_bounded[1].a = T_VALUE_2;
+ a_union_zero_t a_union_zero_array_unbounded[] = {{ T_VALUE_1 }, { T_VALUE_2 }};
+
+#ifdef T_PRINTF_FORMAT
+ printf ("%s: a = '" T_PRINTF_FORMAT "'\n", T_CSTR, a);
+ printf ("%s*: %p => *a_ptr = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_ptr, *a_ptr);
+ printf ("%s&: @%p => a_ref = '" T_PRINTF_FORMAT "'\n", T_CSTR, &a_ref, a_ref);
+
+ printf ("%s[2]: a_array_bounded[0] = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_array_bounded[0]);
+ printf ("%s[2]: a_array_bounded[1] = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_array_bounded[1]);
+
+ printf ("%s[]: a_array_unbounded[0] = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_array_unbounded[0]);
+ printf ("%s[]: a_array_unbounded[1] = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_array_unbounded[1]);
+
+ printf ("(a_class) a_class_instance.m_a = '" T_PRINTF_FORMAT "'\n", a_class_instance.get_a());
+ printf ("(a_class) a_class_instance.m_b = '" T_PRINTF_FORMAT "'\n", a_class_instance.get_b());
+ printf ("(a_class*) a_class_ptr = %p, a_class_ptr->m_a = '" T_PRINTF_FORMAT "'\n", a_class_ptr, a_class_ptr->get_a());
+ printf ("(a_class*) a_class_ptr = %p, a_class_ptr->m_b = '" T_PRINTF_FORMAT "'\n", a_class_ptr, a_class_ptr->get_b());
+ printf ("(a_class&) a_class_ref = %p, a_class_ref.m_a = '" T_PRINTF_FORMAT "'\n", &a_class_ref, a_class_ref.get_a());
+ printf ("(a_class&) a_class_ref = %p, a_class_ref.m_b = '" T_PRINTF_FORMAT "'\n", &a_class_ref, a_class_ref.get_b());
+
+ printf ("(a_struct_t) a_struct.a = '" T_PRINTF_FORMAT "'\n", a_struct.a);
+ printf ("(a_struct_t) a_struct.b = '" T_PRINTF_FORMAT "'\n", a_struct.b);
+ printf ("(a_struct_t*) a_struct_ptr = %p, a_struct_ptr->a = '" T_PRINTF_FORMAT "'\n", a_struct_ptr, a_struct_ptr->a);
+ printf ("(a_struct_t*) a_struct_ptr = %p, a_struct_ptr->b = '" T_PRINTF_FORMAT "'\n", a_struct_ptr, a_struct_ptr->b);
+ printf ("(a_struct_t&) a_struct_ref = %p, a_struct_ref.a = '" T_PRINTF_FORMAT "'\n", &a_struct_ref, a_struct_ref.a);
+ printf ("(a_struct_t&) a_struct_ref = %p, a_struct_ref.b = '" T_PRINTF_FORMAT "'\n", &a_struct_ref, a_struct_ref.b);
+
+ printf ("(a_union_zero_t) a_union_zero.a = '" T_PRINTF_FORMAT "'\n", a_union_zero.a);
+ printf ("(a_union_zero_t*) a_union_zero_ptr = %p, a_union_zero_ptr->a = '" T_PRINTF_FORMAT "'\n", a_union_zero_ptr, a_union_zero_ptr->a);
+ printf ("(a_union_zero_t&) a_union_zero_ref = %p, a_union_zero_ref.a = '" T_PRINTF_FORMAT "'\n", &a_union_zero_ref, a_union_zero_ref.a);
+
+ printf ("(a_union_nonzero_t) a_union_nonzero.u.a = '" T_PRINTF_FORMAT "'\n", a_union_nonzero.u.a);
+ printf ("(a_union_nonzero_t*) a_union_nonzero_ptr = %p, a_union_nonzero_ptr->u.a = '" T_PRINTF_FORMAT "'\n", a_union_nonzero_ptr, a_union_nonzero_ptr->u.a);
+ printf ("(a_union_nonzero_t&) a_union_nonzero_ref = %p, a_union_nonzero_ref.u.a = '" T_PRINTF_FORMAT "'\n", &a_union_nonzero_ref, a_union_nonzero_ref.u.a);
+
+ printf ("(a_struct_t[2]) a_struct_array_bounded[0].a = '" T_PRINTF_FORMAT "'\n", a_struct_array_bounded[0].a);
+ printf ("(a_struct_t[2]) a_struct_array_bounded[0].b = '" T_PRINTF_FORMAT "'\n", a_struct_array_bounded[0].b);
+ printf ("(a_struct_t[2]) a_struct_array_bounded[1].a = '" T_PRINTF_FORMAT "'\n", a_struct_array_bounded[1].a);
+ printf ("(a_struct_t[2]) a_struct_array_bounded[1].b = '" T_PRINTF_FORMAT "'\n", a_struct_array_bounded[1].b);
+
+ printf ("(a_struct_t[]) a_struct_array_unbounded[0].a = '" T_PRINTF_FORMAT "'\n", a_struct_array_unbounded[0].a);
+ printf ("(a_struct_t[]) a_struct_array_unbounded[0].b = '" T_PRINTF_FORMAT "'\n", a_struct_array_unbounded[0].b);
+ printf ("(a_struct_t[]) a_struct_array_unbounded[1].a = '" T_PRINTF_FORMAT "'\n", a_struct_array_unbounded[1].a);
+ printf ("(a_struct_t[]) a_struct_array_unbounded[1].b = '" T_PRINTF_FORMAT "'\n", a_struct_array_unbounded[1].b);
+
+ printf ("(a_union_zero_t[2]) a_union_zero_array_bounded[0].a = '" T_PRINTF_FORMAT "'\n", a_union_zero_array_bounded[0].a);
+ printf ("(a_union_zero_t[2]) a_union_zero_array_bounded[1].a = '" T_PRINTF_FORMAT "'\n", a_union_zero_array_bounded[1].a);
+
+ printf ("(a_union_zero_t[]) a_union_zero_array_unbounded[0].a = '" T_PRINTF_FORMAT "'\n", a_union_zero_array_unbounded[0].a);
+ printf ("(a_union_zero_t[]) a_union_zero_array_unbounded[1].a = '" T_PRINTF_FORMAT "'\n", a_union_zero_array_unbounded[1].a);
+
+#endif
+ puts("About to exit, break here to check values..."); // Here is the line we will break on to check variables.
+
+#ifdef TEST_BLOCK_CAPTURED_VARS
+ void (^myBlock)() = ^() {
+ printf ("%s: a = '" T_PRINTF_FORMAT "'\n", T_CSTR, a);
+ printf ("%s*: %p => *a_ptr = '" T_PRINTF_FORMAT "'\n", T_CSTR, a_ptr, *a_ptr);
+ printf ("%s&: @%p => a_ref = '" T_PRINTF_FORMAT "'\n", T_CSTR, &a_ref, a_ref);
+
+ printf ("(a_class) a_class_instance.m_a = '" T_PRINTF_FORMAT "'\n", a_class_instance.get_a());
+ printf ("(a_class) a_class_instance.m_b = '" T_PRINTF_FORMAT "'\n", a_class_instance.get_b());
+ printf ("(a_class*) a_class_ptr = %p, a_class_ptr->m_a = '" T_PRINTF_FORMAT "'\n", a_class_ptr, a_class_ptr->get_a());
+ printf ("(a_class*) a_class_ptr = %p, a_class_ptr->m_b = '" T_PRINTF_FORMAT "'\n", a_class_ptr, a_class_ptr->get_b());
+ printf ("(a_class&) a_class_ref = %p, a_class_ref.m_a = '" T_PRINTF_FORMAT "'\n", &a_class_ref, a_class_ref.get_a());
+ printf ("(a_class&) a_class_ref = %p, a_class_ref.m_b = '" T_PRINTF_FORMAT "'\n", &a_class_ref, a_class_ref.get_b());
+
+ printf ("(a_struct_t) a_struct.a = '" T_PRINTF_FORMAT "'\n", a_struct.a);
+ printf ("(a_struct_t) a_struct.b = '" T_PRINTF_FORMAT "'\n", a_struct.b);
+ printf ("(a_struct_t*) a_struct_ptr = %p, a_struct_ptr->a = '" T_PRINTF_FORMAT "'\n", a_struct_ptr, a_struct_ptr->a);
+ printf ("(a_struct_t*) a_struct_ptr = %p, a_struct_ptr->b = '" T_PRINTF_FORMAT "'\n", a_struct_ptr, a_struct_ptr->b);
+ printf ("(a_struct_t&) a_struct_ref = %p, a_struct_ref.a = '" T_PRINTF_FORMAT "'\n", &a_struct_ref, a_struct_ref.a);
+ printf ("(a_struct_t&) a_struct_ref = %p, a_struct_ref.b = '" T_PRINTF_FORMAT "'\n", &a_struct_ref, a_struct_ref.b);
+
+ printf ("(a_union_zero_t) a_union_zero.a = '" T_PRINTF_FORMAT "'\n", a_union_zero.a);
+ printf ("(a_union_zero_t*) a_union_zero_ptr = %p, a_union_zero_ptr->a = '" T_PRINTF_FORMAT "'\n", a_union_zero_ptr, a_union_zero_ptr->a);
+ printf ("(a_union_zero_t&) a_union_zero_ref = %p, a_union_zero_ref.a = '" T_PRINTF_FORMAT "'\n", &a_union_zero_ref, a_union_zero_ref.a);
+
+ printf ("(a_union_nonzero_t) a_union_nonzero.u.a = '" T_PRINTF_FORMAT "'\n", a_union_nonzero.u.a);
+ printf ("(a_union_nonzero_t*) a_union_nonzero_ptr = %p, a_union_nonzero_ptr->u.a = '" T_PRINTF_FORMAT "'\n", a_union_nonzero_ptr, a_union_nonzero_ptr->u.a);
+ printf ("(a_union_nonzero_t&) a_union_nonzero_ref = %p, a_union_nonzero_ref.u.a = '" T_PRINTF_FORMAT "'\n", &a_union_nonzero_ref, a_union_nonzero_ref.u.a);
+
+ printf ("That's All Folks!\n"); // Break here to test block captured variables.
+ };
+
+ myBlock();
+#endif
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/types/char.cpp b/packages/Python/lldbsuite/test/types/char.cpp
new file mode 100644
index 000000000000..584582ed9b9c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/char.cpp
@@ -0,0 +1,9 @@
+#define T char
+#define T_CSTR "char"
+#define T_VALUE_1 'a'
+#define T_VALUE_2 'b'
+#define T_VALUE_3 '!'
+#define T_VALUE_4 '~'
+#define T_PRINTF_FORMAT "%c"
+
+#include "basic_type.cpp"
diff --git a/packages/Python/lldbsuite/test/types/double.cpp b/packages/Python/lldbsuite/test/types/double.cpp
new file mode 100644
index 000000000000..6788dadfe02f
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/double.cpp
@@ -0,0 +1,9 @@
+#define T double
+#define T_CSTR "double"
+#define T_VALUE_1 1100.125
+#define T_VALUE_2 2200.250
+#define T_VALUE_3 33.00
+#define T_VALUE_4 44.00
+#define T_PRINTF_FORMAT "%lg"
+
+#include "basic_type.cpp"
diff --git a/packages/Python/lldbsuite/test/types/float.cpp b/packages/Python/lldbsuite/test/types/float.cpp
new file mode 100644
index 000000000000..4bc124661aad
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/float.cpp
@@ -0,0 +1,9 @@
+#define T float
+#define T_CSTR "float"
+#define T_VALUE_1 1100.125
+#define T_VALUE_2 2200.250
+#define T_VALUE_3 33.00
+#define T_VALUE_4 44.00
+#define T_PRINTF_FORMAT "%g"
+
+#include "basic_type.cpp"
diff --git a/packages/Python/lldbsuite/test/types/int.cpp b/packages/Python/lldbsuite/test/types/int.cpp
new file mode 100644
index 000000000000..922398b1c6e3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/int.cpp
@@ -0,0 +1,9 @@
+#define T int
+#define T_CSTR "int"
+#define T_VALUE_1 11001110
+#define T_VALUE_2 22002220
+#define T_VALUE_3 33003330
+#define T_VALUE_4 44004440
+#define T_PRINTF_FORMAT "%i"
+
+#include "basic_type.cpp"
diff --git a/packages/Python/lldbsuite/test/types/long.cpp b/packages/Python/lldbsuite/test/types/long.cpp
new file mode 100644
index 000000000000..9056b42ee77d
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/long.cpp
@@ -0,0 +1,18 @@
+#define T long
+#define T_CSTR "long"
+
+#ifdef __LP64__
+#define T_VALUE_1 110011101111
+#define T_VALUE_2 220022202222
+#define T_VALUE_3 330033303333
+#define T_VALUE_4 440044404444
+#else
+#define T_VALUE_1 110011101
+#define T_VALUE_2 220022202
+#define T_VALUE_3 330033303
+#define T_VALUE_4 440044404
+#endif
+
+#define T_PRINTF_FORMAT "%ld"
+
+#include "basic_type.cpp"
diff --git a/packages/Python/lldbsuite/test/types/long_long.cpp b/packages/Python/lldbsuite/test/types/long_long.cpp
new file mode 100644
index 000000000000..5b442e7257e9
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/long_long.cpp
@@ -0,0 +1,18 @@
+#define T long long
+#define T_CSTR "long long"
+
+#ifdef __LP64__
+#define T_VALUE_1 110011101111
+#define T_VALUE_2 220022202222
+#define T_VALUE_3 330033303333
+#define T_VALUE_4 440044404444
+#else
+#define T_VALUE_1 110011101
+#define T_VALUE_2 220022202
+#define T_VALUE_3 330033303
+#define T_VALUE_4 440044404
+#endif
+
+#define T_PRINTF_FORMAT "%lld"
+
+#include "basic_type.cpp"
diff --git a/packages/Python/lldbsuite/test/types/recursive_type_1.cpp b/packages/Python/lldbsuite/test/types/recursive_type_1.cpp
new file mode 100644
index 000000000000..81d923ffd945
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/recursive_type_1.cpp
@@ -0,0 +1,12 @@
+typedef struct t *tp;
+typedef tp (*get_tp)();
+
+struct s {
+ get_tp get_tp_p;
+};
+
+struct t {
+ struct s *s;
+};
+
+struct t t;
diff --git a/packages/Python/lldbsuite/test/types/recursive_type_2.cpp b/packages/Python/lldbsuite/test/types/recursive_type_2.cpp
new file mode 100644
index 000000000000..304739049a06
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/recursive_type_2.cpp
@@ -0,0 +1,10 @@
+typedef struct t *tp;
+typedef tp (*get_tp)();
+
+struct t {
+ struct {
+ get_tp get_tp_p;
+ };
+};
+
+struct t t;
diff --git a/packages/Python/lldbsuite/test/types/recursive_type_main.cpp b/packages/Python/lldbsuite/test/types/recursive_type_main.cpp
new file mode 100644
index 000000000000..e06cd309be30
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/recursive_type_main.cpp
@@ -0,0 +1,8 @@
+typedef struct t *tp;
+extern struct t t;
+
+int main() {
+ tp tpi = &t;
+ // Test at this line.
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/types/short.cpp b/packages/Python/lldbsuite/test/types/short.cpp
new file mode 100644
index 000000000000..470c68aa8ba7
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/short.cpp
@@ -0,0 +1,9 @@
+#define T short
+#define T_CSTR "short"
+#define T_VALUE_1 11001
+#define T_VALUE_2 22002
+#define T_VALUE_3 -32768
+#define T_VALUE_4 32767
+#define T_PRINTF_FORMAT "%hd"
+
+#include "basic_type.cpp"
diff --git a/packages/Python/lldbsuite/test/types/unsigned_char.cpp b/packages/Python/lldbsuite/test/types/unsigned_char.cpp
new file mode 100644
index 000000000000..0ac555a5a183
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/unsigned_char.cpp
@@ -0,0 +1,9 @@
+#define T unsigned char
+#define T_CSTR "unsigned char"
+#define T_VALUE_1 '0'
+#define T_VALUE_2 '9'
+#define T_VALUE_3 '@'
+#define T_VALUE_4 '$'
+#define T_PRINTF_FORMAT "%c"
+
+#include "basic_type.cpp"
diff --git a/packages/Python/lldbsuite/test/types/unsigned_int.cpp b/packages/Python/lldbsuite/test/types/unsigned_int.cpp
new file mode 100644
index 000000000000..1b307b04afc1
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/unsigned_int.cpp
@@ -0,0 +1,9 @@
+#define T unsigned int
+#define T_CSTR "unsigned int"
+#define T_VALUE_1 11001110
+#define T_VALUE_2 22002220
+#define T_VALUE_3 33003330
+#define T_VALUE_4 44004440
+#define T_PRINTF_FORMAT "%u"
+
+#include "basic_type.cpp"
diff --git a/packages/Python/lldbsuite/test/types/unsigned_long.cpp b/packages/Python/lldbsuite/test/types/unsigned_long.cpp
new file mode 100644
index 000000000000..0c442e399d53
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/unsigned_long.cpp
@@ -0,0 +1,18 @@
+#define T unsigned long
+#define T_CSTR "unsigned long"
+
+#ifdef __LP64__
+#define T_VALUE_1 110011101111
+#define T_VALUE_2 220022202222
+#define T_VALUE_3 330033303333
+#define T_VALUE_4 440044404444
+#else
+#define T_VALUE_1 110011101
+#define T_VALUE_2 220022202
+#define T_VALUE_3 330033303
+#define T_VALUE_4 440044404
+#endif
+
+#define T_PRINTF_FORMAT "%lu"
+
+#include "basic_type.cpp"
diff --git a/packages/Python/lldbsuite/test/types/unsigned_long_long.cpp b/packages/Python/lldbsuite/test/types/unsigned_long_long.cpp
new file mode 100644
index 000000000000..648aad01b3a3
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/unsigned_long_long.cpp
@@ -0,0 +1,18 @@
+#define T unsigned long long
+#define T_CSTR "unsigned long long"
+
+#ifdef __LP64__
+#define T_VALUE_1 110011101111
+#define T_VALUE_2 220022202222
+#define T_VALUE_3 330033303333
+#define T_VALUE_4 440044404444
+#else
+#define T_VALUE_1 110011101
+#define T_VALUE_2 220022202
+#define T_VALUE_3 330033303
+#define T_VALUE_4 440044404
+#endif
+
+#define T_PRINTF_FORMAT "%llu"
+
+#include "basic_type.cpp"
diff --git a/packages/Python/lldbsuite/test/types/unsigned_short.cpp b/packages/Python/lldbsuite/test/types/unsigned_short.cpp
new file mode 100644
index 000000000000..09af2aad62c2
--- /dev/null
+++ b/packages/Python/lldbsuite/test/types/unsigned_short.cpp
@@ -0,0 +1,9 @@
+#define T unsigned short
+#define T_CSTR "unsigned short"
+#define T_VALUE_1 11001
+#define T_VALUE_2 22002
+#define T_VALUE_3 0
+#define T_VALUE_4 65535
+#define T_PRINTF_FORMAT "%hu"
+
+#include "basic_type.cpp"
diff --git a/packages/Python/lldbsuite/test/warnings/uuid/Makefile b/packages/Python/lldbsuite/test/warnings/uuid/Makefile
new file mode 100644
index 000000000000..8a7102e347af
--- /dev/null
+++ b/packages/Python/lldbsuite/test/warnings/uuid/Makefile
@@ -0,0 +1,5 @@
+LEVEL = ../../make
+
+CXX_SOURCES := main.cpp
+
+include $(LEVEL)/Makefile.rules
diff --git a/packages/Python/lldbsuite/test/warnings/uuid/TestAddDsymCommand.py b/packages/Python/lldbsuite/test/warnings/uuid/TestAddDsymCommand.py
new file mode 100644
index 000000000000..002a7aef0c76
--- /dev/null
+++ b/packages/Python/lldbsuite/test/warnings/uuid/TestAddDsymCommand.py
@@ -0,0 +1,107 @@
+"""Test that the 'add-dsym', aka 'target symbols add', command informs the user about success or failure."""
+
+from __future__ import print_function
+
+
+
+import os, time
+import lldb
+from lldbsuite.test.lldbtest import *
+
+@skipUnlessDarwin
+class AddDsymCommandCase(TestBase):
+
+ mydir = TestBase.compute_mydir(__file__)
+
+ def setUp(self):
+ TestBase.setUp(self)
+ self.template = 'main.cpp.template'
+ self.source = 'main.cpp'
+ self.teardown_hook_added = False
+
+ @no_debug_info_test
+ def test_add_dsym_command_with_error(self):
+ """Test that the 'add-dsym' command informs the user about failures."""
+
+ # Call the program generator to produce main.cpp, version 1.
+ self.generate_main_cpp(version=1)
+ self.buildDsym(clean=True)
+
+ # Insert some delay and then call the program generator to produce main.cpp, version 2.
+ time.sleep(5)
+ self.generate_main_cpp(version=101)
+ # Now call make again, but this time don't generate the dSYM.
+ self.buildDwarf(clean=False)
+
+ self.exe_name = 'a.out'
+ self.do_add_dsym_with_error(self.exe_name)
+
+ @no_debug_info_test
+ def test_add_dsym_command_with_success(self):
+ """Test that the 'add-dsym' command informs the user about success."""
+
+ # Call the program generator to produce main.cpp, version 1.
+ self.generate_main_cpp(version=1)
+ self.buildDsym(clean=True)
+
+ self.exe_name = 'a.out'
+ self.do_add_dsym_with_success(self.exe_name)
+
+ @no_debug_info_test
+ def test_add_dsym_with_dSYM_bundle(self):
+ """Test that the 'add-dsym' command informs the user about success."""
+
+ # Call the program generator to produce main.cpp, version 1.
+ self.generate_main_cpp(version=1)
+ self.buildDsym(clean=True)
+
+ self.exe_name = 'a.out'
+ self.do_add_dsym_with_dSYM_bundle(self.exe_name)
+
+
+ def generate_main_cpp(self, version=0):
+ """Generate main.cpp from main.cpp.template."""
+ temp = os.path.join(os.getcwd(), self.template)
+ with open(temp, 'r') as f:
+ content = f.read()
+
+ new_content = content.replace('%ADD_EXTRA_CODE%',
+ 'printf("This is version %d\\n");' % version)
+ src = os.path.join(os.getcwd(), self.source)
+ with open(src, 'w') as f:
+ f.write(new_content)
+
+ # The main.cpp has been generated, add a teardown hook to remove it.
+ if not self.teardown_hook_added:
+ self.addTearDownHook(lambda: os.remove(src))
+ self.teardown_hook_added = True
+
+ def do_add_dsym_with_error(self, exe_name):
+ """Test that the 'add-dsym' command informs the user about failures."""
+ self.runCmd("file " + exe_name, CURRENT_EXECUTABLE_SET)
+
+ wrong_path = os.path.join("%s.dSYM" % exe_name, "Contents")
+ self.expect("add-dsym " + wrong_path, error=True,
+ substrs = ['invalid module path'])
+
+ right_path = os.path.join("%s.dSYM" % exe_name, "Contents", "Resources", "DWARF", exe_name)
+ self.expect("add-dsym " + right_path, error=True,
+ substrs = ['symbol file', 'does not match'])
+
+ def do_add_dsym_with_success(self, exe_name):
+ """Test that the 'add-dsym' command informs the user about success."""
+ self.runCmd("file " + exe_name, CURRENT_EXECUTABLE_SET)
+
+ # This time, the UUID should match and we expect some feedback from lldb.
+ right_path = os.path.join("%s.dSYM" % exe_name, "Contents", "Resources", "DWARF", exe_name)
+ self.expect("add-dsym " + right_path,
+ substrs = ['symbol file', 'has been added to'])
+
+ def do_add_dsym_with_dSYM_bundle(self, exe_name):
+ """Test that the 'add-dsym' command informs the user about success when loading files in bundles."""
+ self.runCmd("file " + exe_name, CURRENT_EXECUTABLE_SET)
+
+ # This time, the UUID should be found inside the bundle
+ right_path = "%s.dSYM" % exe_name
+ self.expect("add-dsym " + right_path,
+ substrs = ['symbol file', 'has been added to'])
diff --git a/packages/Python/lldbsuite/test/warnings/uuid/main.cpp.template b/packages/Python/lldbsuite/test/warnings/uuid/main.cpp.template
new file mode 100644
index 000000000000..d952c9686b57
--- /dev/null
+++ b/packages/Python/lldbsuite/test/warnings/uuid/main.cpp.template
@@ -0,0 +1,19 @@
+//===-- main.cpp ------------------------------------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+
+#include <stdio.h>
+
+int
+main(int argc, char const *argv[])
+{
+ int my_int = argc + 3;
+ printf("Hello UUID Mismatch: %d\n", my_int); // Set breakpoint here.
+ %ADD_EXTRA_CODE%
+ return 0;
+}
diff --git a/packages/Python/lldbsuite/test/xunit_formatter.py b/packages/Python/lldbsuite/test/xunit_formatter.py
new file mode 100644
index 000000000000..35fdba449a0c
--- /dev/null
+++ b/packages/Python/lldbsuite/test/xunit_formatter.py
@@ -0,0 +1,565 @@
+"""
+ The LLVM Compiler Infrastructure
+
+This file is distributed under the University of Illinois Open Source
+License. See LICENSE.TXT for details.
+
+Provides an xUnit ResultsFormatter for integrating the LLDB
+test suite with the Jenkins xUnit aggregator and other xUnit-compliant
+test output processors.
+"""
+from __future__ import print_function
+from __future__ import absolute_import
+
+# System modules
+import re
+import sys
+import xml.sax.saxutils
+
+# Third-party modules
+import six
+
+# Local modules
+from .result_formatter import EventBuilder
+from .result_formatter import ResultsFormatter
+
+
+class XunitFormatter(ResultsFormatter):
+ """Provides xUnit-style formatted output.
+ """
+
+ # Result mapping arguments
+ RM_IGNORE = 'ignore'
+ RM_SUCCESS = 'success'
+ RM_FAILURE = 'failure'
+ RM_PASSTHRU = 'passthru'
+
+ @staticmethod
+ def _build_illegal_xml_regex():
+ """Contructs a regex to match all illegal xml characters.
+
+ Expects to be used against a unicode string."""
+ # Construct the range pairs of invalid unicode chareacters.
+ illegal_chars_u = [
+ (0x00, 0x08), (0x0B, 0x0C), (0x0E, 0x1F), (0x7F, 0x84),
+ (0x86, 0x9F), (0xFDD0, 0xFDDF), (0xFFFE, 0xFFFF)]
+
+ # For wide builds, we have more.
+ if sys.maxunicode >= 0x10000:
+ illegal_chars_u.extend(
+ [(0x1FFFE, 0x1FFFF), (0x2FFFE, 0x2FFFF), (0x3FFFE, 0x3FFFF),
+ (0x4FFFE, 0x4FFFF), (0x5FFFE, 0x5FFFF), (0x6FFFE, 0x6FFFF),
+ (0x7FFFE, 0x7FFFF), (0x8FFFE, 0x8FFFF), (0x9FFFE, 0x9FFFF),
+ (0xAFFFE, 0xAFFFF), (0xBFFFE, 0xBFFFF), (0xCFFFE, 0xCFFFF),
+ (0xDFFFE, 0xDFFFF), (0xEFFFE, 0xEFFFF), (0xFFFFE, 0xFFFFF),
+ (0x10FFFE, 0x10FFFF)])
+
+ # Build up an array of range expressions.
+ illegal_ranges = [
+ "%s-%s" % (six.unichr(low), six.unichr(high))
+ for (low, high) in illegal_chars_u]
+
+ # Compile the regex
+ return re.compile(six.u('[%s]') % six.u('').join(illegal_ranges))
+
+ @staticmethod
+ def _quote_attribute(text):
+ """Returns the given text in a manner safe for usage in an XML attribute.
+
+ @param text the text that should appear within an XML attribute.
+ @return the attribute-escaped version of the input text.
+ """
+ return xml.sax.saxutils.quoteattr(text)
+
+ def _replace_invalid_xml(self, str_or_unicode):
+ """Replaces invalid XML characters with a '?'.
+
+ @param str_or_unicode a string to replace invalid XML
+ characters within. Can be unicode or not. If not unicode,
+ assumes it is a byte string in utf-8 encoding.
+
+ @returns a utf-8-encoded byte string with invalid
+ XML replaced with '?'.
+ """
+ # Get the content into unicode
+ if isinstance(str_or_unicode, str):
+ unicode_content = str_or_unicode.decode('utf-8')
+ else:
+ unicode_content = str_or_unicode
+ return self.invalid_xml_re.sub(
+ six.u('?'), unicode_content).encode('utf-8')
+
+ @classmethod
+ def arg_parser(cls):
+ """@return arg parser used to parse formatter-specific options."""
+ parser = super(XunitFormatter, cls).arg_parser()
+
+ # These are valid choices for results mapping.
+ results_mapping_choices = [
+ XunitFormatter.RM_IGNORE,
+ XunitFormatter.RM_SUCCESS,
+ XunitFormatter.RM_FAILURE,
+ XunitFormatter.RM_PASSTHRU]
+ parser.add_argument(
+ "--assert-on-unknown-events",
+ action="store_true",
+ help=('cause unknown test events to generate '
+ 'a python assert. Default is to ignore.'))
+ parser.add_argument(
+ "--ignore-skip-name",
+ "-n",
+ metavar='PATTERN',
+ action="append",
+ dest='ignore_skip_name_patterns',
+ help=('a python regex pattern, where '
+ 'any skipped test with a test method name where regex '
+ 'matches (via search) will be ignored for xUnit test '
+ 'result purposes. Can be specified multiple times.'))
+ parser.add_argument(
+ "--ignore-skip-reason",
+ "-r",
+ metavar='PATTERN',
+ action="append",
+ dest='ignore_skip_reason_patterns',
+ help=('a python regex pattern, where '
+ 'any skipped test with a skip reason where the regex '
+ 'matches (via search) will be ignored for xUnit test '
+ 'result purposes. Can be specified multiple times.'))
+ parser.add_argument(
+ "--xpass", action="store", choices=results_mapping_choices,
+ default=XunitFormatter.RM_FAILURE,
+ help=('specify mapping from unexpected success to jUnit/xUnit '
+ 'result type'))
+ parser.add_argument(
+ "--xfail", action="store", choices=results_mapping_choices,
+ default=XunitFormatter.RM_IGNORE,
+ help=('specify mapping from expected failure to jUnit/xUnit '
+ 'result type'))
+ return parser
+
+ @staticmethod
+ def _build_regex_list_from_patterns(patterns):
+ """Builds a list of compiled regexes from option value.
+
+ @param option string containing a comma-separated list of regex
+ patterns. Zero-length or None will produce an empty regex list.
+
+ @return list of compiled regular expressions, empty if no
+ patterns provided.
+ """
+ regex_list = []
+ if patterns is not None:
+ for pattern in patterns:
+ regex_list.append(re.compile(pattern))
+ return regex_list
+
+ def __init__(self, out_file, options):
+ """Initializes the XunitFormatter instance.
+ @param out_file file-like object where formatted output is written.
+ @param options_dict specifies a dictionary of options for the
+ formatter.
+ """
+ # Initialize the parent
+ super(XunitFormatter, self).__init__(out_file, options)
+ self.text_encoding = "UTF-8"
+ self.invalid_xml_re = XunitFormatter._build_illegal_xml_regex()
+ self.total_test_count = 0
+ self.ignore_skip_name_regexes = (
+ XunitFormatter._build_regex_list_from_patterns(
+ options.ignore_skip_name_patterns))
+ self.ignore_skip_reason_regexes = (
+ XunitFormatter._build_regex_list_from_patterns(
+ options.ignore_skip_reason_patterns))
+
+ self.elements = {
+ "successes": [],
+ "errors": [],
+ "failures": [],
+ "skips": [],
+ "unexpected_successes": [],
+ "expected_failures": [],
+ "all": []
+ }
+
+ self.status_handlers = {
+ EventBuilder.STATUS_SUCCESS: self._handle_success,
+ EventBuilder.STATUS_FAILURE: self._handle_failure,
+ EventBuilder.STATUS_ERROR: self._handle_error,
+ EventBuilder.STATUS_SKIP: self._handle_skip,
+ EventBuilder.STATUS_EXPECTED_FAILURE:
+ self._handle_expected_failure,
+ EventBuilder.STATUS_EXPECTED_TIMEOUT:
+ self._handle_expected_timeout,
+ EventBuilder.STATUS_UNEXPECTED_SUCCESS:
+ self._handle_unexpected_success,
+ EventBuilder.STATUS_EXCEPTIONAL_EXIT:
+ self._handle_exceptional_exit,
+ EventBuilder.STATUS_TIMEOUT:
+ self._handle_timeout
+ }
+
+ RESULT_TYPES = set(
+ [EventBuilder.TYPE_TEST_RESULT,
+ EventBuilder.TYPE_JOB_RESULT])
+
+ def handle_event(self, test_event):
+ super(XunitFormatter, self).handle_event(test_event)
+
+ event_type = test_event["event"]
+ if event_type is None:
+ return
+
+ if event_type == "terminate":
+ # Process all the final result events into their
+ # XML counterparts.
+ for result_event in self.result_events.values():
+ self._process_test_result(result_event)
+ self._finish_output()
+ else:
+ # This is an unknown event.
+ if self.options.assert_on_unknown_events:
+ raise Exception("unknown event type {} from {}\n".format(
+ event_type, test_event))
+
+ def _handle_success(self, test_event):
+ """Handles a test success.
+ @param test_event the test event to handle.
+ """
+ result = self._common_add_testcase_entry(test_event)
+ with self.lock:
+ self.elements["successes"].append(result)
+
+ def _handle_failure(self, test_event):
+ """Handles a test failure.
+ @param test_event the test event to handle.
+ """
+ message = self._replace_invalid_xml(test_event["issue_message"])
+ backtrace = self._replace_invalid_xml(
+ "".join(test_event.get("issue_backtrace", [])))
+
+ result = self._common_add_testcase_entry(
+ test_event,
+ inner_content=(
+ '<failure type={} message={}><![CDATA[{}]]></failure>'.format(
+ XunitFormatter._quote_attribute(test_event["issue_class"]),
+ XunitFormatter._quote_attribute(message),
+ backtrace)
+ ))
+ with self.lock:
+ self.elements["failures"].append(result)
+
+ def _handle_error(self, test_event):
+ """Handles a test error.
+ @param test_event the test event to handle.
+ """
+ message = self._replace_invalid_xml(test_event["issue_message"])
+ backtrace = self._replace_invalid_xml(
+ "".join(test_event.get("issue_backtrace", [])))
+
+ result = self._common_add_testcase_entry(
+ test_event,
+ inner_content=(
+ '<error type={} message={}><![CDATA[{}]]></error>'.format(
+ XunitFormatter._quote_attribute(test_event["issue_class"]),
+ XunitFormatter._quote_attribute(message),
+ backtrace)
+ ))
+ with self.lock:
+ self.elements["errors"].append(result)
+
+ def _handle_exceptional_exit(self, test_event):
+ """Handles an exceptional exit.
+ @param test_event the test method or job result event to handle.
+ """
+ if "test_name" in test_event:
+ name = test_event["test_name"]
+ else:
+ name = test_event.get("test_filename", "<unknown test/filename>")
+
+ message_text = "ERROR: {} ({}): {}".format(
+ test_event.get("exception_code", 0),
+ test_event.get("exception_description", ""),
+ name)
+ message = self._replace_invalid_xml(message_text)
+
+ result = self._common_add_testcase_entry(
+ test_event,
+ inner_content=(
+ '<error type={} message={}></error>'.format(
+ "exceptional_exit",
+ XunitFormatter._quote_attribute(message))
+ ))
+ with self.lock:
+ self.elements["errors"].append(result)
+
+ def _handle_timeout(self, test_event):
+ """Handles a test method or job timeout.
+ @param test_event the test method or job result event to handle.
+ """
+ if "test_name" in test_event:
+ name = test_event["test_name"]
+ else:
+ name = test_event.get("test_filename", "<unknown test/filename>")
+
+ message_text = "TIMEOUT: {}".format(name)
+ message = self._replace_invalid_xml(message_text)
+
+ result = self._common_add_testcase_entry(
+ test_event,
+ inner_content=(
+ '<error type={} message={}></error>'.format(
+ "timeout",
+ XunitFormatter._quote_attribute(message))
+ ))
+ with self.lock:
+ self.elements["errors"].append(result)
+
+ @staticmethod
+ def _ignore_based_on_regex_list(test_event, test_key, regex_list):
+ """Returns whether to ignore a test event based on patterns.
+
+ @param test_event the test event dictionary to check.
+ @param test_key the key within the dictionary to check.
+ @param regex_list a list of zero or more regexes. May contain
+ zero or more compiled regexes.
+
+ @return True if any o the regex list match based on the
+ re.search() method; false otherwise.
+ """
+ for regex in regex_list:
+ match = regex.search(test_event.get(test_key, ''))
+ if match:
+ return True
+ return False
+
+ def _handle_skip(self, test_event):
+ """Handles a skipped test.
+ @param test_event the test event to handle.
+ """
+
+ # Are we ignoring this test based on test name?
+ if XunitFormatter._ignore_based_on_regex_list(
+ test_event, 'test_name', self.ignore_skip_name_regexes):
+ return
+
+ # Are we ignoring this test based on skip reason?
+ if XunitFormatter._ignore_based_on_regex_list(
+ test_event, 'skip_reason', self.ignore_skip_reason_regexes):
+ return
+
+ # We're not ignoring this test. Process the skip.
+ reason = self._replace_invalid_xml(test_event.get("skip_reason", ""))
+ result = self._common_add_testcase_entry(
+ test_event,
+ inner_content='<skipped message={} />'.format(
+ XunitFormatter._quote_attribute(reason)))
+ with self.lock:
+ self.elements["skips"].append(result)
+
+ def _handle_expected_failure(self, test_event):
+ """Handles a test that failed as expected.
+ @param test_event the test event to handle.
+ """
+ if self.options.xfail == XunitFormatter.RM_PASSTHRU:
+ # This is not a natively-supported junit/xunit
+ # testcase mode, so it might fail a validating
+ # test results viewer.
+ if "bugnumber" in test_event:
+ bug_id_attribute = 'bug-id={} '.format(
+ XunitFormatter._quote_attribute(test_event["bugnumber"]))
+ else:
+ bug_id_attribute = ''
+
+ result = self._common_add_testcase_entry(
+ test_event,
+ inner_content=(
+ '<expected-failure {}type={} message={} />'.format(
+ bug_id_attribute,
+ XunitFormatter._quote_attribute(
+ test_event["issue_class"]),
+ XunitFormatter._quote_attribute(
+ test_event["issue_message"]))
+ ))
+ with self.lock:
+ self.elements["expected_failures"].append(result)
+ elif self.options.xfail == XunitFormatter.RM_SUCCESS:
+ result = self._common_add_testcase_entry(test_event)
+ with self.lock:
+ self.elements["successes"].append(result)
+ elif self.options.xfail == XunitFormatter.RM_FAILURE:
+ result = self._common_add_testcase_entry(
+ test_event,
+ inner_content='<failure type={} message={} />'.format(
+ XunitFormatter._quote_attribute(test_event["issue_class"]),
+ XunitFormatter._quote_attribute(
+ test_event["issue_message"])))
+ with self.lock:
+ self.elements["failures"].append(result)
+ elif self.options.xfail == XunitFormatter.RM_IGNORE:
+ pass
+ else:
+ raise Exception(
+ "unknown xfail option: {}".format(self.options.xfail))
+
+ def _handle_expected_timeout(self, test_event):
+ """Handles expected_timeout.
+ @param test_event the test event to handle.
+ """
+ # We don't do anything with expected timeouts, not even report.
+ pass
+
+ def _handle_unexpected_success(self, test_event):
+ """Handles a test that passed but was expected to fail.
+ @param test_event the test event to handle.
+ """
+ if self.options.xpass == XunitFormatter.RM_PASSTHRU:
+ # This is not a natively-supported junit/xunit
+ # testcase mode, so it might fail a validating
+ # test results viewer.
+ result = self._common_add_testcase_entry(
+ test_event,
+ inner_content=("<unexpected-success />"))
+ with self.lock:
+ self.elements["unexpected_successes"].append(result)
+ elif self.options.xpass == XunitFormatter.RM_SUCCESS:
+ # Treat the xpass as a success.
+ result = self._common_add_testcase_entry(test_event)
+ with self.lock:
+ self.elements["successes"].append(result)
+ elif self.options.xpass == XunitFormatter.RM_FAILURE:
+ # Treat the xpass as a failure.
+ if "bugnumber" in test_event:
+ message = "unexpected success (bug_id:{})".format(
+ test_event["bugnumber"])
+ else:
+ message = "unexpected success (bug_id:none)"
+ result = self._common_add_testcase_entry(
+ test_event,
+ inner_content='<failure type={} message={} />'.format(
+ XunitFormatter._quote_attribute("unexpected_success"),
+ XunitFormatter._quote_attribute(message)))
+ with self.lock:
+ self.elements["failures"].append(result)
+ elif self.options.xpass == XunitFormatter.RM_IGNORE:
+ # Ignore the xpass result as far as xUnit reporting goes.
+ pass
+ else:
+ raise Exception("unknown xpass option: {}".format(
+ self.options.xpass))
+
+ def _process_test_result(self, test_event):
+ """Processes the test_event known to be a test result.
+
+ This categorizes the event appropriately and stores the data needed
+ to generate the final xUnit report. This method skips events that
+ cannot be represented in xUnit output.
+ """
+ if "status" not in test_event:
+ raise Exception("test event dictionary missing 'status' key")
+
+ status = test_event["status"]
+ if status not in self.status_handlers:
+ raise Exception("test event status '{}' unsupported".format(
+ status))
+
+ # Call the status handler for the test result.
+ self.status_handlers[status](test_event)
+
+ def _common_add_testcase_entry(self, test_event, inner_content=None):
+ """Registers a testcase result, and returns the text created.
+
+ The caller is expected to manage failure/skip/success counts
+ in some kind of appropriate way. This call simply constructs
+ the XML and appends the returned result to the self.all_results
+ list.
+
+ @param test_event the test event dictionary.
+
+ @param inner_content if specified, gets included in the <testcase>
+ inner section, at the point before stdout and stderr would be
+ included. This is where a <failure/>, <skipped/>, <error/>, etc.
+ could go.
+
+ @return the text of the xml testcase element.
+ """
+
+ # Get elapsed time.
+ test_class = test_event["test_class"]
+ test_name = test_event["test_name"]
+ event_time = test_event["event_time"]
+ time_taken = self.elapsed_time_for_test(
+ test_class, test_name, event_time)
+
+ # Plumb in stdout/stderr once we shift over to only test results.
+ test_stdout = ''
+ test_stderr = ''
+
+ # Formulate the output xml.
+ if not inner_content:
+ inner_content = ""
+ result = (
+ '<testcase classname="{}" name="{}" time="{:.3f}">'
+ '{}{}{}</testcase>'.format(
+ test_class,
+ test_name,
+ time_taken,
+ inner_content,
+ test_stdout,
+ test_stderr))
+
+ # Save the result, update total test count.
+ with self.lock:
+ self.total_test_count += 1
+ self.elements["all"].append(result)
+
+ return result
+
+ def _finish_output_no_lock(self):
+ """Flushes out the report of test executions to form valid xml output.
+
+ xUnit output is in XML. The reporting system cannot complete the
+ formatting of the output without knowing when there is no more input.
+ This call addresses notifcation of the completed test run and thus is
+ when we can finish off the report output.
+ """
+
+ # Figure out the counts line for the testsuite. If we have
+ # been counting either unexpected successes or expected
+ # failures, we'll output those in the counts, at the risk of
+ # being invalidated by a validating test results viewer.
+ # These aren't counted by default so they won't show up unless
+ # the user specified a formatter option to include them.
+ xfail_count = len(self.elements["expected_failures"])
+ xpass_count = len(self.elements["unexpected_successes"])
+ if xfail_count > 0 or xpass_count > 0:
+ extra_testsuite_attributes = (
+ ' expected-failures="{}"'
+ ' unexpected-successes="{}"'.format(xfail_count, xpass_count))
+ else:
+ extra_testsuite_attributes = ""
+
+ # Output the header.
+ self.out_file.write(
+ '<?xml version="1.0" encoding="{}"?>\n'
+ '<testsuites>'
+ '<testsuite name="{}" tests="{}" errors="{}" failures="{}" '
+ 'skip="{}"{}>\n'.format(
+ self.text_encoding,
+ "LLDB test suite",
+ self.total_test_count,
+ len(self.elements["errors"]),
+ len(self.elements["failures"]),
+ len(self.elements["skips"]),
+ extra_testsuite_attributes))
+
+ # Output each of the test result entries.
+ for result in self.elements["all"]:
+ self.out_file.write(result + '\n')
+
+ # Close off the test suite.
+ self.out_file.write('</testsuite></testsuites>\n')
+
+ def _finish_output(self):
+ """Finish writing output as all incoming events have arrived."""
+ with self.lock:
+ self._finish_output_no_lock()