1 //===-- DWARFExpressionTest.cpp -------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Expression/DWARFExpression.h"
10 #include "Plugins/Platform/Linux/PlatformLinux.h"
11 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
12 #include "TestingSupport/Symbol/YAMLModuleTester.h"
13 #include "lldb/Core/Value.h"
14 #include "lldb/Core/Debugger.h"
15 #include "lldb/Core/dwarf.h"
16 #include "lldb/Host/HostInfo.h"
17 #include "lldb/Symbol/ObjectFile.h"
18 #include "lldb/Utility/Reproducer.h"
19 #include "lldb/Utility/StreamString.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Testing/Support/Error.h"
22 #include "gtest/gtest.h"
23 
24 using namespace lldb_private;
25 
26 static llvm::Expected<Scalar> Evaluate(llvm::ArrayRef<uint8_t> expr,
27                                        lldb::ModuleSP module_sp = {},
28                                        DWARFUnit *unit = nullptr,
29                                        ExecutionContext *exe_ctx = nullptr) {
30   DataExtractor extractor(expr.data(), expr.size(), lldb::eByteOrderLittle,
31                           /*addr_size*/ 4);
32   Value result;
33   Status status;
34   if (!DWARFExpression::Evaluate(exe_ctx, /*reg_ctx*/ nullptr, module_sp,
35                                  extractor, unit, lldb::eRegisterKindLLDB,
36                                  /*initial_value_ptr*/ nullptr,
37                                  /*object_address_ptr*/ nullptr, result,
38                                  &status))
39     return status.ToError();
40 
41   switch (result.GetValueType()) {
42   case Value::ValueType::Scalar:
43     return result.GetScalar();
44   case Value::ValueType::HostAddress: {
45     // Convert small buffers to scalars to simplify the tests.
46     DataBufferHeap &buf = result.GetBuffer();
47     if (buf.GetByteSize() <= 8) {
48       uint64_t val = 0;
49       memcpy(&val, buf.GetBytes(), buf.GetByteSize());
50       return Scalar(llvm::APInt(buf.GetByteSize()*8, val, false));
51     }
52   }
53     LLVM_FALLTHROUGH;
54   default:
55     return status.ToError();
56   }
57 }
58 
59 class DWARFExpressionTester : public YAMLModuleTester {
60 public:
61   using YAMLModuleTester::YAMLModuleTester;
62   llvm::Expected<Scalar> Eval(llvm::ArrayRef<uint8_t> expr) {
63     return ::Evaluate(expr, m_module_sp, m_dwarf_unit);
64   }
65 };
66 
67 /// Unfortunately Scalar's operator==() is really picky.
68 static Scalar GetScalar(unsigned bits, uint64_t value, bool sign) {
69   Scalar scalar(value);
70   scalar.TruncOrExtendTo(bits, sign);
71   return scalar;
72 }
73 
74 /// This is needed for the tests that use a mock process.
75 class DWARFExpressionMockProcessTest : public ::testing::Test {
76 public:
77   void SetUp() override {
78     llvm::cantFail(repro::Reproducer::Initialize(repro::ReproducerMode::Off, {}));
79     FileSystem::Initialize();
80     HostInfo::Initialize();
81     platform_linux::PlatformLinux::Initialize();
82   }
83   void TearDown() override {
84     platform_linux::PlatformLinux::Terminate();
85     HostInfo::Terminate();
86     FileSystem::Terminate();
87     repro::Reproducer::Terminate();
88   }
89 };
90 
91 TEST(DWARFExpression, DW_OP_pick) {
92   EXPECT_THAT_EXPECTED(Evaluate({DW_OP_lit1, DW_OP_lit0, DW_OP_pick, 0}),
93                        llvm::HasValue(0));
94   EXPECT_THAT_EXPECTED(Evaluate({DW_OP_lit1, DW_OP_lit0, DW_OP_pick, 1}),
95                        llvm::HasValue(1));
96   EXPECT_THAT_EXPECTED(Evaluate({DW_OP_lit1, DW_OP_lit0, DW_OP_pick, 2}),
97                        llvm::Failed());
98 }
99 
100 TEST(DWARFExpression, DW_OP_const) {
101   // Extend to address size.
102   EXPECT_THAT_EXPECTED(Evaluate({DW_OP_const1u, 0x88}), llvm::HasValue(0x88));
103   EXPECT_THAT_EXPECTED(Evaluate({DW_OP_const1s, 0x88}),
104                        llvm::HasValue(0xffffff88));
105   EXPECT_THAT_EXPECTED(Evaluate({DW_OP_const2u, 0x47, 0x88}),
106                        llvm::HasValue(0x8847));
107   EXPECT_THAT_EXPECTED(Evaluate({DW_OP_const2s, 0x47, 0x88}),
108                        llvm::HasValue(0xffff8847));
109   EXPECT_THAT_EXPECTED(Evaluate({DW_OP_const4u, 0x44, 0x42, 0x47, 0x88}),
110                        llvm::HasValue(0x88474244));
111   EXPECT_THAT_EXPECTED(Evaluate({DW_OP_const4s, 0x44, 0x42, 0x47, 0x88}),
112                        llvm::HasValue(0x88474244));
113 
114   // Truncate to address size.
115   EXPECT_THAT_EXPECTED(
116       Evaluate({DW_OP_const8u, 0x00, 0x11, 0x22, 0x33, 0x44, 0x42, 0x47, 0x88}),
117       llvm::HasValue(0x33221100));
118   EXPECT_THAT_EXPECTED(
119       Evaluate({DW_OP_const8s, 0x00, 0x11, 0x22, 0x33, 0x44, 0x42, 0x47, 0x88}),
120       llvm::HasValue(0x33221100));
121 
122   // Don't truncate to address size for compatibility with clang (pr48087).
123   EXPECT_THAT_EXPECTED(
124       Evaluate({DW_OP_constu, 0x81, 0x82, 0x84, 0x88, 0x90, 0xa0, 0x40}),
125       llvm::HasValue(0x01010101010101));
126   EXPECT_THAT_EXPECTED(
127       Evaluate({DW_OP_consts, 0x81, 0x82, 0x84, 0x88, 0x90, 0xa0, 0x40}),
128       llvm::HasValue(0xffff010101010101));
129 }
130 
131 TEST(DWARFExpression, DW_OP_convert) {
132   /// Auxiliary debug info.
133   const char *yamldata = R"(
134 --- !ELF
135 FileHeader:
136   Class:   ELFCLASS64
137   Data:    ELFDATA2LSB
138   Type:    ET_EXEC
139   Machine: EM_386
140 DWARF:
141   debug_abbrev:
142     - Table:
143         - Code:            0x00000001
144           Tag:             DW_TAG_compile_unit
145           Children:        DW_CHILDREN_yes
146           Attributes:
147             - Attribute:       DW_AT_language
148               Form:            DW_FORM_data2
149         - Code:            0x00000002
150           Tag:             DW_TAG_base_type
151           Children:        DW_CHILDREN_no
152           Attributes:
153             - Attribute:       DW_AT_encoding
154               Form:            DW_FORM_data1
155             - Attribute:       DW_AT_byte_size
156               Form:            DW_FORM_data1
157   debug_info:
158     - Version:         4
159       AddrSize:        8
160       Entries:
161         - AbbrCode:        0x00000001
162           Values:
163             - Value:           0x000000000000000C
164         # 0x0000000e:
165         - AbbrCode:        0x00000002
166           Values:
167             - Value:           0x0000000000000007 # DW_ATE_unsigned
168             - Value:           0x0000000000000004
169         # 0x00000011:
170         - AbbrCode:        0x00000002
171           Values:
172             - Value:           0x0000000000000007 # DW_ATE_unsigned
173             - Value:           0x0000000000000008
174         # 0x00000014:
175         - AbbrCode:        0x00000002
176           Values:
177             - Value:           0x0000000000000005 # DW_ATE_signed
178             - Value:           0x0000000000000008
179         # 0x00000017:
180         - AbbrCode:        0x00000002
181           Values:
182             - Value:           0x0000000000000008 # DW_ATE_unsigned_char
183             - Value:           0x0000000000000001
184         # 0x0000001a:
185         - AbbrCode:        0x00000002
186           Values:
187             - Value:           0x0000000000000006 # DW_ATE_signed_char
188             - Value:           0x0000000000000001
189         # 0x0000001d:
190         - AbbrCode:        0x00000002
191           Values:
192             - Value:           0x000000000000000b # DW_ATE_numeric_string
193             - Value:           0x0000000000000001
194         - AbbrCode:        0x00000000
195 )";
196   uint8_t offs_uint32_t = 0x0000000e;
197   uint8_t offs_uint64_t = 0x00000011;
198   uint8_t offs_sint64_t = 0x00000014;
199   uint8_t offs_uchar = 0x00000017;
200   uint8_t offs_schar = 0x0000001a;
201 
202   DWARFExpressionTester t(yamldata);
203   ASSERT_TRUE((bool)t.GetDwarfUnit());
204 
205   // Constant is given as little-endian.
206   bool is_signed = true;
207   bool not_signed = false;
208 
209   //
210   // Positive tests.
211   //
212 
213   // Leave as is.
214   EXPECT_THAT_EXPECTED(t.Eval({DW_OP_const4u, 0x11, 0x22, 0x33, 0x44, //
215                                DW_OP_convert, offs_uint32_t}),
216                        llvm::HasValue(GetScalar(64, 0x44332211, not_signed)));
217 
218   // Zero-extend to 64 bits.
219   EXPECT_THAT_EXPECTED(t.Eval({DW_OP_const4u, 0x11, 0x22, 0x33, 0x44, //
220                                DW_OP_convert, offs_uint64_t}),
221                        llvm::HasValue(GetScalar(64, 0x44332211, not_signed)));
222 
223   // Sign-extend to 64 bits.
224   EXPECT_THAT_EXPECTED(
225       t.Eval({DW_OP_const4s, 0xcc, 0xdd, 0xee, 0xff, //
226               DW_OP_convert, offs_sint64_t}),
227       llvm::HasValue(GetScalar(64, 0xffffffffffeeddcc, is_signed)));
228 
229   // Sign-extend, then truncate.
230   EXPECT_THAT_EXPECTED(t.Eval({DW_OP_const4s, 0xcc, 0xdd, 0xee, 0xff, //
231                                DW_OP_convert, offs_sint64_t,          //
232                                DW_OP_convert, offs_uint32_t}),
233                        llvm::HasValue(GetScalar(32, 0xffeeddcc, not_signed)));
234 
235   // Truncate to default unspecified (pointer-sized) type.
236   EXPECT_THAT_EXPECTED(t.Eval({DW_OP_const4s, 0xcc, 0xdd, 0xee, 0xff, //
237                                DW_OP_convert, offs_sint64_t,          //
238                                DW_OP_convert, 0x00}),
239                        llvm::HasValue(GetScalar(32, 0xffeeddcc, not_signed)));
240 
241   // Truncate to 8 bits.
242   EXPECT_THAT_EXPECTED(
243       t.Eval({DW_OP_const4s, 'A', 'B', 'C', 'D', DW_OP_convert, offs_uchar}),
244       llvm::HasValue(GetScalar(8, 'A', not_signed)));
245 
246   // Also truncate to 8 bits.
247   EXPECT_THAT_EXPECTED(
248       t.Eval({DW_OP_const4s, 'A', 'B', 'C', 'D', DW_OP_convert, offs_schar}),
249       llvm::HasValue(GetScalar(8, 'A', is_signed)));
250 
251   //
252   // Errors.
253   //
254 
255   // No Module.
256   EXPECT_THAT_ERROR(Evaluate({DW_OP_const1s, 'X', DW_OP_convert, 0x00}, nullptr,
257                              t.GetDwarfUnit())
258                         .takeError(),
259                     llvm::Failed());
260 
261   // No DIE.
262   EXPECT_THAT_ERROR(
263       t.Eval({DW_OP_const1s, 'X', DW_OP_convert, 0x01}).takeError(),
264       llvm::Failed());
265 
266   // Unsupported.
267   EXPECT_THAT_ERROR(
268       t.Eval({DW_OP_const1s, 'X', DW_OP_convert, 0x1d}).takeError(),
269       llvm::Failed());
270 }
271 
272 TEST(DWARFExpression, DW_OP_stack_value) {
273   EXPECT_THAT_EXPECTED(Evaluate({DW_OP_stack_value}), llvm::Failed());
274 }
275 
276 TEST(DWARFExpression, DW_OP_piece) {
277   EXPECT_THAT_EXPECTED(Evaluate({DW_OP_const2u, 0x11, 0x22, DW_OP_piece, 2,
278                                  DW_OP_const2u, 0x33, 0x44, DW_OP_piece, 2}),
279                        llvm::HasValue(GetScalar(32, 0x44332211, true)));
280   EXPECT_THAT_EXPECTED(
281       Evaluate({DW_OP_piece, 1, DW_OP_const1u, 0xff, DW_OP_piece, 1}),
282       // Note that the "00" should really be "undef", but we can't
283       // represent that yet.
284       llvm::HasValue(GetScalar(16, 0xff00, true)));
285 }
286 
287 TEST(DWARFExpression, DW_OP_implicit_value) {
288   unsigned char bytes = 4;
289 
290   EXPECT_THAT_EXPECTED(
291       Evaluate({DW_OP_implicit_value, bytes, 0x11, 0x22, 0x33, 0x44}),
292       llvm::HasValue(GetScalar(8 * bytes, 0x44332211, true)));
293 }
294 
295 TEST(DWARFExpression, DW_OP_unknown) {
296   EXPECT_THAT_EXPECTED(
297       Evaluate({0xff}),
298       llvm::FailedWithMessage(
299           "Unhandled opcode DW_OP_unknown_ff in DWARFExpression"));
300 }
301 
302 TEST_F(DWARFExpressionMockProcessTest, DW_OP_deref) {
303   EXPECT_THAT_EXPECTED(Evaluate({DW_OP_lit0, DW_OP_deref}), llvm::Failed());
304 
305   struct MockProcess : Process {
306     using Process::Process;
307     ConstString GetPluginName() override { return ConstString("mock process"); }
308     uint32_t GetPluginVersion() override { return 0; }
309     bool CanDebug(lldb::TargetSP target,
310                   bool plugin_specified_by_name) override {
311       return false;
312     };
313     Status DoDestroy() override { return {}; }
314     void RefreshStateAfterStop() override {}
315     bool DoUpdateThreadList(ThreadList &old_thread_list,
316                             ThreadList &new_thread_list) override {
317       return false;
318     };
319     size_t DoReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
320                         Status &error) override {
321       for (size_t i = 0; i < size; ++i)
322         ((char *)buf)[i] = (vm_addr + i) & 0xff;
323       error.Clear();
324       return size;
325     }
326   };
327 
328   // Set up a mock process.
329   ArchSpec arch("i386-pc-linux");
330   Platform::SetHostPlatform(
331       platform_linux::PlatformLinux::CreateInstance(true, &arch));
332   lldb::DebuggerSP debugger_sp = Debugger::CreateInstance();
333   ASSERT_TRUE(debugger_sp);
334   lldb::TargetSP target_sp;
335   lldb::PlatformSP platform_sp;
336   debugger_sp->GetTargetList().CreateTarget(
337       *debugger_sp, "", arch, eLoadDependentsNo, platform_sp, target_sp);
338   ASSERT_TRUE(target_sp);
339   ASSERT_TRUE(target_sp->GetArchitecture().IsValid());
340   ASSERT_TRUE(platform_sp);
341   lldb::ListenerSP listener_sp(Listener::MakeListener("dummy"));
342   lldb::ProcessSP process_sp =
343       std::make_shared<MockProcess>(target_sp, listener_sp);
344   ASSERT_TRUE(process_sp);
345 
346   ExecutionContext exe_ctx(process_sp);
347   EXPECT_THAT_EXPECTED(Evaluate({DW_OP_lit4, DW_OP_deref}, {}, {}, &exe_ctx),
348                        llvm::HasValue(GetScalar(32, 0x07060504, false)));
349 }
350