File: TestFirmwareCorefiles.py

package info (click to toggle)
llvm-toolchain-19 1%3A19.1.7-3~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,998,492 kB
  • sloc: cpp: 6,951,680; ansic: 1,486,157; asm: 913,598; python: 232,024; f90: 80,126; objc: 75,281; lisp: 37,276; pascal: 16,990; sh: 10,009; ml: 5,058; perl: 4,724; awk: 3,523; makefile: 3,167; javascript: 2,504; xml: 892; fortran: 664; cs: 573
file content (382 lines) | stat: -rw-r--r-- 14,843 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
"""Test that corefiles with LC_NOTE "kern ver str" and "main bin spec" load commands works."""


import os
import re
import subprocess

import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil


class TestFirmwareCorefiles(TestBase):
    @skipIf(
        debug_info=no_match(["dsym"]),
        bugnumber="This test is looking explicitly for a dSYM",
    )
    @skipIf(archs=no_match(["x86_64", "arm64", "arm64e", "aarch64"]))
    @skipIfRemote
    @skipUnlessDarwin
    def test_lc_note_version_string(self):
        self.build()
        aout_exe_basename = "a.out"
        aout_exe = self.getBuildArtifact(aout_exe_basename)
        verstr_corefile = self.getBuildArtifact("verstr.core")
        verstr_corefile_invalid_ident = self.getBuildArtifact(
            "verstr-invalid-ident.core"
        )
        verstr_corefile_addr = self.getBuildArtifact("verstr-addr.core")
        create_corefile = self.getBuildArtifact("create-empty-corefile")
        slide = 0x70000000000
        call(
            create_corefile
            + " version-string "
            + verstr_corefile
            + " "
            + aout_exe
            + " 0xffffffffffffffff 0xffffffffffffffff",
            shell=True,
        )
        call(
            create_corefile
            + " version-string "
            + verstr_corefile_invalid_ident
            + ' "" '
            + "0xffffffffffffffff 0xffffffffffffffff",
            shell=True,
        )
        call(
            create_corefile
            + " version-string "
            + verstr_corefile_addr
            + " "
            + aout_exe
            + (" 0x%x" % slide)
            + " 0xffffffffffffffff",
            shell=True,
        )

        if self.TraceOn():
            self.runCmd("log enable lldb dyld host")
            self.addTearDownHook(lambda: self.runCmd("log disable lldb dyld host"))

        # Register the a.out binary with this UUID in lldb's global module
        # cache, then throw the Target away.
        target = self.dbg.CreateTarget(aout_exe)
        self.dbg.DeleteTarget(target)

        # First, try the "kern ver str" corefile
        target = self.dbg.CreateTarget("")
        err = lldb.SBError()
        if self.TraceOn():
            self.runCmd("script print('loading corefile %s')" % verstr_corefile)
        process = target.LoadCore(verstr_corefile)
        self.assertTrue(process.IsValid())
        if self.TraceOn():
            self.runCmd("image list")
            self.runCmd("target mod dump sections")
        self.assertEqual(target.GetNumModules(), 1)
        fspec = target.GetModuleAtIndex(0).GetFileSpec()
        self.assertEqual(fspec.GetFilename(), aout_exe_basename)
        self.dbg.DeleteTarget(target)

        # Second, try the "kern ver str" corefile which has an invalid ident,
        # make sure we don't crash.
        target = self.dbg.CreateTarget("")
        err = lldb.SBError()
        if self.TraceOn():
            self.runCmd(
                "script print('loading corefile %s')" % verstr_corefile_invalid_ident
            )
        process = target.LoadCore(verstr_corefile_invalid_ident)
        self.assertTrue(process.IsValid())

        # Third, try the "kern ver str" corefile where it loads at an address
        target = self.dbg.CreateTarget("")
        err = lldb.SBError()
        if self.TraceOn():
            self.runCmd("script print('loading corefile %s')" % verstr_corefile_addr)
        process = target.LoadCore(verstr_corefile_addr)
        self.assertTrue(process.IsValid())
        if self.TraceOn():
            self.runCmd("image list")
            self.runCmd("target mod dump sections")
        self.assertEqual(target.GetNumModules(), 1)
        fspec = target.GetModuleAtIndex(0).GetFileSpec()
        self.assertEqual(fspec.GetFilename(), aout_exe_basename)
        main_sym = target.GetModuleAtIndex(0).FindSymbol("main", lldb.eSymbolTypeAny)
        main_addr = main_sym.GetStartAddress()
        self.assertGreater(main_addr.GetLoadAddress(target), slide)
        self.assertNotEqual(main_addr.GetLoadAddress(target), lldb.LLDB_INVALID_ADDRESS)
        self.dbg.DeleteTarget(target)

    @skipIf(
        debug_info=no_match(["dsym"]),
        bugnumber="This test is looking explicitly for a dSYM",
    )
    @skipIf(archs=no_match(["x86_64", "arm64", "arm64e", "aarch64"]))
    @skipIfRemote
    @skipUnlessDarwin
    def test_lc_note_main_bin_spec(self):
        self.build()
        aout_exe_basename = "a.out"
        aout_exe = self.getBuildArtifact(aout_exe_basename)
        create_corefile = self.getBuildArtifact("create-empty-corefile")
        binspec_corefile = self.getBuildArtifact("binspec.core")
        binspec_corefile_addr = self.getBuildArtifact("binspec-addr.core")
        binspec_corefile_slideonly = self.getBuildArtifact(
            "binspec-addr-slideonly.core"
        )

        slide = 0x70000000000

        ### Create our corefile
        # 0xffffffffffffffff means load address unknown
        call(
            create_corefile
            + " main-bin-spec "
            + binspec_corefile
            + " "
            + aout_exe
            + " 0xffffffffffffffff 0xffffffffffffffff",
            shell=True,
        )
        call(
            create_corefile
            + " main-bin-spec "
            + binspec_corefile_addr
            + " "
            + aout_exe
            + (" 0x%x" % slide)
            + " 0xffffffffffffffff",
            shell=True,
        )
        call(
            create_corefile
            + " main-bin-spec "
            + binspec_corefile_slideonly
            + " "
            + aout_exe
            + " 0xffffffffffffffff"
            + (" 0x%x" % slide),
            shell=True,
        )

        if self.TraceOn():
            self.runCmd("log enable lldb dyld host")
            self.addTearDownHook(lambda: self.runCmd("log disable lldb dyld host"))

        # Register the a.out binary with this UUID in lldb's global module
        # cache, then throw the Target away.
        target = self.dbg.CreateTarget(aout_exe)
        self.dbg.DeleteTarget(target)

        # First, try the "main bin spec" corefile
        target = self.dbg.CreateTarget("")
        if self.TraceOn():
            self.runCmd("script print('loading corefile %s')" % binspec_corefile)
        process = target.LoadCore(binspec_corefile)
        self.assertTrue(process.IsValid())
        if self.TraceOn():
            self.runCmd("image list")
            self.runCmd("target mod dump sections")
        self.assertEqual(target.GetNumModules(), 1)
        fspec = target.GetModuleAtIndex(0).GetFileSpec()
        self.assertEqual(fspec.GetFilename(), aout_exe_basename)
        self.dbg.DeleteTarget(target)

        # Second, try the "main bin spec" corefile where it loads at an address
        target = self.dbg.CreateTarget("")
        if self.TraceOn():
            self.runCmd("script print('loading corefile %s')" % binspec_corefile_addr)
        process = target.LoadCore(binspec_corefile_addr)
        self.assertTrue(process.IsValid())
        if self.TraceOn():
            self.runCmd("image list")
            self.runCmd("target mod dump sections")
        self.assertEqual(target.GetNumModules(), 1)
        fspec = target.GetModuleAtIndex(0).GetFileSpec()
        self.assertEqual(fspec.GetFilename(), aout_exe_basename)
        main_sym = target.GetModuleAtIndex(0).FindSymbol("main", lldb.eSymbolTypeAny)
        main_addr = main_sym.GetStartAddress()
        self.assertGreater(main_addr.GetLoadAddress(target), slide)
        self.assertNotEqual(main_addr.GetLoadAddress(target), lldb.LLDB_INVALID_ADDRESS)
        self.dbg.DeleteTarget(target)

        # Third, try the "main bin spec" corefile where it loads at a slide
        target = self.dbg.CreateTarget("")
        if self.TraceOn():
            self.runCmd(
                "script print('loading corefile %s')" % binspec_corefile_slideonly
            )
        process = target.LoadCore(binspec_corefile_slideonly)
        self.assertTrue(process.IsValid())
        if self.TraceOn():
            self.runCmd("image list")
            self.runCmd("target mod dump sections")
        self.assertEqual(target.GetNumModules(), 1)
        fspec = target.GetModuleAtIndex(0).GetFileSpec()
        self.assertEqual(fspec.GetFilename(), aout_exe_basename)
        main_sym = target.GetModuleAtIndex(0).FindSymbol("main", lldb.eSymbolTypeAny)
        main_addr = main_sym.GetStartAddress()
        self.assertGreater(main_addr.GetLoadAddress(target), slide)
        self.assertNotEqual(main_addr.GetLoadAddress(target), lldb.LLDB_INVALID_ADDRESS)
        self.dbg.DeleteTarget(target)

    @skipIf(
        debug_info=no_match(["dsym"]),
        bugnumber="This test is looking explicitly for a dSYM",
    )
    @skipIf(archs=no_match(["x86_64", "arm64", "arm64e", "aarch64"]))
    @skipIfRemote
    @skipUnlessDarwin
    def test_lc_note_main_bin_spec_os_plugin(self):
        self.build()
        aout_exe = self.getBuildArtifact("a.out")
        aout_exe_basename = "a.out"
        create_corefile = self.getBuildArtifact("create-empty-corefile")
        binspec_corefile_addr = self.getBuildArtifact("binspec-addr.core")

        slide = 0x70000000000

        ### Create our corefile
        # 0xffffffffffffffff means load address unknown
        call(
            create_corefile
            + " main-bin-spec "
            + binspec_corefile_addr
            + " "
            + aout_exe
            + (" 0x%x" % slide)
            + " 0xffffffffffffffff",
            shell=True,
        )

        ## We can hook in our dsym-for-uuid shell script to lldb with this env
        ## var instead of requiring a defaults write.
        dsym_for_uuid = self.getBuildArtifact("dsym-for-uuid.sh")
        os.environ["LLDB_APPLE_DSYMFORUUID_EXECUTABLE"] = dsym_for_uuid
        if self.TraceOn():
            print("Setting env var LLDB_APPLE_DSYMFORUUID_EXECUTABLE=" + dsym_for_uuid)
        self.addTearDownHook(
            lambda: os.environ.pop("LLDB_APPLE_DSYMFORUUID_EXECUTABLE", None)
        )

        self.runCmd("settings set target.load-script-from-symbol-file true")
        self.addTearDownHook(
            lambda: self.runCmd(
                "settings set target.load-script-from-symbol-file false"
            )
        )

        dsym_python_dir = os.path.join(
            "%s.dSYM" % aout_exe, "Contents", "Resources", "Python"
        )
        os.makedirs(dsym_python_dir)
        python_os_plugin_path = os.path.join(self.getSourceDir(), "operating_system.py")
        python_init = [
            "def __lldb_init_module(debugger, internal_dict):",
            "  debugger.HandleCommand('settings set target.process.python-os-plugin-path %s')"
            % python_os_plugin_path,
        ]
        with open(os.path.join(dsym_python_dir, "a_out.py"), "w") as writer:
            for l in python_init:
                writer.write(l + "\n")

        dwarfdump_uuid_regex = re.compile("UUID: ([-0-9a-fA-F]+) \(([^\(]+)\) .*")
        dwarfdump_cmd_output = subprocess.check_output(
            ('/usr/bin/dwarfdump --uuid "%s"' % aout_exe), shell=True
        ).decode("utf-8")
        aout_uuid = None
        for line in dwarfdump_cmd_output.splitlines():
            match = dwarfdump_uuid_regex.search(line)
            if match:
                aout_uuid = match.group(1)
        self.assertNotEqual(aout_uuid, None, "Could not get uuid of built a.out")

        ###  Create our dsym-for-uuid shell script which returns aout_exe
        shell_cmds = [
            "#! /bin/sh",
            "# the last argument is the uuid",
            "while [ $# -gt 1 ]",
            "do",
            "  shift",
            "done",
            "ret=0",
            'echo "<?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?>"',
            'echo "<!DOCTYPE plist PUBLIC \\"-//Apple//DTD PLIST 1.0//EN\\" \\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\\">"',
            'echo "<plist version=\\"1.0\\">"',
            "",
            'if [ "$1" != "%s" ]' % (aout_uuid),
            "then",
            '  echo "<key>DBGError</key><string>not found</string>"',
            '  echo "</plist>"',
            "  exit 1",
            "fi",
            "  uuid=%s" % aout_uuid,
            "  bin=%s" % aout_exe,
            "  dsym=%s.dSYM/Contents/Resources/DWARF/%s"
            % (aout_exe, os.path.basename(aout_exe)),
            'echo "<dict><key>$uuid</key><dict>"',
            "",
            'echo "<key>DBGDSYMPath</key><string>$dsym</string>"',
            'echo "<key>DBGSymbolRichExecutable</key><string>$bin</string>"',
            'echo "</dict></dict></plist>"',
            "exit $ret",
        ]

        with open(dsym_for_uuid, "w") as writer:
            for l in shell_cmds:
                writer.write(l + "\n")

        os.chmod(dsym_for_uuid, 0o755)

        ### Now run lldb on the corefile
        ### which will give us a UUID
        ### which we call dsym-for-uuid.sh with
        ### which gives us a binary and dSYM
        ### which lldb should load!

        if self.TraceOn():
            self.runCmd("log enable lldb dyld host")
            self.addTearDownHook(lambda: self.runCmd("log disable lldb dyld host"))
        # Now load the binary and confirm that we load the OS plugin.
        target = self.dbg.CreateTarget("")

        if self.TraceOn():
            self.runCmd(
                "script print('loading corefile %s with OS plugin')"
                % binspec_corefile_addr
            )

        process = target.LoadCore(binspec_corefile_addr)
        self.assertTrue(process.IsValid())
        if self.TraceOn():
            self.runCmd("image list")
            self.runCmd("target mod dump sections")
            self.runCmd("thread list")
        self.assertEqual(target.GetNumModules(), 1)
        fspec = target.GetModuleAtIndex(0).GetFileSpec()
        self.assertEqual(fspec.GetFilename(), aout_exe_basename)

        # 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",
        )
        thread = process.GetThreadByID(0x222222222)
        self.assertTrue(
            thread.IsValid(),
            "Make sure there is a thread 0x222222222 after we load the python OS plug-in",
        )
        thread = process.GetThreadByID(0x333333333)
        self.assertTrue(
            thread.IsValid(),
            "Make sure there is a thread 0x333333333 after we load the python OS plug-in",
        )

        self.runCmd("settings clear target.process.python-os-plugin-path")
        self.dbg.DeleteTarget(target)