LLDB mainline
StopInfoMachException.cpp
Go to the documentation of this file.
1//===-- StopInfoMachException.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
10
11#include "lldb/lldb-forward.h"
12
13#if defined(__APPLE__)
14// Needed for the EXC_RESOURCE interpretation macros
15#include <kern/exc_resource.h>
16#endif
17
19#include "lldb/Symbol/Symbol.h"
20#include "lldb/Target/ABI.h"
23#include "lldb/Target/Process.h"
25#include "lldb/Target/Target.h"
26#include "lldb/Target/Thread.h"
30#include "lldb/Utility/Log.h"
32#include <optional>
33
34using namespace lldb;
35using namespace lldb_private;
36
37/// Information about a pointer-authentication related instruction.
43
44/// Get any pointer-authentication related information about the instruction
45/// at address \p at_addr.
46static std::optional<PtrauthInstructionInfo>
48 const Address &at_addr) {
49 const char *plugin_name = nullptr;
50 const char *flavor = nullptr;
51 const char *cpu = nullptr;
52 const char *features = nullptr;
53 AddressRange range_bounds(at_addr, 4);
54 const bool prefer_file_cache = true;
55 DisassemblerSP disassembler_sp =
56 Disassembler::DisassembleRange(arch, plugin_name, flavor, cpu, features,
57 target, range_bounds, prefer_file_cache);
58 if (!disassembler_sp)
59 return std::nullopt;
60
61 InstructionList &insn_list = disassembler_sp->GetInstructionList();
62 InstructionSP insn = insn_list.GetInstructionAtIndex(0);
63 if (!insn)
64 return std::nullopt;
65
66 return PtrauthInstructionInfo{insn->IsAuthenticated(), insn->IsLoad(),
67 insn->DoesBranch()};
68}
69
70/// Describe the load address of \p addr using the format filename:line:col.
71static void DescribeAddressBriefly(Stream &strm, const Address &addr,
72 Target &target) {
73 strm.Printf("at address=0x%" PRIx64, addr.GetLoadAddress(&target));
75 if (addr.GetDescription(s, target, eDescriptionLevelBrief))
76 strm.Printf(" %s", s.GetString().data());
77 strm.Printf(".\n");
78}
79
80std::optional<addr_t> StopInfoMachException::GetTagFaultAddress() const {
81 const bool bad_access =
82 (m_value == 1 || m_value == 12); // EXC_BAD_ACCESS or EXC_GUARD
83 const bool tag_fault = (m_exc_code == 0x106); // EXC_ARM_MTE_TAG_FAULT
84 // Whether the subcode (m_exc_subcode) holds the fault address.
85 const bool has_fault_addr = (m_exc_data_count >= 2);
86
87 if (bad_access && tag_fault && has_fault_addr)
88 return m_exc_subcode; // The subcode is the fault address.
89
90 return std::nullopt;
91}
92
93static constexpr uint8_t g_mte_tag_shift = 64 - 8;
94static constexpr addr_t g_mte_tag_mask = (addr_t)0x0f << g_mte_tag_shift;
95
97 std::optional<addr_t> fault_address = GetTagFaultAddress();
98 if (!fault_address)
99 return false;
100
101 const uint64_t bad_address = *fault_address;
102
103 StreamString strm;
104 strm.Printf("EXC_ARM_MTE_TAG_FAULT (code=%" PRIu64 ", address=0x%" PRIx64
105 ")\n",
106 m_exc_code, bad_address);
107
108 const uint8_t tag = (bad_address & g_mte_tag_mask) >> g_mte_tag_shift;
109 const addr_t canonical_addr = bad_address & ~g_mte_tag_mask;
110 strm.Printf(
111 "Note: MTE tag mismatch detected: pointer tag=%d, address=0x%" PRIx64,
112 tag, canonical_addr);
113 m_description = std::string(strm.GetString());
114
115 return true;
116}
117
119 bool IsBreakpoint = m_value == 6; // EXC_BREAKPOINT
120 bool IsBadAccess = m_value == 1; // EXC_BAD_ACCESS
121 if (!IsBreakpoint && !IsBadAccess)
122 return false;
123
124 // Check that we have a live process.
125 if (!exe_ctx.HasProcessScope() || !exe_ctx.HasThreadScope() ||
126 !exe_ctx.HasTargetScope())
127 return false;
128
129 Thread &thread = *exe_ctx.GetThreadPtr();
130 StackFrameSP current_frame = thread.GetStackFrameAtIndex(0);
131 if (!current_frame)
132 return false;
133
134 Target &target = *exe_ctx.GetTargetPtr();
135 Process &process = *exe_ctx.GetProcessPtr();
136 const ArchSpec &arch = target.GetArchitecture();
137
138 // Check for a ptrauth-enabled target.
139 const bool ptrauth_enabled_target =
141 if (!ptrauth_enabled_target)
142 return false;
143
144 // Set up a stream we can write a diagnostic into.
145 StreamString strm;
146 auto emit_ptrauth_prologue = [&](uint64_t at_address) {
147 strm.Printf("EXC_BAD_ACCESS (code=%" PRIu64 ", address=0x%" PRIx64 ")\n",
148 m_exc_code, at_address);
149 strm.Printf("Note: Possible pointer authentication failure detected.\n");
150 };
151
152 ABISP abi_sp = process.GetABI();
153 assert(abi_sp && "Missing ABI info");
154
155 // Check if we have a "brk 0xc47x" trap, where the value that failed to
156 // authenticate is in x16.
157 Address current_address = current_frame->GetFrameCodeAddress();
158 if (IsBreakpoint) {
159 RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
160 if (!reg_ctx)
161 return false;
162
163 const RegisterInfo *X16Info = reg_ctx->GetRegisterInfoByName("x16");
164 RegisterValue X16Val;
165 if (!reg_ctx->ReadRegister(X16Info, X16Val))
166 return false;
167 uint64_t bad_address = X16Val.GetAsUInt64();
168
169 uint64_t fixed_bad_address = abi_sp->FixCodeAddress(bad_address);
170 Address brk_address;
171 if (!target.ResolveLoadAddress(fixed_bad_address, brk_address))
172 return false;
173
174 auto brk_ptrauth_info =
175 GetPtrauthInstructionInfo(target, arch, current_address);
176 if (brk_ptrauth_info && brk_ptrauth_info->IsAuthenticated) {
177 emit_ptrauth_prologue(bad_address);
178 strm.Printf("Found value that failed to authenticate ");
179 DescribeAddressBriefly(strm, brk_address, target);
180 m_description = std::string(strm.GetString());
181 return true;
182 }
183 return false;
184 }
185
186 assert(IsBadAccess && "Handle EXC_BAD_ACCESS only after this point");
187
188 // Check that we have the "bad address" from an EXC_BAD_ACCESS.
189 if (m_exc_data_count < 2)
190 return false;
191
192 // Ok, we know the Target is valid and that it describes a ptrauth-enabled
193 // device. Now, we need to determine whether this exception was caused by a
194 // ptrauth failure.
195
196 uint64_t bad_address = m_exc_subcode;
197 uint64_t fixed_bad_address = abi_sp->FixCodeAddress(bad_address);
198 uint64_t current_pc = current_address.GetLoadAddress(&target);
199
200 // Detect: LDRAA, LDRAB (Load Register, with pointer authentication).
201 //
202 // If an authenticated load results in an exception, the instruction at the
203 // current PC should be one of LDRAx.
204 if (bad_address != current_pc && fixed_bad_address != current_pc) {
205 auto ptrauth_info =
206 GetPtrauthInstructionInfo(target, arch, current_address);
207 if (ptrauth_info && ptrauth_info->IsAuthenticated && ptrauth_info->IsLoad) {
208 emit_ptrauth_prologue(bad_address);
209 strm.Printf("Found authenticated load instruction ");
210 DescribeAddressBriefly(strm, current_address, target);
211 m_description = std::string(strm.GetString());
212 return true;
213 }
214 }
215
216 // Detect: BLRAA, BLRAAZ, BLRAB, BLRABZ (Branch with Link to Register, with
217 // pointer authentication).
218 //
219 // TODO: Detect: BRAA, BRAAZ, BRAB, BRABZ (Branch to Register, with pointer
220 // authentication). At a minimum, this requires call site info support for
221 // indirect calls.
222 //
223 // If an authenticated call or tail call results in an exception, stripping
224 // the bad address should give the current PC, which points to the address
225 // we tried to branch to.
226 if (bad_address != current_pc && fixed_bad_address == current_pc) {
227 if (StackFrameSP parent_frame = thread.GetStackFrameAtIndex(1)) {
228 addr_t return_pc =
229 parent_frame->GetFrameCodeAddress().GetLoadAddress(&target);
230 Address blr_address;
231 if (!target.ResolveLoadAddress(return_pc - 4, blr_address))
232 return false;
233
234 auto blr_ptrauth_info =
235 GetPtrauthInstructionInfo(target, arch, blr_address);
236 if (blr_ptrauth_info && blr_ptrauth_info->IsAuthenticated &&
237 blr_ptrauth_info->DoesBranch) {
238 emit_ptrauth_prologue(bad_address);
239 strm.Printf("Found authenticated indirect branch ");
240 DescribeAddressBriefly(strm, blr_address, target);
241 m_description = std::string(strm.GetString());
242 return true;
243 }
244 }
245 }
246
247 // TODO: Detect: RETAA, RETAB (Return from subroutine, with pointer
248 // authentication).
249 //
250 // Is there a motivating, non-malicious code snippet that corrupts LR?
251
252 return false;
253}
254
256 const bool is_bad_access = (m_value == 1);
257 const bool is_cpa2_fault = (m_exc_code == 0x108);
258
259 // Check if subcode has address.
260 const bool has_fault_addr = (m_exc_data_count >= 2);
261
262 if (!is_bad_access || !is_cpa2_fault || !has_fault_addr)
263 return false;
264
265 const addr_t fault_address = m_exc_subcode;
266
267 StreamString strm;
268 strm.Printf("EXC_ARM_CPA_FAIL (code=%" PRIu64 ", address=0x%" PRIx64 ")\n",
269 m_exc_code, fault_address);
270 strm.Printf("Note: Checked Pointer Arithmetic failure detected.\n");
271
272 m_description = std::string(strm.GetString());
273 return true;
274}
275
277 if (!m_description.empty())
278 return m_description.c_str();
280 return "invalid stop reason!";
281
282 ExecutionContext exe_ctx(m_thread_wp.lock());
283 Target *target = exe_ctx.GetTargetPtr();
284 const llvm::Triple::ArchType cpu =
285 target ? target->GetArchitecture().GetMachine()
286 : llvm::Triple::UnknownArch;
287
288 const char *exc_desc = nullptr;
289 const char *code_label = "code";
290 const char *code_desc = nullptr;
291 const char *subcode_label = "subcode";
292 const char *subcode_desc = nullptr;
293
294#if defined(__APPLE__)
295 char code_desc_buf[32];
296 char subcode_desc_buf[32];
297#endif
298
299 switch (m_value) {
300 case 1: // EXC_BAD_ACCESS
301 exc_desc = "EXC_BAD_ACCESS";
302 subcode_label = "address";
303 switch (cpu) {
304 case llvm::Triple::x86:
305 case llvm::Triple::x86_64:
306 switch (m_exc_code) {
307 case 0xd:
308 code_desc = "EXC_I386_GPFLT";
310 break;
311 }
312 break;
313 case llvm::Triple::arm:
314 case llvm::Triple::thumb:
315 switch (m_exc_code) {
316 case 0x101:
317 code_desc = "EXC_ARM_DA_ALIGN";
318 break;
319 case 0x102:
320 code_desc = "EXC_ARM_DA_DEBUG";
321 break;
322 }
323 break;
324
325 case llvm::Triple::aarch64:
326 if (DeterminePtrauthFailure(exe_ctx))
327 return m_description.c_str();
329 return m_description.c_str();
331 return m_description.c_str();
332 break;
333
334 default:
335 break;
336 }
337 break;
338
339 case 2: // EXC_BAD_INSTRUCTION
340 exc_desc = "EXC_BAD_INSTRUCTION";
341 switch (cpu) {
342 case llvm::Triple::x86:
343 case llvm::Triple::x86_64:
344 if (m_exc_code == 1)
345 code_desc = "EXC_I386_INVOP";
346 break;
347
348 case llvm::Triple::arm:
349 case llvm::Triple::thumb:
350 if (m_exc_code == 1)
351 code_desc = "EXC_ARM_UNDEFINED";
352 break;
353
354 default:
355 break;
356 }
357 break;
358
359 case 3: // EXC_ARITHMETIC
360 exc_desc = "EXC_ARITHMETIC";
361 switch (cpu) {
362 case llvm::Triple::x86:
363 case llvm::Triple::x86_64:
364 switch (m_exc_code) {
365 case 1:
366 code_desc = "EXC_I386_DIV";
367 break;
368 case 2:
369 code_desc = "EXC_I386_INTO";
370 break;
371 case 3:
372 code_desc = "EXC_I386_NOEXT";
373 break;
374 case 4:
375 code_desc = "EXC_I386_EXTOVR";
376 break;
377 case 5:
378 code_desc = "EXC_I386_EXTERR";
379 break;
380 case 6:
381 code_desc = "EXC_I386_EMERR";
382 break;
383 case 7:
384 code_desc = "EXC_I386_BOUND";
385 break;
386 case 8:
387 code_desc = "EXC_I386_SSEEXTERR";
388 break;
389 }
390 break;
391
392 default:
393 break;
394 }
395 break;
396
397 case 4: // EXC_EMULATION
398 exc_desc = "EXC_EMULATION";
399 break;
400
401 case 5: // EXC_SOFTWARE
402 exc_desc = "EXC_SOFTWARE";
403 if (m_exc_code == 0x10003) {
404 subcode_desc = "EXC_SOFT_SIGNAL";
405 subcode_label = "signo";
406 }
407 break;
408
409 case 6: // EXC_BREAKPOINT
410 {
411 exc_desc = "EXC_BREAKPOINT";
412 switch (cpu) {
413 case llvm::Triple::x86:
414 case llvm::Triple::x86_64:
415 switch (m_exc_code) {
416 case 1:
417 code_desc = "EXC_I386_SGL";
418 break;
419 case 2:
420 code_desc = "EXC_I386_BPT";
421 break;
422 }
423 break;
424
425 case llvm::Triple::arm:
426 case llvm::Triple::thumb:
427 switch (m_exc_code) {
428 case 0x101:
429 code_desc = "EXC_ARM_DA_ALIGN";
430 break;
431 case 0x102:
432 code_desc = "EXC_ARM_DA_DEBUG";
433 break;
434 case 1:
435 code_desc = "EXC_ARM_BREAKPOINT";
436 break;
437 // FIXME temporary workaround, exc_code 0 does not really mean
438 // EXC_ARM_BREAKPOINT
439 case 0:
440 code_desc = "EXC_ARM_BREAKPOINT";
441 break;
442 }
443 break;
444
445 case llvm::Triple::aarch64:
446 if (DeterminePtrauthFailure(exe_ctx))
447 return m_description.c_str();
448 break;
449
450 default:
451 break;
452 }
453 } break;
454
455 case 7:
456 exc_desc = "EXC_SYSCALL";
457 break;
458
459 case 8:
460 exc_desc = "EXC_MACH_SYSCALL";
461 break;
462
463 case 9:
464 exc_desc = "EXC_RPC_ALERT";
465 break;
466
467 case 10:
468 exc_desc = "EXC_CRASH";
469 break;
470 case 11:
471 exc_desc = "EXC_RESOURCE";
472#if defined(__APPLE__)
473 {
474 int resource_type = EXC_RESOURCE_DECODE_RESOURCE_TYPE(m_exc_code);
475
476 code_label = "limit";
477 code_desc = code_desc_buf;
478 subcode_label = "observed";
479 subcode_desc = subcode_desc_buf;
480
481 switch (resource_type) {
482 case RESOURCE_TYPE_CPU:
483 exc_desc =
484 "EXC_RESOURCE (RESOURCE_TYPE_CPU: CPU usage monitor tripped)";
485 snprintf(code_desc_buf, sizeof(code_desc_buf), "%d%%",
486 (int)EXC_RESOURCE_CPUMONITOR_DECODE_PERCENTAGE(m_exc_code));
487 snprintf(subcode_desc_buf, sizeof(subcode_desc_buf), "%d%%",
488 (int)EXC_RESOURCE_CPUMONITOR_DECODE_PERCENTAGE_OBSERVED(
490 break;
491 case RESOURCE_TYPE_WAKEUPS:
492 exc_desc = "EXC_RESOURCE (RESOURCE_TYPE_WAKEUPS: idle wakeups monitor "
493 "tripped)";
494 snprintf(
495 code_desc_buf, sizeof(code_desc_buf), "%d w/s",
496 (int)EXC_RESOURCE_CPUMONITOR_DECODE_WAKEUPS_PERMITTED(m_exc_code));
497 snprintf(subcode_desc_buf, sizeof(subcode_desc_buf), "%d w/s",
498 (int)EXC_RESOURCE_CPUMONITOR_DECODE_WAKEUPS_OBSERVED(
500 break;
501 case RESOURCE_TYPE_MEMORY:
502 exc_desc = "EXC_RESOURCE (RESOURCE_TYPE_MEMORY: high watermark memory "
503 "limit exceeded)";
504 snprintf(code_desc_buf, sizeof(code_desc_buf), "%d MB",
505 (int)EXC_RESOURCE_HWM_DECODE_LIMIT(m_exc_code));
506 subcode_desc = nullptr;
507 subcode_label = nullptr;
508 break;
509#if defined(RESOURCE_TYPE_IO)
510 // RESOURCE_TYPE_IO is introduced in macOS SDK 10.12.
511 case RESOURCE_TYPE_IO:
512 exc_desc = "EXC_RESOURCE RESOURCE_TYPE_IO";
513 snprintf(code_desc_buf, sizeof(code_desc_buf), "%d MB",
514 (int)EXC_RESOURCE_IO_DECODE_LIMIT(m_exc_code));
515 snprintf(subcode_desc_buf, sizeof(subcode_desc_buf), "%d MB",
516 (int)EXC_RESOURCE_IO_OBSERVED(m_exc_subcode));
517 ;
518 break;
519#endif
520 }
521 }
522#endif
523 break;
524 case 12:
526 return m_description.c_str();
527 exc_desc = "EXC_GUARD";
528 break;
529 }
530
531 StreamString strm;
532
533 if (exc_desc)
534 strm.PutCString(exc_desc);
535 else
536 strm.Printf("EXC_??? (%" PRIu64 ")", m_value);
537
538 if (m_exc_data_count >= 1) {
539 if (code_desc)
540 strm.Printf(" (%s=%s", code_label, code_desc);
541 else
542 strm.Printf(" (%s=%" PRIu64, code_label, m_exc_code);
543 }
544
545 if (m_exc_data_count >= 2) {
546 if (subcode_label && subcode_desc)
547 strm.Printf(", %s=%s", subcode_label, subcode_desc);
548 else if (subcode_label)
549 strm.Printf(", %s=0x%" PRIx64, subcode_label, m_exc_subcode);
550 }
551
552 if (m_exc_data_count > 0)
553 strm.PutChar(')');
554
555 m_description = std::string(strm.GetString());
556 return m_description.c_str();
557}
558
559#if defined(__APPLE__)
560const char *
561StopInfoMachException::MachException::Name(exception_type_t exc_type) {
562 switch (exc_type) {
563 case EXC_BAD_ACCESS:
564 return "EXC_BAD_ACCESS";
565 case EXC_BAD_INSTRUCTION:
566 return "EXC_BAD_INSTRUCTION";
567 case EXC_ARITHMETIC:
568 return "EXC_ARITHMETIC";
569 case EXC_EMULATION:
570 return "EXC_EMULATION";
571 case EXC_SOFTWARE:
572 return "EXC_SOFTWARE";
573 case EXC_BREAKPOINT:
574 return "EXC_BREAKPOINT";
575 case EXC_SYSCALL:
576 return "EXC_SYSCALL";
577 case EXC_MACH_SYSCALL:
578 return "EXC_MACH_SYSCALL";
579 case EXC_RPC_ALERT:
580 return "EXC_RPC_ALERT";
581#ifdef EXC_CRASH
582 case EXC_CRASH:
583 return "EXC_CRASH";
584#endif
585 case EXC_RESOURCE:
586 return "EXC_RESOURCE";
587#ifdef EXC_GUARD
588 case EXC_GUARD:
589 return "EXC_GUARD";
590#endif
591#ifdef EXC_CORPSE_NOTIFY
592 case EXC_CORPSE_NOTIFY:
593 return "EXC_CORPSE_NOTIFY";
594#endif
595#ifdef EXC_CORPSE_VARIANT_BIT
596 case EXC_CORPSE_VARIANT_BIT:
597 return "EXC_CORPSE_VARIANT_BIT";
598#endif
599 default:
600 break;
601 }
602 return NULL;
603}
604
605std::optional<exception_type_t>
606StopInfoMachException::MachException::ExceptionCode(const char *name) {
607 return llvm::StringSwitch<std::optional<exception_type_t>>(name)
608 .Case("EXC_BAD_ACCESS", EXC_BAD_ACCESS)
609 .Case("EXC_BAD_INSTRUCTION", EXC_BAD_INSTRUCTION)
610 .Case("EXC_ARITHMETIC", EXC_ARITHMETIC)
611 .Case("EXC_EMULATION", EXC_EMULATION)
612 .Case("EXC_SOFTWARE", EXC_SOFTWARE)
613 .Case("EXC_BREAKPOINT", EXC_BREAKPOINT)
614 .Case("EXC_SYSCALL", EXC_SYSCALL)
615 .Case("EXC_MACH_SYSCALL", EXC_MACH_SYSCALL)
616 .Case("EXC_RPC_ALERT", EXC_RPC_ALERT)
617#ifdef EXC_CRASH
618 .Case("EXC_CRASH", EXC_CRASH)
619#endif
620 .Case("EXC_RESOURCE", EXC_RESOURCE)
621#ifdef EXC_GUARD
622 .Case("EXC_GUARD", EXC_GUARD)
623#endif
624#ifdef EXC_CORPSE_NOTIFY
625 .Case("EXC_CORPSE_NOTIFY", EXC_CORPSE_NOTIFY)
626#endif
627 .Default(std::nullopt);
628}
629#endif
630
632 Thread &thread, uint32_t exc_type, uint32_t exc_data_count,
633 uint64_t exc_code, uint64_t exc_sub_code, uint64_t exc_sub_sub_code,
634 bool pc_already_adjusted, bool adjust_pc_if_needed) {
635 if (exc_type == 0)
636 return StopInfoSP();
637
638 bool not_stepping_but_got_singlestep_exception = false;
639 uint32_t pc_decrement = 0;
640 ExecutionContext exe_ctx(thread.shared_from_this());
641 Target *target = exe_ctx.GetTargetPtr();
642 const llvm::Triple::ArchType cpu =
643 target ? target->GetArchitecture().GetMachine()
644 : llvm::Triple::UnknownArch;
645
646 ProcessSP process_sp(thread.GetProcess());
647 RegisterContextSP reg_ctx_sp(thread.GetRegisterContext());
648 // Caveat: with x86 KDP if we've hit a breakpoint, the pc we
649 // receive is past the breakpoint instruction.
650 // If we have a breakpoints at 0x100 and 0x101, we hit the
651 // 0x100 breakpoint and the pc is reported at 0x101.
652 // We will initially mark this thread as being stopped at an
653 // unexecuted breakpoint at 0x101. Later when we see that
654 // we stopped for a Breakpoint reason, we will decrement the
655 // pc, and update the thread to record that we hit the
656 // breakpoint at 0x100.
657 // The fact that the pc may be off by one at this point
658 // (for an x86 KDP breakpoint hit) is not a problem.
659 addr_t pc = reg_ctx_sp->GetPC();
660 BreakpointSiteSP bp_site_sp =
661 process_sp->GetBreakpointSiteList().FindByAddress(pc);
662 if (bp_site_sp && process_sp->IsBreakpointSitePhysicallyEnabled(*bp_site_sp))
663 thread.SetThreadStoppedAtUnexecutedBP(pc);
664
665 switch (exc_type) {
666 case 1: // EXC_BAD_ACCESS
667 case 2: // EXC_BAD_INSTRUCTION
668 case 3: // EXC_ARITHMETIC
669 case 4: // EXC_EMULATION
670 break;
671
672 case 5: // EXC_SOFTWARE
673 if (exc_code == 0x10003) // EXC_SOFT_SIGNAL
674 {
675 if (exc_sub_code == 5) {
676 // On MacOSX, a SIGTRAP can signify that a process has called exec,
677 // so we should check with our dynamic loader to verify.
678 ProcessSP process_sp(thread.GetProcess());
679 if (process_sp) {
680 DynamicLoader *dynamic_loader = process_sp->GetDynamicLoader();
681 if (dynamic_loader && dynamic_loader->ProcessDidExec()) {
682 // The program was re-exec'ed
684 }
685 }
686 }
687 return StopInfo::CreateStopReasonWithSignal(thread, exc_sub_code);
688 }
689 break;
690
691 // A mach exception comes with 2-4 pieces of data.
692 // The sub-codes are only provided for certain types
693 // of mach exceptions.
694 // [exc_type, exc_code, exc_sub_code, exc_sub_sub_code]
695 //
696 // Here are all of the EXC_BREAKPOINT, exc_type==6,
697 // exceptions we can receive.
698 //
699 // Instruction step:
700 // [6, 1, 0]
701 // Intel KDP [6, 3, ??]
702 // armv7 [6, 0x102, <stop-pc>] Same as software breakpoint!
703 //
704 // Software breakpoint:
705 // x86 [6, 2, 0]
706 // Intel KDP [6, 2, <bp-addr + 1>]
707 // arm64 [6, 1, <bp-addr>]
708 // armv7 [6, 0x102, <bp-addr>] Same as instruction step!
709 //
710 // Hardware breakpoint:
711 // x86 [6, 1, <bp-addr>, 0]
712 // x86/Rosetta not implemented, see software breakpoint
713 // arm64 [6, 1, <bp-addr>]
714 // armv7 not implemented, see software breakpoint
715 //
716 // Hardware watchpoint:
717 // x86 [6, 1, <accessed-addr>, 0] (both Intel hw and Rosetta)
718 // arm64 [6, 0x102, <accessed-addr>, 0]
719 // armv7 [6, 0x102, <accessed-addr>, 0]
720 //
721 // arm64 BRK instruction (imm arg not reflected in the ME)
722 // [ 6, 1, <addr-of-BRK-insn>]
723 //
724 // In order of codes mach exceptions:
725 // [6, 1, 0] - instruction step
726 // [6, 1, <bp-addr>] - hardware breakpoint or watchpoint
727 //
728 // [6, 2, 0] - software breakpoint
729 // [6, 2, <bp-addr + 1>] - software breakpoint
730 //
731 // [6, 3] - instruction step
732 //
733 // [6, 0x102, <stop-pc>] armv7 instruction step
734 // [6, 0x102, <bp-addr>] armv7 software breakpoint
735 // [6, 0x102, <accessed-addr>, 0] arm64/armv7 watchpoint
736
737 case 6: // EXC_BREAKPOINT
738 {
739 bool stopped_by_hitting_breakpoint = false;
740 bool stopped_by_completing_stepi = false;
741 bool stopped_watchpoint = false;
742 std::optional<addr_t> address;
743
744 // exc_code 1
745 if (exc_code == 1) {
746 if (exc_sub_code == 0) {
747 stopped_by_completing_stepi = true;
748 } else {
749 // Ambiguous: could be signalling a
750 // breakpoint or watchpoint hit.
751 stopped_by_hitting_breakpoint = true;
752 stopped_watchpoint = true;
753 address = exc_sub_code;
754 }
755 }
756
757 // exc_code 2
758 if (exc_code == 2) {
759 if (exc_sub_code == 0)
760 stopped_by_hitting_breakpoint = true;
761 else {
762 stopped_by_hitting_breakpoint = true;
763 // Intel KDP software breakpoint
764 if (!pc_already_adjusted)
765 pc_decrement = 1;
766 }
767 }
768
769 // exc_code 3
770 if (exc_code == 3)
771 stopped_by_completing_stepi = true;
772
773 // exc_code 0x102
774 if (exc_code == 0x102 && exc_sub_code != 0) {
775 if (cpu == llvm::Triple::arm || cpu == llvm::Triple::thumb) {
776 stopped_by_hitting_breakpoint = true;
777 stopped_by_completing_stepi = true;
778 }
779 stopped_watchpoint = true;
780 address = exc_sub_code;
781 }
782
783 // The Mach Exception may have been ambiguous --
784 // e.g. we stopped either because of a breakpoint
785 // or a watchpoint. We'll disambiguate which it
786 // really was.
787
788 if (stopped_by_hitting_breakpoint) {
789 addr_t pc = reg_ctx_sp->GetPC() - pc_decrement;
790
791 if (address)
792 bp_site_sp =
793 process_sp->GetBreakpointSiteList().FindByAddress(*address);
794 if (!bp_site_sp && reg_ctx_sp) {
795 bp_site_sp = process_sp->GetBreakpointSiteList().FindByAddress(pc);
796 }
797 if (bp_site_sp &&
798 process_sp->IsBreakpointSitePhysicallyEnabled(*bp_site_sp)) {
799 // We've hit this breakpoint, whether it was intended for this thread
800 // or not. Clear this in the Tread object so we step past it on resume.
801 thread.SetThreadHitBreakpointSite();
802
803 if (bp_site_sp->ValidForThisThread(thread)) {
804 // Update the PC if we were asked to do so, but only do so if we find
805 // a breakpoint that we know about because this could be a trap
806 // instruction in the code.
807 if (pc_decrement > 0 && adjust_pc_if_needed && reg_ctx_sp)
808 reg_ctx_sp->SetPC(pc);
809
811 thread, bp_site_sp->GetID());
812 } else {
813 return StopInfoSP();
814 }
815 }
816 }
817
818 // Breakpoint-hit events are handled.
819 // Now handle watchpoints.
820
821 if (stopped_watchpoint && address) {
822 WatchpointResourceSP wp_rsrc_sp =
823 target->GetProcessSP()->GetWatchpointResourceList().FindByAddress(
824 *address);
825 if (wp_rsrc_sp && wp_rsrc_sp->GetNumberOfConstituents() > 0) {
827 thread, wp_rsrc_sp->GetConstituentAtIndex(0)->GetID());
828 }
829 }
830
831 // Finally, handle instruction step.
832
833 if (stopped_by_completing_stepi) {
834 if (thread.GetTemporaryResumeState() != eStateStepping)
835 not_stepping_but_got_singlestep_exception = true;
836 else
838 }
839
840 } break;
841
842 case 7: // EXC_SYSCALL
843 case 8: // EXC_MACH_SYSCALL
844 case 9: // EXC_RPC_ALERT
845 case 10: // EXC_CRASH
846 break;
847 }
848
849 return std::make_shared<StopInfoMachException>(
850 thread, exc_type, exc_data_count, exc_code, exc_sub_code,
851 not_stepping_but_got_singlestep_exception);
852}
853
854void StopInfoMachException::PerformAction([[maybe_unused]] Event *event_ptr) {
855 // This action currently only fires if the exception is an ARM breakpoint
856 // and if the PC is still at the instruction that caused the exception.
857 if (!(m_value == 6 /*EXC_BREAKPOINT*/ &&
858 m_exc_code == 1 /*EXC_ARM_BREAKPOINT*/) ||
859 m_exc_subcode != m_thread_wp.lock()->GetRegisterContext()->GetPC())
860 return;
862}
863
864// Detect an unusual situation on Darwin where:
865//
866// 0. We did an instruction-step before this.
867// 1. We have a hardware breakpoint or watchpoint set.
868// 2. We resumed the process, but not with an instruction-step.
869// 3. The thread gets an "instruction-step completed" mach exception.
870// 4. The pc has not advanced - it is the same as before.
871//
872// This method returns true for that combination of events.
874 Log *log = GetLog(LLDBLog::Step);
875
876 // We got an instruction-step completed mach exception but we were not
877 // doing an instruction step on this thread.
879 return false;
880
881 RegisterContextSP reg_ctx_sp(thread.GetRegisterContext());
882 std::optional<addr_t> prev_pc = thread.GetPreviousFrameZeroPC();
883 if (!reg_ctx_sp || !prev_pc)
884 return false;
885
886 // The previous pc value and current pc value are the same.
887 if (*prev_pc != reg_ctx_sp->GetPC())
888 return false;
889
890 // We have a watchpoint -- this is the kernel bug.
891 ProcessSP process_sp = thread.GetProcess();
892 if (process_sp->GetWatchpointResourceList().GetSize()) {
893 LLDB_LOGF(log,
894 "Thread stopped with insn-step completed mach exception but "
895 "thread was not stepping; there is a hardware watchpoint set.");
896 return true;
897 }
898
899 // We have a hardware breakpoint -- this is the kernel bug.
900 auto &bp_site_list = process_sp->GetBreakpointSiteList();
901 for (auto &site : bp_site_list.Sites()) {
902 if (site->IsHardware() &&
903 process_sp->IsBreakpointSitePhysicallyEnabled(*site)) {
904 LLDB_LOGF(log,
905 "Thread stopped with insn-step completed mach exception but "
906 "thread was not stepping; there is a hardware breakpoint set.");
907 return true;
908 }
909 }
910
911 return false;
912}
#define LLDB_LOGF(log,...)
Definition Log.h:389
static std::optional< PtrauthInstructionInfo > GetPtrauthInstructionInfo(Target &target, const ArchSpec &arch, const Address &at_addr)
Get any pointer-authentication related information about the instruction at address at_addr.
static constexpr uint8_t g_mte_tag_shift
static constexpr addr_t g_mte_tag_mask
static void DescribeAddressBriefly(Stream &strm, const Address &addr, Target &target)
Describe the load address of addr using the format filename:line:col.
A section + offset based address range class.
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition Address.cpp:303
bool GetDescription(Stream &s, Target &target, lldb::DescriptionLevel level) const
Write a description of this object to a Stream.
Definition Address.cpp:385
An architecture specification class.
Definition ArchSpec.h:32
llvm::Triple::ArchType GetMachine() const
Returns a machine family for the current architecture.
Definition ArchSpec.cpp:886
Core GetCore() const
Definition ArchSpec.h:536
static lldb::DisassemblerSP DisassembleRange(const ArchSpec &arch, const char *plugin_name, const char *flavor, const char *cpu, const char *features, Target &target, llvm::ArrayRef< AddressRange > disasm_ranges, bool force_live_memory=false)
A plug-in interface definition class for dynamic loaders.
virtual bool ProcessDidExec()
Helper function that can be used to detect when a process has called exec and is now a new and differ...
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
bool HasThreadScope() const
Returns true the ExecutionContext object contains a valid target, process, and thread.
bool HasProcessScope() const
Returns true the ExecutionContext object contains a valid target and process.
Target * GetTargetPtr() const
Returns a pointer to the target object.
bool HasTargetScope() const
Returns true the ExecutionContext object contains a valid target.
Process * GetProcessPtr() const
Returns a pointer to the process object.
RegisterContext * GetRegisterContext() const
Thread * GetThreadPtr() const
Returns a pointer to the thread object.
lldb::InstructionSP GetInstructionAtIndex(size_t idx) const
A plug-in interface definition class for debugging a process.
Definition Process.h:369
const lldb::ABISP & GetABI()
Definition Process.cpp:1529
const RegisterInfo * GetRegisterInfoByName(llvm::StringRef reg_name, uint32_t start_idx=0)
virtual bool ReadRegister(const RegisterInfo *reg_info, RegisterValue &reg_value)=0
uint64_t GetAsUInt64(uint64_t fail_value=UINT64_MAX, bool *success_ptr=nullptr) const
void PerformAction(Event *event_ptr) override
Allow this plugin to respond to stop events to enable skip-over-trap behaviour on AArch64.
bool DeterminePtrauthFailure(ExecutionContext &exe_ctx)
Determine the pointer-authentication related failure that caused this exception.
bool WasContinueInterrupted(Thread &thread) override
A Continue operation can result in a false stop event before any execution has happened.
std::optional< lldb::addr_t > GetTagFaultAddress() const
static lldb::StopInfoSP CreateStopReasonWithMachException(Thread &thread, uint32_t exc_type, uint32_t exc_data_count, uint64_t exc_code, uint64_t exc_sub_code, uint64_t exc_sub_sub_code, bool pc_already_adjusted=true, bool adjust_pc_if_needed=false)
std::string m_description
Definition StopInfo.h:233
uint64_t GetValue() const
Definition StopInfo.h:46
static lldb::StopInfoSP CreateStopReasonToTrace(Thread &thread)
static lldb::StopInfoSP CreateStopReasonWithSignal(Thread &thread, int signo, const char *description=nullptr, std::optional< int > code=std::nullopt)
static lldb::StopInfoSP CreateStopReasonWithWatchpointID(Thread &thread, lldb::break_id_t watch_id, bool silently_continue=false)
static lldb::StopInfoSP CreateStopReasonWithBreakpointSiteID(Thread &thread, lldb::break_id_t break_id)
static lldb::StopInfoSP CreateStopReasonWithExec(Thread &thread)
friend class Thread
Definition StopInfo.h:251
lldb::ThreadWP m_thread_wp
Definition StopInfo.h:228
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t PutChar(char ch)
Definition Stream.cpp:131
const lldb::ProcessSP & GetProcessSP() const
Definition Target.cpp:330
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow, bool allow_section_end=false)
Definition Target.cpp:3507
const ArchSpec & GetArchitecture() const
Definition Target.h:1321
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
std::shared_ptr< lldb_private::ABI > ABISP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::BreakpointSite > BreakpointSiteSP
@ eDescriptionLevelBrief
@ eStateStepping
Process or thread is in the process of stepping and can not be examined.
std::shared_ptr< lldb_private::Instruction > InstructionSP
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::Disassembler > DisassemblerSP
std::shared_ptr< lldb_private::WatchpointResource > WatchpointResourceSP
std::shared_ptr< lldb_private::StopInfo > StopInfoSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
Information about a pointer-authentication related instruction.
Every register is described in detail including its name, alternate name (optional),...