LLDB mainline
AppleObjCRuntimeV2.cpp
Go to the documentation of this file.
1//===-- AppleObjCRuntimeV2.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
11
12#include "lldb/Core/Debugger.h"
14#include "lldb/Core/Module.h"
16#include "lldb/Core/Section.h"
28#include "lldb/Symbol/Symbol.h"
31#include "lldb/Target/ABI.h"
36#include "lldb/Target/Process.h"
39#include "lldb/Target/Target.h"
40#include "lldb/Target/Thread.h"
43#include "lldb/Utility/Log.h"
45#include "lldb/Utility/Scalar.h"
46#include "lldb/Utility/Status.h"
47#include "lldb/Utility/Stream.h"
49#include "lldb/Utility/Timer.h"
53
55#include "AppleObjCDeclVendor.h"
56#include "AppleObjCRuntimeV2.h"
59
60#include "clang/AST/ASTContext.h"
61#include "clang/AST/DeclObjC.h"
62#include "clang/Basic/TargetInfo.h"
63#include "llvm/ADT/STLExtras.h"
64#include "llvm/ADT/ScopeExit.h"
65#include "llvm/ADT/Sequence.h"
66#include "llvm/Support/Error.h"
67
68#include <cstdint>
69#include <memory>
70#include <optional>
71#include <string>
72#include <vector>
73
74using namespace lldb;
75using namespace lldb_private;
76
77namespace {
78struct RuntimeGlobalSymbolSpec {
79 ConstString name;
80
81 /// Whether to only return the address or also the value.
82 bool read_value = true;
83
84 /// A byte size of 0 means use the process pointer size.
85 uint8_t byte_size = 0;
86};
87
88struct RuntimeGlobalSymbolResult {
89 uint64_t value = LLDB_INVALID_ADDRESS;
90 bool success = false;
91};
92} // namespace
93
95
97 "__lldb_apple_objc_v2_get_dynamic_class_info";
98
99static const char *g_get_dynamic_class_info_body = R"(
100
101extern "C"
102{
103 size_t strlen(const char *);
104 char *strncpy (char * s1, const char * s2, size_t n);
105 int printf(const char * format, ...);
106}
107#define DEBUG_PRINTF(fmt, ...) if (should_log) printf(fmt, ## __VA_ARGS__)
108
109typedef struct _NXMapTable {
110 void *prototype;
111 unsigned num_classes;
112 unsigned num_buckets_minus_one;
113 void *buckets;
114} NXMapTable;
115
116#define NX_MAPNOTAKEY ((void *)(-1))
117
118typedef struct BucketInfo
119{
120 const char *name_ptr;
121 Class isa;
122} BucketInfo;
123
124struct ClassInfo
125{
126 Class isa;
127 uint32_t hash;
128} __attribute__((__packed__));
129
130uint32_t
131__lldb_apple_objc_v2_get_dynamic_class_info (void *gdb_objc_realized_classes_ptr,
132 void *class_infos_ptr,
133 uint32_t class_infos_byte_size,
134 uint32_t should_log)
135{
136 DEBUG_PRINTF ("gdb_objc_realized_classes_ptr = %p\n", gdb_objc_realized_classes_ptr);
137 DEBUG_PRINTF ("class_infos_ptr = %p\n", class_infos_ptr);
138 DEBUG_PRINTF ("class_infos_byte_size = %u\n", class_infos_byte_size);
139 const NXMapTable *grc = (const NXMapTable *)gdb_objc_realized_classes_ptr;
140 if (grc)
141 {
142 const unsigned num_classes = grc->num_classes;
143 DEBUG_PRINTF ("num_classes = %u\n", grc->num_classes);
144 if (class_infos_ptr)
145 {
146 const unsigned num_buckets_minus_one = grc->num_buckets_minus_one;
147 DEBUG_PRINTF ("num_buckets_minus_one = %u\n", num_buckets_minus_one);
148
149 const size_t max_class_infos = class_infos_byte_size/sizeof(ClassInfo);
150 DEBUG_PRINTF ("max_class_infos = %u\n", max_class_infos);
151
152 ClassInfo *class_infos = (ClassInfo *)class_infos_ptr;
153 BucketInfo *buckets = (BucketInfo *)grc->buckets;
154
155 uint32_t idx = 0;
156 for (unsigned i=0; i<=num_buckets_minus_one; ++i)
157 {
158 if (buckets[i].name_ptr != NX_MAPNOTAKEY)
159 {
160 if (idx < max_class_infos)
161 {
162 const char *s = buckets[i].name_ptr;
163 uint32_t h = 5381;
164 for (unsigned char c = *s; c; c = *++s)
165 h = ((h << 5) + h) + c;
166 class_infos[idx].hash = h;
167 class_infos[idx].isa = buckets[i].isa;
168 DEBUG_PRINTF ("[%u] isa = %8p %s\n", idx, class_infos[idx].isa, buckets[i].name_ptr);
169 }
170 ++idx;
171 }
172 }
173 if (idx < max_class_infos)
174 {
175 class_infos[idx].isa = NULL;
176 class_infos[idx].hash = 0;
177 }
178 }
179 return num_classes;
180 }
181 return 0;
182}
183
184)";
185
187 "__lldb_apple_objc_v2_get_dynamic_class_info2";
188
189static const char *g_get_dynamic_class_info2_body = R"(
190
191extern "C" {
192 int printf(const char * format, ...);
193 void free(void *ptr);
194 Class* objc_copyRealizedClassList_nolock(unsigned int *outCount);
195 const char* objc_debug_class_getNameRaw(Class cls);
196}
197
198#define DEBUG_PRINTF(fmt, ...) if (should_log) printf(fmt, ## __VA_ARGS__)
199
200struct ClassInfo
201{
202 Class isa;
203 uint32_t hash;
204} __attribute__((__packed__));
205
206uint32_t
207__lldb_apple_objc_v2_get_dynamic_class_info2(void *gdb_objc_realized_classes_ptr,
208 void *class_infos_ptr,
209 uint32_t class_infos_byte_size,
210 uint32_t should_log)
211{
212 DEBUG_PRINTF ("class_infos_ptr = %p\n", class_infos_ptr);
213 DEBUG_PRINTF ("class_infos_byte_size = %u\n", class_infos_byte_size);
214
215 const size_t max_class_infos = class_infos_byte_size/sizeof(ClassInfo);
216 DEBUG_PRINTF ("max_class_infos = %u\n", max_class_infos);
217
218 ClassInfo *class_infos = (ClassInfo *)class_infos_ptr;
219
220 uint32_t count = 0;
221 Class* realized_class_list = objc_copyRealizedClassList_nolock(&count);
222 DEBUG_PRINTF ("count = %u\n", count);
223
224 uint32_t idx = 0;
225 for (uint32_t i=0; i<count; ++i)
226 {
227 if (idx < max_class_infos)
228 {
229 Class isa = realized_class_list[i];
230 const char *name_ptr = objc_debug_class_getNameRaw(isa);
231 if (!name_ptr)
232 continue;
233 const char *s = name_ptr;
234 uint32_t h = 5381;
235 for (unsigned char c = *s; c; c = *++s)
236 h = ((h << 5) + h) + c;
237 class_infos[idx].hash = h;
238 class_infos[idx].isa = isa;
239 DEBUG_PRINTF ("[%u] isa = %8p %s\n", idx, class_infos[idx].isa, name_ptr);
240 }
241 idx++;
242 }
243
244 if (idx < max_class_infos)
245 {
246 class_infos[idx].isa = NULL;
247 class_infos[idx].hash = 0;
248 }
249
250 free(realized_class_list);
251 return count;
252}
253)";
254
256 "__lldb_apple_objc_v2_get_dynamic_class_info3";
257
258static const char *g_get_dynamic_class_info3_body = R"(
259
260extern "C" {
261 int printf(const char * format, ...);
262 void free(void *ptr);
263 size_t objc_getRealizedClassList_trylock(Class *buffer, size_t len);
264 const char* objc_debug_class_getNameRaw(Class cls);
265 const char* class_getName(Class cls);
266}
267
268#define DEBUG_PRINTF(fmt, ...) if (should_log) printf(fmt, ## __VA_ARGS__)
269
270struct ClassInfo
271{
272 Class isa;
273 uint32_t hash;
274} __attribute__((__packed__));
275
276uint32_t
277__lldb_apple_objc_v2_get_dynamic_class_info3(void *gdb_objc_realized_classes_ptr,
278 void *class_infos_ptr,
279 uint32_t class_infos_byte_size,
280 void *class_buffer,
281 uint32_t class_buffer_len,
282 uint32_t should_log)
283{
284 DEBUG_PRINTF ("class_infos_ptr = %p\n", class_infos_ptr);
285 DEBUG_PRINTF ("class_infos_byte_size = %u\n", class_infos_byte_size);
286
287 const size_t max_class_infos = class_infos_byte_size/sizeof(ClassInfo);
288 DEBUG_PRINTF ("max_class_infos = %u\n", max_class_infos);
289
290 ClassInfo *class_infos = (ClassInfo *)class_infos_ptr;
291
292 Class *realized_class_list = (Class*)class_buffer;
293
294 uint32_t count = objc_getRealizedClassList_trylock(realized_class_list,
295 class_buffer_len);
296 DEBUG_PRINTF ("count = %u\n", count);
297
298 uint32_t idx = 0;
299 for (uint32_t i=0; i<count; ++i)
300 {
301 if (idx < max_class_infos)
302 {
303 Class isa = realized_class_list[i];
304 const char *name_ptr = objc_debug_class_getNameRaw(isa);
305 if (!name_ptr) {
306 class_getName(isa); // Realize name of lazy classes.
307 name_ptr = objc_debug_class_getNameRaw(isa);
308 }
309 if (!name_ptr)
310 continue;
311 const char *s = name_ptr;
312 uint32_t h = 5381;
313 for (unsigned char c = *s; c; c = *++s)
314 h = ((h << 5) + h) + c;
315 class_infos[idx].hash = h;
316 class_infos[idx].isa = isa;
317 DEBUG_PRINTF ("[%u] isa = %8p %s\n", idx, class_infos[idx].isa, name_ptr);
318 }
319 idx++;
320 }
321
322 if (idx < max_class_infos)
323 {
324 class_infos[idx].isa = NULL;
325 class_infos[idx].hash = 0;
326 }
327
328 return count;
329}
330)";
331
332// We'll substitute in class_getName or class_getNameRaw depending
333// on which is present.
334static const char *g_shared_cache_class_name_funcptr = R"(
335extern "C"
336{
337 const char *{0}(void *objc_class);
338 const char *(*class_name_lookup_func)(void *) = {1};
339}
340)";
341
343 "__lldb_apple_objc_v2_get_shared_cache_class_info";
344
346
347extern "C"
348{
349 size_t strlen(const char *);
350 char *strncpy (char * s1, const char * s2, size_t n);
351 int printf(const char * format, ...);
352}
353
354#define DEBUG_PRINTF(fmt, ...) if (should_log) printf(fmt, ## __VA_ARGS__)
355
356
357struct objc_classheader_t {
358 int32_t clsOffset;
359 int32_t hiOffset;
360};
361
362struct objc_classheader_v16_t {
363 uint64_t isDuplicate : 1,
364 objectCacheOffset : 47, // Offset from the shared cache base
365 dylibObjCIndex : 16;
366};
367
368struct objc_clsopt_t {
369 uint32_t capacity;
370 uint32_t occupied;
371 uint32_t shift;
372 uint32_t mask;
373 uint32_t zero;
374 uint32_t unused;
375 uint64_t salt;
376 uint32_t scramble[256];
377 uint8_t tab[0]; // tab[mask+1]
378 // uint8_t checkbytes[capacity];
379 // int32_t offset[capacity];
380 // objc_classheader_t clsOffsets[capacity];
381 // uint32_t duplicateCount;
382 // objc_classheader_t duplicateOffsets[duplicateCount];
383};
384
385struct objc_clsopt_v16_t {
386 uint32_t version;
387 uint32_t capacity;
388 uint32_t occupied;
389 uint32_t shift;
390 uint32_t mask;
391 uint32_t zero;
392 uint64_t salt;
393 uint32_t scramble[256];
394 uint8_t tab[0]; // tab[mask+1]
395 // uint8_t checkbytes[capacity];
396 // int32_t offset[capacity];
397 // objc_classheader_t clsOffsets[capacity];
398 // uint32_t duplicateCount;
399 // objc_classheader_t duplicateOffsets[duplicateCount];
400};
401
402struct objc_opt_t {
403 uint32_t version;
404 int32_t selopt_offset;
405 int32_t headeropt_offset;
406 int32_t clsopt_offset;
407};
408
409struct objc_opt_v14_t {
410 uint32_t version;
411 uint32_t flags;
412 int32_t selopt_offset;
413 int32_t headeropt_offset;
414 int32_t clsopt_offset;
415};
416
417struct objc_opt_v16_t {
418 uint32_t version;
419 uint32_t flags;
420 int32_t selopt_offset;
421 int32_t headeropt_ro_offset;
422 int32_t unused_clsopt_offset;
423 int32_t unused_protocolopt_offset;
424 int32_t headeropt_rw_offset;
425 int32_t unused_protocolopt2_offset;
426 int32_t largeSharedCachesClassOffset;
427 int32_t largeSharedCachesProtocolOffset;
428 uint64_t relativeMethodSelectorBaseAddressCacheOffset;
429};
430
431struct ClassInfo
432{
433 Class isa;
434 uint32_t hash;
435} __attribute__((__packed__));
436)";
437
439
440uint32_t
441__lldb_apple_objc_v2_get_shared_cache_class_info (void *objc_opt_ro_ptr,
442 void *shared_cache_base_ptr,
443 void *class_infos_ptr,
444 uint64_t *relative_selector_offset,
445 uint32_t class_infos_byte_size,
446 uint32_t *start_idx,
447 uint32_t should_log)
448{
449 *relative_selector_offset = 0;
450 uint32_t idx = 0;
451 DEBUG_PRINTF ("objc_opt_ro_ptr = %p\n", objc_opt_ro_ptr);
452 DEBUG_PRINTF ("shared_cache_base_ptr = %p\n", shared_cache_base_ptr);
453 DEBUG_PRINTF ("class_infos_ptr = %p\n", class_infos_ptr);
454 DEBUG_PRINTF ("class_infos_byte_size = %u (%llu class infos)\n", class_infos_byte_size, (uint64_t)(class_infos_byte_size/sizeof(ClassInfo)));
455 DEBUG_PRINTF ("start_idx = %u\n", *start_idx);
456 if (objc_opt_ro_ptr)
457 {
458 const objc_opt_t *objc_opt = (objc_opt_t *)objc_opt_ro_ptr;
459 const objc_opt_v14_t* objc_opt_v14 = (objc_opt_v14_t*)objc_opt_ro_ptr;
460 const objc_opt_v16_t* objc_opt_v16 = (objc_opt_v16_t*)objc_opt_ro_ptr;
461 if (objc_opt->version >= 16)
462 {
463 *relative_selector_offset = objc_opt_v16->relativeMethodSelectorBaseAddressCacheOffset;
464 DEBUG_PRINTF ("objc_opt->version = %u\n", objc_opt_v16->version);
465 DEBUG_PRINTF ("objc_opt->flags = %u\n", objc_opt_v16->flags);
466 DEBUG_PRINTF ("objc_opt->selopt_offset = %d\n", objc_opt_v16->selopt_offset);
467 DEBUG_PRINTF ("objc_opt->headeropt_ro_offset = %d\n", objc_opt_v16->headeropt_ro_offset);
468 DEBUG_PRINTF ("objc_opt->relativeMethodSelectorBaseAddressCacheOffset = %d\n", *relative_selector_offset);
469 }
470 else if (objc_opt->version >= 14)
471 {
472 DEBUG_PRINTF ("objc_opt->version = %u\n", objc_opt_v14->version);
473 DEBUG_PRINTF ("objc_opt->flags = %u\n", objc_opt_v14->flags);
474 DEBUG_PRINTF ("objc_opt->selopt_offset = %d\n", objc_opt_v14->selopt_offset);
475 DEBUG_PRINTF ("objc_opt->headeropt_offset = %d\n", objc_opt_v14->headeropt_offset);
476 DEBUG_PRINTF ("objc_opt->clsopt_offset = %d\n", objc_opt_v14->clsopt_offset);
477 }
478 else
479 {
480 DEBUG_PRINTF ("objc_opt->version = %u\n", objc_opt->version);
481 DEBUG_PRINTF ("objc_opt->selopt_offset = %d\n", objc_opt->selopt_offset);
482 DEBUG_PRINTF ("objc_opt->headeropt_offset = %d\n", objc_opt->headeropt_offset);
483 DEBUG_PRINTF ("objc_opt->clsopt_offset = %d\n", objc_opt->clsopt_offset);
484 }
485
486 if (objc_opt->version == 16)
487 {
488 int32_t large_offset = objc_opt_v16->largeSharedCachesClassOffset;
489 const objc_clsopt_v16_t* clsopt = (const objc_clsopt_v16_t*)((uint8_t *)objc_opt + large_offset);
490 // Work around a bug in some version shared cache builder where the offset overflows 2GiB (rdar://146432183).
491 uint32_t unsigned_offset = (uint32_t)large_offset;
492 if (unsigned_offset > 0x7fffffff && unsigned_offset < 0x82000000) {
493 clsopt = (const objc_clsopt_v16_t*)((uint8_t *)objc_opt + unsigned_offset);
494 DEBUG_PRINTF("warning: applying largeSharedCachesClassOffset overflow workaround!\n");
495 }
496 const size_t max_class_infos = class_infos_byte_size/sizeof(ClassInfo);
497
498 DEBUG_PRINTF("max_class_infos = %llu\n", (uint64_t)max_class_infos);
499
500 ClassInfo *class_infos = (ClassInfo *)class_infos_ptr;
501
502 const uint8_t *checkbytes = &clsopt->tab[clsopt->mask+1];
503 const int32_t *offsets = (const int32_t *)(checkbytes + clsopt->capacity);
504 const objc_classheader_v16_t *classOffsets = (const objc_classheader_v16_t *)(offsets + clsopt->capacity);
505
506 DEBUG_PRINTF ("clsopt->capacity = %u\n", clsopt->capacity);
507 DEBUG_PRINTF ("clsopt->mask = 0x%8.8x\n", clsopt->mask);
508 DEBUG_PRINTF ("classOffsets = %p\n", classOffsets);
509
510 const uint32_t original_start_idx = *start_idx;
511
512 // Always start at the start_idx here. If it's greater than the capacity,
513 // it will skip the loop entirely and go to the duplicate handling below.
514 for (uint32_t i=*start_idx; i<clsopt->capacity; ++i)
515 {
516 const uint64_t objectCacheOffset = classOffsets[i].objectCacheOffset;
517 DEBUG_PRINTF("objectCacheOffset[%u] = %u\n", i, objectCacheOffset);
518
519 if (classOffsets[i].isDuplicate) {
520 DEBUG_PRINTF("isDuplicate = true\n");
521 continue; // duplicate
522 }
523
524 if (objectCacheOffset == 0) {
525 DEBUG_PRINTF("objectCacheOffset == invalidEntryOffset\n");
526 continue; // invalid offset
527 }
528
529 if (class_infos && idx < max_class_infos)
530 {
531 class_infos[idx].isa = (Class)((uint8_t *)shared_cache_base_ptr + objectCacheOffset);
532
533 // Lookup the class name.
534 const char *name = class_name_lookup_func(class_infos[idx].isa);
535 DEBUG_PRINTF("[%u] isa = %8p %s\n", idx, class_infos[idx].isa, name);
536
537 // Hash the class name so we don't have to read it.
538 const char *s = name;
539 uint32_t h = 5381;
540 for (unsigned char c = *s; c; c = *++s)
541 {
542 // class_getName demangles swift names and the hash must
543 // be calculated on the mangled name. hash==0 means lldb
544 // will fetch the mangled name and compute the hash in
545 // ParseClassInfoArray.
546 if (c == '.')
547 {
548 h = 0;
549 break;
550 }
551 h = ((h << 5) + h) + c;
552 }
553 class_infos[idx].hash = h;
554 }
555 else
556 {
557 DEBUG_PRINTF("not(class_infos && idx < max_class_infos)\n");
558 *start_idx = i;
559 break;
560 }
561 ++idx;
562 }
563
564 if (idx < max_class_infos) {
565 const uint32_t *duplicate_count_ptr = (uint32_t *)&classOffsets[clsopt->capacity];
566 const uint32_t duplicate_count = *duplicate_count_ptr;
567 const objc_classheader_v16_t *duplicateClassOffsets = (const objc_classheader_v16_t *)(&duplicate_count_ptr[1]);
568
569 DEBUG_PRINTF ("duplicate_count = %u\n", duplicate_count);
570 DEBUG_PRINTF ("duplicateClassOffsets = %p\n", duplicateClassOffsets);
571
572 const uint32_t duplicate_start_idx =
573 *start_idx < clsopt->capacity ?
574 0 :
575 *start_idx - clsopt->capacity;
576
577 for (uint32_t i=duplicate_start_idx; i<duplicate_count; ++i)
578 {
579 const uint64_t objectCacheOffset = duplicateClassOffsets[i].objectCacheOffset;
580 DEBUG_PRINTF("objectCacheOffset[%u] = %u\n", i, objectCacheOffset);
581
582 if (duplicateClassOffsets[i].isDuplicate) {
583 DEBUG_PRINTF("isDuplicate = true\n");
584 continue; // duplicate
585 }
586
587 if (objectCacheOffset == 0) {
588 DEBUG_PRINTF("objectCacheOffset == invalidEntryOffset\n");
589 continue; // invalid offset
590 }
591
592 if (class_infos && idx < max_class_infos)
593 {
594 class_infos[idx].isa = (Class)((uint8_t *)shared_cache_base_ptr + objectCacheOffset);
595
596 // Lookup the class name.
597 const char *name = class_name_lookup_func(class_infos[idx].isa);
598 DEBUG_PRINTF("[%u] isa = %8p %s\n", idx, class_infos[idx].isa, name);
599
600 // Hash the class name so we don't have to read it.
601 const char *s = name;
602 uint32_t h = 5381;
603 for (unsigned char c = *s; c; c = *++s)
604 {
605 // class_getName demangles swift names and the hash must
606 // be calculated on the mangled name. hash==0 means lldb
607 // will fetch the mangled name and compute the hash in
608 // ParseClassInfoArray.
609 if (c == '.')
610 {
611 h = 0;
612 break;
613 }
614 h = ((h << 5) + h) + c;
615 }
616 class_infos[idx].hash = h;
617 } else {
618 DEBUG_PRINTF("not(class_infos && idx < max_class_infos)\n");
619 *start_idx = i;
620 break;
621 }
622 ++idx;
623 }
624 }
625 // Always make sure start_idx gets updated. Otherwise we have an infinite
626 // loop if there are exactly max_class_infos number of classes.
627 if (*start_idx == original_start_idx) {
628 *start_idx = idx;
629 }
630 }
631 else if (objc_opt->version >= 12 && objc_opt->version <= 15)
632 {
633 const objc_clsopt_t* clsopt = NULL;
634 if (objc_opt->version >= 14)
635 clsopt = (const objc_clsopt_t*)((uint8_t *)objc_opt_v14 + objc_opt_v14->clsopt_offset);
636 else
637 clsopt = (const objc_clsopt_t*)((uint8_t *)objc_opt + objc_opt->clsopt_offset);
638 const size_t max_class_infos = class_infos_byte_size/sizeof(ClassInfo);
639 DEBUG_PRINTF("max_class_infos = %llu\n", (uint64_t)max_class_infos);
640 ClassInfo *class_infos = (ClassInfo *)class_infos_ptr;
641 int32_t invalidEntryOffset = 0;
642 // this is safe to do because the version field order is invariant
643 if (objc_opt->version == 12)
644 invalidEntryOffset = 16;
645 const uint8_t *checkbytes = &clsopt->tab[clsopt->mask+1];
646 const int32_t *offsets = (const int32_t *)(checkbytes + clsopt->capacity);
647 const objc_classheader_t *classOffsets = (const objc_classheader_t *)(offsets + clsopt->capacity);
648 DEBUG_PRINTF ("clsopt->capacity = %u\n", clsopt->capacity);
649 DEBUG_PRINTF ("clsopt->mask = 0x%8.8x\n", clsopt->mask);
650 DEBUG_PRINTF ("classOffsets = %p\n", classOffsets);
651 DEBUG_PRINTF("invalidEntryOffset = %d\n", invalidEntryOffset);
652 for (uint32_t i=0; i<clsopt->capacity; ++i)
653 {
654 const int32_t clsOffset = classOffsets[i].clsOffset;
655 DEBUG_PRINTF("clsOffset[%u] = %u\n", i, clsOffset);
656 if (clsOffset & 1)
657 {
658 DEBUG_PRINTF("clsOffset & 1\n");
659 continue; // duplicate
660 }
661 else if (clsOffset == invalidEntryOffset)
662 {
663 DEBUG_PRINTF("clsOffset == invalidEntryOffset\n");
664 continue; // invalid offset
665 }
666
667 if (class_infos && idx < max_class_infos)
668 {
669 class_infos[idx].isa = (Class)((uint8_t *)clsopt + clsOffset);
670 const char *name = class_name_lookup_func (class_infos[idx].isa);
671 DEBUG_PRINTF ("[%u] isa = %8p %s\n", idx, class_infos[idx].isa, name);
672 // Hash the class name so we don't have to read it
673 const char *s = name;
674 uint32_t h = 5381;
675 for (unsigned char c = *s; c; c = *++s)
676 {
677 // class_getName demangles swift names and the hash must
678 // be calculated on the mangled name. hash==0 means lldb
679 // will fetch the mangled name and compute the hash in
680 // ParseClassInfoArray.
681 if (c == '.')
682 {
683 h = 0;
684 break;
685 }
686 h = ((h << 5) + h) + c;
687 }
688 class_infos[idx].hash = h;
689 }
690 else
691 {
692 DEBUG_PRINTF("not(class_infos && idx < max_class_infos)\n");
693 }
694 ++idx;
695 }
696
697 const uint32_t *duplicate_count_ptr = (uint32_t *)&classOffsets[clsopt->capacity];
698 const uint32_t duplicate_count = *duplicate_count_ptr;
699 const objc_classheader_t *duplicateClassOffsets = (const objc_classheader_t *)(&duplicate_count_ptr[1]);
700 DEBUG_PRINTF ("duplicate_count = %u\n", duplicate_count);
701 DEBUG_PRINTF ("duplicateClassOffsets = %p\n", duplicateClassOffsets);
702 for (uint32_t i=0; i<duplicate_count; ++i)
703 {
704 const int32_t clsOffset = duplicateClassOffsets[i].clsOffset;
705 if (clsOffset & 1)
706 continue; // duplicate
707 else if (clsOffset == invalidEntryOffset)
708 continue; // invalid offset
709
710 if (class_infos && idx < max_class_infos)
711 {
712 class_infos[idx].isa = (Class)((uint8_t *)clsopt + clsOffset);
713 const char *name = class_name_lookup_func (class_infos[idx].isa);
714 DEBUG_PRINTF ("[%u] isa = %8p %s\n", idx, class_infos[idx].isa, name);
715 // Hash the class name so we don't have to read it
716 const char *s = name;
717 uint32_t h = 5381;
718 for (unsigned char c = *s; c; c = *++s)
719 {
720 // class_getName demangles swift names and the hash must
721 // be calculated on the mangled name. hash==0 means lldb
722 // will fetch the mangled name and compute the hash in
723 // ParseClassInfoArray.
724 if (c == '.')
725 {
726 h = 0;
727 break;
728 }
729 h = ((h << 5) + h) + c;
730 }
731 class_infos[idx].hash = h;
732 }
733 ++idx;
734 }
735 }
736 DEBUG_PRINTF ("%u class_infos\n", idx);
737 DEBUG_PRINTF ("done\n");
738 }
739 return idx;
740}
741
742
743)";
744
745static uint64_t
747 const ModuleSP &module_sp, Status &error,
748 bool read_value = true, uint8_t byte_size = 0,
749 uint64_t default_value = LLDB_INVALID_ADDRESS,
751 if (!process) {
752 error = Status::FromErrorString("no process");
753 return default_value;
754 }
755
756 if (!module_sp) {
757 error = Status::FromErrorString("no module");
758 return default_value;
759 }
760
761 if (!byte_size)
762 byte_size = process->GetAddressByteSize();
763 const Symbol *symbol =
764 module_sp->FindFirstSymbolWithNameAndType(name, lldb::eSymbolTypeData);
765
766 if (!symbol || !symbol->ValueIsAddress()) {
767 error = Status::FromErrorString("no symbol");
768 return default_value;
769 }
770
771 lldb::addr_t symbol_load_addr =
772 symbol->GetAddressRef().GetLoadAddress(&process->GetTarget());
773 if (symbol_load_addr == LLDB_INVALID_ADDRESS) {
774 error = Status::FromErrorString("symbol address invalid");
775 return default_value;
776 }
777
778 if (read_value)
779 return process->ReadUnsignedIntegerFromMemory(symbol_load_addr, byte_size,
780 default_value, error);
781 return symbol_load_addr;
782}
783
784/// Batched version of ExtractRuntimeGlobalSymbol. Resolves symbols and reads
785/// their values in a single batch using ReadUnsignedIntegersFromMemory.
786static llvm::SmallVector<RuntimeGlobalSymbolResult>
788 Process *process, const ModuleSP &module_sp,
789 llvm::ArrayRef<RuntimeGlobalSymbolSpec> specs) {
790
791 // Start out with all results in a failed state.
792 llvm::SmallVector<RuntimeGlobalSymbolResult> results(specs.size());
793
794 if (!process || !module_sp)
795 return results;
796
797 const uint8_t ptr_size = process->GetAddressByteSize();
798
799 // Phase 1: Resolve all symbols to addresses. Build a work list of entries
800 // that need their values read in Phase 2.
801 struct ReadEntry {
802 size_t result_idx;
803 lldb::addr_t addr;
804 uint8_t byte_size;
805 };
806 llvm::SmallVector<ReadEntry> work_list;
807 for (auto [i, spec] : llvm::enumerate(specs)) {
808 const uint8_t size = spec.byte_size ? spec.byte_size : ptr_size;
809 const Symbol *symbol = module_sp->FindFirstSymbolWithNameAndType(
810 spec.name, lldb::eSymbolTypeData);
811
812 if (!symbol || !symbol->ValueIsAddress())
813 continue;
814
815 lldb::addr_t symbol_load_addr =
816 symbol->GetAddressRef().GetLoadAddress(&process->GetTarget());
817 if (symbol_load_addr == LLDB_INVALID_ADDRESS)
818 continue;
819
820 if (!spec.read_value)
821 results[i] = {symbol_load_addr, true};
822 else
823 work_list.push_back({i, symbol_load_addr, size});
824 }
825
826 // Phase 2: Batch read values, grouping consecutive entries with the same
827 // byte size into a single ReadUnsignedIntegersFromMemory call.
828 llvm::stable_sort(work_list, [](const ReadEntry &a, const ReadEntry &b) {
829 return a.byte_size < b.byte_size;
830 });
831
832 for (size_t i = 0; i < work_list.size();) {
833 const uint8_t byte_size = work_list[i].byte_size;
834 const size_t group_start = i;
835
836 llvm::SmallVector<lldb::addr_t> addrs;
837 while (i < work_list.size() && work_list[i].byte_size == byte_size)
838 addrs.push_back(work_list[i++].addr);
839
840 auto read_values =
841 process->ReadUnsignedIntegersFromMemory(addrs, byte_size);
842
843 for (size_t j = 0; j < addrs.size(); ++j) {
844 size_t idx = work_list[group_start + j].result_idx;
845 if (read_values[j].has_value())
846 results[idx] = {*read_values[j], true};
847 }
848 }
849
850 return results;
851}
852
853static void RegisterObjCExceptionRecognizer(Process *process);
854
856 const ModuleSP &objc_module_sp)
857 : AppleObjCRuntime(process), m_objc_module_sp(objc_module_sp),
867 TaggedPointerVendorV2::CreateInstance(*this, objc_module_sp)),
870 static const ConstString g_gdb_object_getClass("gdb_object_getClass");
871 m_has_object_getClass = HasSymbol(g_gdb_object_getClass);
872 static const ConstString g_objc_copyRealizedClassList(
873 "_ZL33objc_copyRealizedClassList_nolockPj");
874 static const ConstString g_objc_getRealizedClassList_trylock(
875 "_objc_getRealizedClassList_trylock");
876 m_has_objc_copyRealizedClassList = HasSymbol(g_objc_copyRealizedClassList);
878 HasSymbol(g_objc_getRealizedClassList_trylock);
881}
882
885 if (auto process_sp = in_value.GetProcessSP()) {
886 assert(process_sp.get() == m_process);
887 if (auto descriptor_sp = GetNonKVOClassDescriptor(in_value)) {
888 LanguageType impl_lang = descriptor_sp->GetImplementationLanguage();
889 if (impl_lang != eLanguageTypeUnknown)
890 return process_sp->GetLanguageRuntime(impl_lang);
891 }
892 }
893 return nullptr;
894}
895
897 ValueObject &in_value, lldb::DynamicValueType use_dynamic,
898 TypeAndOrName &class_type_or_name, Address &address,
899 Value::ValueType &value_type, llvm::ArrayRef<uint8_t> &local_buffer) {
900 // We should never get here with a null process...
901 assert(m_process != nullptr);
902
903 // The Runtime is attached to a particular process, you shouldn't pass in a
904 // value from another process. Note, however, the process might be NULL (e.g.
905 // if the value was made with SBTarget::EvaluateExpression...) in which case
906 // it is sufficient if the target's match:
907
908 Process *process = in_value.GetProcessSP().get();
909 if (process)
910 assert(process == m_process);
911 else
912 assert(in_value.GetTargetSP().get() == m_process->CalculateTarget().get());
913
914 class_type_or_name.Clear();
915 value_type = Value::ValueType::Scalar;
916
917 // Make sure we can have a dynamic value before starting...
918 if (CouldHaveDynamicValue(in_value)) {
919 // First job, pull out the address at 0 offset from the object That will
920 // be the ISA pointer.
921 ClassDescriptorSP objc_class_sp(GetNonKVOClassDescriptor(in_value));
922 if (objc_class_sp) {
923 const addr_t object_ptr = in_value.GetPointerValue().address;
924 address.SetRawAddress(object_ptr);
925
926 ConstString class_name(objc_class_sp->GetClassName());
927 class_type_or_name.SetName(class_name);
928 TypeSP type_sp(objc_class_sp->GetType());
929 if (type_sp)
930 class_type_or_name.SetTypeSP(type_sp);
931 else {
932 type_sp = LookupInCompleteClassCache(class_name);
933 if (type_sp) {
934 objc_class_sp->SetType(type_sp);
935 class_type_or_name.SetTypeSP(type_sp);
936 } else {
937 // try to go for a CompilerType at least
938 if (auto *vendor = GetDeclVendor()) {
939 auto types = vendor->FindTypes(class_name, /*max_matches*/ 1);
940 if (!types.empty())
941 class_type_or_name.SetCompilerType(types.front());
942 }
943 }
944 }
945 }
946 }
947 return !class_type_or_name.IsEmpty();
948}
949
950// Static Functions
952 LanguageType language) {
953 // FIXME: This should be a MacOS or iOS process, and we need to look for the
954 // OBJC section to make
955 // sure we aren't using the V1 runtime.
956 if (language == eLanguageTypeObjC) {
957 ModuleSP objc_module_sp;
958
959 if (AppleObjCRuntime::GetObjCVersion(process, objc_module_sp) ==
961 return new AppleObjCRuntimeV2(process, objc_module_sp);
962 return nullptr;
963 }
964 return nullptr;
965}
966
969 false,
970 "verbose",
971 'v',
973 nullptr,
974 {},
975 0,
977 "Print ivar and method information in detail"}};
978
980public:
981 class CommandOptions : public Options {
982 public:
983 CommandOptions() : Options(), m_verbose(false, false) {}
984
985 ~CommandOptions() override = default;
986
987 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
988 ExecutionContext *execution_context) override {
990 const int short_option = m_getopt_table[option_idx].val;
991 switch (short_option) {
992 case 'v':
993 m_verbose.SetCurrentValue(true);
994 m_verbose.SetOptionWasSet();
995 break;
996
997 default:
999 "unrecognized short option '%c'", short_option);
1000 break;
1001 }
1002
1003 return error;
1004 }
1005
1006 void OptionParsingStarting(ExecutionContext *execution_context) override {
1007 m_verbose.Clear();
1008 }
1009
1010 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1011 return llvm::ArrayRef(g_objc_classtable_dump_options);
1012 }
1013
1015 };
1016
1018 : CommandObjectParsed(interpreter, "dump",
1019 "Dump information on Objective-C classes "
1020 "known to the current process.",
1021 "language objc class-table dump",
1022 eCommandRequiresProcess |
1023 eCommandProcessMustBeLaunched |
1024 eCommandProcessMustBePaused),
1025 m_options() {
1027 }
1028
1030
1031 Options *GetOptions() override { return &m_options; }
1032
1033protected:
1034 void DoExecute(Args &command, CommandReturnObject &result) override {
1035 std::unique_ptr<RegularExpression> regex_up;
1036 switch (command.GetArgumentCount()) {
1037 case 0:
1038 break;
1039 case 1: {
1040 regex_up =
1041 std::make_unique<RegularExpression>(command.GetArgumentAtIndex(0));
1042 if (!regex_up->IsValid()) {
1043 result.AppendError(
1044 "invalid argument - please provide a valid regular expression");
1046 return;
1047 }
1048 break;
1049 }
1050 default: {
1051 result.AppendError("please provide 0 or 1 arguments");
1053 return;
1054 }
1055 }
1056
1057 Process *process = m_exe_ctx.GetProcessPtr();
1058 ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*process);
1059 if (objc_runtime) {
1060 auto iterators_pair = objc_runtime->GetDescriptorIteratorPair();
1061 auto iterator = iterators_pair.first;
1062 auto &std_out = result.GetOutputStream();
1063 for (; iterator != iterators_pair.second; iterator++) {
1064 if (iterator->second) {
1065 const char *class_name =
1066 iterator->second->GetClassName().AsCString("<unknown>");
1067 if (regex_up && class_name &&
1068 !regex_up->Execute(llvm::StringRef(class_name)))
1069 continue;
1070 std_out.Printf("isa = 0x%" PRIx64, iterator->first);
1071 std_out.Printf(" name = %s", class_name);
1072 std_out.Printf(" instance size = %" PRIu64,
1073 iterator->second->GetInstanceSize());
1074 std_out.Printf(" num ivars = %" PRIuPTR,
1075 (uintptr_t)iterator->second->GetNumIVars());
1076 if (auto superclass = iterator->second->GetSuperclass()) {
1077 std_out.Printf(" superclass = %s",
1078 superclass->GetClassName().AsCString("<unknown>"));
1079 }
1080 std_out.Printf("\n");
1081 if (m_options.m_verbose) {
1082 for (size_t i = 0; i < iterator->second->GetNumIVars(); i++) {
1083 auto ivar = iterator->second->GetIVarAtIndex(i);
1084 std_out.Printf(
1085 " ivar name = %s type = %s size = %" PRIu64
1086 " offset = %" PRId32 "\n",
1087 ivar.m_name.AsCString("<unknown>"),
1088 ivar.m_type.GetDisplayTypeName().AsCString("<unknown>"),
1089 ivar.m_size, ivar.m_offset);
1090 }
1091
1092 iterator->second->Describe(
1093 nullptr,
1094 [&std_out](const char *name, const char *type) -> bool {
1095 std_out.Printf(" instance method name = %s type = %s\n",
1096 name, type);
1097 return false;
1098 },
1099 [&std_out](const char *name, const char *type) -> bool {
1100 std_out.Printf(" class method name = %s type = %s\n", name,
1101 type);
1102 return false;
1103 },
1104 nullptr);
1105 }
1106 } else {
1107 if (regex_up && !regex_up->Execute(llvm::StringRef()))
1108 continue;
1109 std_out.Printf("isa = 0x%" PRIx64 " has no associated class.\n",
1110 iterator->first);
1111 }
1112 }
1114 return;
1115 }
1116 result.AppendError("current process has no Objective-C runtime loaded");
1118 }
1119
1121};
1122
1124 : public CommandObjectParsed {
1125public:
1128 interpreter, "info", "Dump information on a tagged pointer.",
1129 "language objc tagged-pointer info",
1130 eCommandRequiresProcess | eCommandProcessMustBeLaunched |
1131 eCommandProcessMustBePaused) {
1133 }
1134
1136
1137protected:
1138 void DoExecute(Args &command, CommandReturnObject &result) override {
1139 if (command.GetArgumentCount() == 0) {
1140 result.AppendError("this command requires arguments");
1142 return;
1143 }
1144
1145 Process *process = m_exe_ctx.GetProcessPtr();
1146 ExecutionContext exe_ctx(process);
1147
1148 ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*process);
1149 if (!objc_runtime) {
1150 result.AppendError("current process has no Objective-C runtime loaded");
1152 return;
1153 }
1154
1155 ObjCLanguageRuntime::TaggedPointerVendor *tagged_ptr_vendor =
1156 objc_runtime->GetTaggedPointerVendor();
1157 if (!tagged_ptr_vendor) {
1158 result.AppendError("current process has no tagged pointer support");
1160 return;
1161 }
1162
1163 for (size_t i = 0; i < command.GetArgumentCount(); i++) {
1164 const char *arg_str = command.GetArgumentAtIndex(i);
1165 if (!arg_str)
1166 continue;
1167
1168 Status error;
1170 &exe_ctx, arg_str, LLDB_INVALID_ADDRESS, &error);
1171 if (arg_addr == 0 || arg_addr == LLDB_INVALID_ADDRESS || error.Fail()) {
1173 "could not convert '{0}' to a valid address\n", arg_str);
1175 return;
1176 }
1177
1178 if (!tagged_ptr_vendor->IsPossibleTaggedPointer(arg_addr)) {
1179 result.GetOutputStream().Format("{0:x16} is not tagged\n", arg_addr);
1180 continue;
1181 }
1182
1183 auto descriptor_sp = tagged_ptr_vendor->GetClassDescriptor(arg_addr);
1184 if (!descriptor_sp) {
1186 "could not get class descriptor for {0:x16}\n", arg_addr);
1188 return;
1189 }
1190
1191 uint64_t info_bits = 0;
1192 uint64_t value_bits = 0;
1193 uint64_t payload = 0;
1194 if (descriptor_sp->GetTaggedPointerInfo(&info_bits, &value_bits,
1195 &payload)) {
1196 result.GetOutputStream().Format(
1197 "{0:x} is tagged\n"
1198 "\tpayload = {1:x16}\n"
1199 "\tvalue = {2:x16}\n"
1200 "\tinfo bits = {3:x16}\n"
1201 "\tclass = {4}\n",
1202 arg_addr, payload, value_bits, info_bits,
1203 descriptor_sp->GetClassName().AsCString("<unknown>"));
1204 } else {
1205 result.GetOutputStream().Format("{0:x16} is not tagged\n", arg_addr);
1206 }
1207 }
1208
1210 }
1211};
1212
1214public:
1217 interpreter, "class-table",
1218 "Commands for operating on the Objective-C class table.",
1219 "class-table <subcommand> [<subcommand-options>]") {
1221 "dump",
1223 }
1224
1226};
1227
1229public:
1232 interpreter, "tagged-pointer",
1233 "Commands for operating on Objective-C tagged pointers.",
1234 "tagged-pointer <subcommand> [<subcommand-options>]") {
1236 "info",
1239 }
1240
1242};
1243
1245public:
1248 interpreter, "objc",
1249 "Commands for operating on the Objective-C language runtime.",
1250 "objc <subcommand> [<subcommand-options>]") {
1251 LoadSubCommand("class-table",
1253 new CommandObjectMultiwordObjC_ClassTable(interpreter)));
1254 LoadSubCommand("tagged-pointer",
1256 interpreter)));
1257 }
1258
1259 ~CommandObjectMultiwordObjC() override = default;
1260};
1261
1264 GetPluginNameStatic(), "Apple Objective-C Language Runtime - Version 2",
1266 [](CommandInterpreter &interpreter) -> lldb::CommandObjectSP {
1267 return CommandObjectSP(new CommandObjectMultiwordObjC(interpreter));
1268 },
1270}
1271
1275
1278 bool catch_bp, bool throw_bp) {
1279 BreakpointResolverSP resolver_sp;
1280
1281 if (throw_bp)
1282 resolver_sp = std::make_shared<BreakpointResolverName>(
1283 bkpt, std::get<1>(GetExceptionThrowLocation()).AsCString(nullptr),
1284 eFunctionNameTypeBase, eLanguageTypeUnknown, Breakpoint::Exact, 0,
1285 /*offset_is_insn_count = */ false, eLazyBoolNo);
1286 // FIXME: We don't do catch breakpoints for ObjC yet.
1287 // Should there be some way for the runtime to specify what it can do in this
1288 // regard?
1289 return resolver_sp;
1290}
1291
1292llvm::Expected<std::unique_ptr<UtilityFunction>>
1294 ExecutionContext &exe_ctx) {
1295 char check_function_code[2048];
1296
1297 int len = 0;
1299 len = ::snprintf(check_function_code, sizeof(check_function_code), R"(
1300 extern "C" void *gdb_object_getClass(void *);
1301 extern "C" int printf(const char *format, ...);
1302 extern "C" void
1303 %s(void *$__lldb_arg_obj, void *$__lldb_arg_selector) {
1304 if ($__lldb_arg_obj == (void *)0)
1305 return; // nil is ok
1306 if (!gdb_object_getClass($__lldb_arg_obj)) {
1307 *((volatile int *)0) = 'ocgc';
1308 } else if ($__lldb_arg_selector != (void *)0) {
1309 signed char $responds = (signed char)
1310 [(id)$__lldb_arg_obj respondsToSelector:
1311 (void *) $__lldb_arg_selector];
1312 if ($responds == (signed char) 0)
1313 *((volatile int *)0) = 'ocgc';
1314 }
1315 })",
1316 name.c_str());
1317 } else {
1318 len = ::snprintf(check_function_code, sizeof(check_function_code), R"(
1319 extern "C" void *gdb_class_getClass(void *);
1320 extern "C" int printf(const char *format, ...);
1321 extern "C" void
1322 %s(void *$__lldb_arg_obj, void *$__lldb_arg_selector) {
1323 if ($__lldb_arg_obj == (void *)0)
1324 return; // nil is ok
1325 void **$isa_ptr = (void **)$__lldb_arg_obj;
1326 if (*$isa_ptr == (void *)0 ||
1327 !gdb_class_getClass(*$isa_ptr))
1328 *((volatile int *)0) = 'ocgc';
1329 else if ($__lldb_arg_selector != (void *)0) {
1330 signed char $responds = (signed char)
1331 [(id)$__lldb_arg_obj respondsToSelector:
1332 (void *) $__lldb_arg_selector];
1333 if ($responds == (signed char) 0)
1334 *((volatile int *)0) = 'ocgc';
1335 }
1336 })",
1337 name.c_str());
1338 }
1339
1340 assert(len < (int)sizeof(check_function_code));
1342
1343 return GetTargetRef().CreateUtilityFunction(check_function_code, name,
1344 eLanguageTypeC, exe_ctx);
1345}
1346
1348 const char *ivar_name) {
1349 uint32_t ivar_offset = LLDB_INVALID_IVAR_OFFSET;
1350
1351 ConstString class_name = parent_ast_type.GetTypeName();
1352 if (!class_name.IsEmpty() && ivar_name && ivar_name[0]) {
1353 // Make the objective C V2 mangled name for the ivar offset from the class
1354 // name and ivar name
1355 std::string buffer("OBJC_IVAR_$_");
1356 buffer.append(class_name.GetStringRef());
1357 buffer.push_back('.');
1358 buffer.append(ivar_name);
1359 ConstString ivar_const_str(buffer);
1360
1361 // Try to get the ivar offset address from the symbol table first using the
1362 // name we created above
1363 SymbolContextList sc_list;
1364 Target &target = m_process->GetTarget();
1365 target.GetImages().FindSymbolsWithNameAndType(ivar_const_str,
1366 eSymbolTypeObjCIVar, sc_list);
1368 addr_t ivar_offset_address = LLDB_INVALID_ADDRESS;
1370 Status error;
1371 SymbolContext ivar_offset_symbol;
1372 if (sc_list.GetSize() == 1 &&
1373 sc_list.GetContextAtIndex(0, ivar_offset_symbol)) {
1374 if (ivar_offset_symbol.symbol)
1375 ivar_offset_address =
1376 ivar_offset_symbol.symbol->GetLoadAddress(&target);
1377 }
1378
1379 // If we didn't get the ivar offset address from the symbol table, fall
1380 // back to getting it from the runtime
1381 if (ivar_offset_address == LLDB_INVALID_ADDRESS)
1382 ivar_offset_address = LookupRuntimeSymbol(ivar_const_str);
1383
1384 if (ivar_offset_address != LLDB_INVALID_ADDRESS)
1385 ivar_offset = m_process->ReadUnsignedIntegerFromMemory(
1386 ivar_offset_address, 4, LLDB_INVALID_IVAR_OFFSET, error);
1387 }
1388 return ivar_offset;
1389}
1390
1391// tagged pointers are special not-a-real-pointer values that contain both type
1392// and value information this routine attempts to check with as little
1393// computational effort as possible whether something could possibly be a
1394// tagged pointer - false positives are possible but false negatives shouldn't
1397 return false;
1398 return m_tagged_pointer_vendor_up->IsPossibleTaggedPointer(ptr);
1399}
1400
1401class RemoteNXMapTable {
1402public:
1403 RemoteNXMapTable() : m_end_iterator(*this, -1) {}
1404
1405 void Dump() {
1406 printf("RemoteNXMapTable.m_load_addr = 0x%" PRIx64 "\n", m_load_addr);
1407 printf("RemoteNXMapTable.m_count = %u\n", m_count);
1408 printf("RemoteNXMapTable.m_num_buckets_minus_one = %u\n",
1409 m_num_buckets_minus_one);
1410 printf("RemoteNXMapTable.m_buckets_ptr = 0x%" PRIX64 "\n", m_buckets_ptr);
1411 }
1412
1413 bool ParseHeader(Process *process, lldb::addr_t load_addr) {
1414 m_process = process;
1415 m_load_addr = load_addr;
1416 m_map_pair_size = m_process->GetAddressByteSize() * 2;
1417 m_invalid_key =
1418 m_process->GetAddressByteSize() == 8 ? UINT64_MAX : UINT32_MAX;
1419 Status err;
1420
1421 // This currently holds true for all platforms we support, but we might
1422 // need to change this to use get the actually byte size of "unsigned" from
1423 // the target AST...
1424 const uint32_t unsigned_byte_size = sizeof(uint32_t);
1425 // Skip the prototype as we don't need it (const struct
1426 // +NXMapTablePrototype *prototype)
1427
1428 bool success = true;
1429 if (load_addr == LLDB_INVALID_ADDRESS)
1430 success = false;
1431 else {
1432 lldb::addr_t cursor = load_addr + m_process->GetAddressByteSize();
1434 // unsigned count;
1435 m_count = m_process->ReadUnsignedIntegerFromMemory(
1436 cursor, unsigned_byte_size, 0, err);
1437 if (m_count) {
1438 cursor += unsigned_byte_size;
1439
1440 // unsigned nbBucketsMinusOne;
1441 m_num_buckets_minus_one = m_process->ReadUnsignedIntegerFromMemory(
1442 cursor, unsigned_byte_size, 0, err);
1443 cursor += unsigned_byte_size;
1444
1445 // void *buckets;
1446 std::optional<lldb::addr_t> buckets_ptr =
1447 llvm::expectedToOptional(m_process->ReadPointerFromMemory(cursor));
1448 if (buckets_ptr)
1449 m_buckets_ptr = *buckets_ptr;
1450
1451 success = m_count > 0 && buckets_ptr.has_value();
1452 }
1454
1455 if (!success) {
1456 m_count = 0;
1459 }
1460 return success;
1461 }
1463 // const_iterator mimics NXMapState and its code comes from NXInitMapState
1464 // and NXNextMapState.
1465 typedef std::pair<ConstString, ObjCLanguageRuntime::ObjCISA> element;
1467 friend class const_iterator;
1468 class const_iterator {
1469 public:
1470 const_iterator(RemoteNXMapTable &parent, int index)
1471 : m_parent(parent), m_index(index) {
1473 }
1474
1475 const_iterator(const const_iterator &rhs)
1476 : m_parent(rhs.m_parent), m_index(rhs.m_index) {
1477 // AdvanceToValidIndex() has been called by rhs already.
1478 }
1479
1480 const_iterator &operator=(const const_iterator &rhs) {
1481 // AdvanceToValidIndex() has been called by rhs already.
1482 assert(&m_parent == &rhs.m_parent);
1483 m_index = rhs.m_index;
1484 return *this;
1485 }
1486
1487 bool operator==(const const_iterator &rhs) const {
1488 if (&m_parent != &rhs.m_parent)
1489 return false;
1490 if (m_index != rhs.m_index)
1491 return false;
1492
1493 return true;
1494 }
1495
1496 bool operator!=(const const_iterator &rhs) const {
1497 return !(operator==(rhs));
1498 }
1499
1500 const_iterator &operator++() {
1501 AdvanceToValidIndex();
1502 return *this;
1503 }
1504
1505 element operator*() const {
1506 if (m_index == -1) {
1507 // TODO find a way to make this an error, but not an assert
1508 return element();
1509 }
1510
1511 lldb::addr_t pairs_ptr = m_parent.m_buckets_ptr;
1512 size_t map_pair_size = m_parent.m_map_pair_size;
1513 lldb::addr_t pair_ptr = pairs_ptr + (m_index * map_pair_size);
1514
1515 llvm::Expected<lldb::addr_t> key =
1516 m_parent.m_process->ReadPointerFromMemory(pair_ptr);
1517 if (!key) {
1518 llvm::consumeError(key.takeError());
1519 return element();
1520 }
1521 llvm::Expected<lldb::addr_t> value =
1522 m_parent.m_process->ReadPointerFromMemory(
1523 pair_ptr + m_parent.m_process->GetAddressByteSize());
1524 if (!value) {
1525 llvm::consumeError(value.takeError());
1526 return element();
1527 }
1528
1529 std::string key_string;
1532 m_parent.m_process->ReadCStringFromMemory(*key, key_string, err);
1533 if (!err.Success())
1534 return element();
1535
1536 return element(ConstString(key_string),
1539
1540 private:
1541 void AdvanceToValidIndex() {
1542 if (m_index == -1)
1543 return;
1545 const lldb::addr_t pairs_ptr = m_parent.m_buckets_ptr;
1546 const size_t map_pair_size = m_parent.m_map_pair_size;
1547 const lldb::addr_t invalid_key = m_parent.m_invalid_key;
1548
1549 while (m_index--) {
1550 lldb::addr_t pair_ptr = pairs_ptr + (m_index * map_pair_size);
1551 llvm::Expected<lldb::addr_t> key =
1552 m_parent.m_process->ReadPointerFromMemory(pair_ptr);
1554 if (!key) {
1555 llvm::consumeError(key.takeError());
1556 m_index = -1;
1557 return;
1558 }
1559
1560 if (*key != invalid_key)
1561 return;
1563 }
1564 RemoteNXMapTable &m_parent;
1565 int m_index;
1566 };
1567
1568 const_iterator begin() {
1569 return const_iterator(*this, m_num_buckets_minus_one + 1);
1570 }
1571
1572 const_iterator end() { return m_end_iterator; }
1573
1574 uint32_t GetCount() const { return m_count; }
1575
1576 uint32_t GetBucketCount() const { return m_num_buckets_minus_one; }
1577
1578 lldb::addr_t GetBucketDataPointer() const { return m_buckets_ptr; }
1579
1580 lldb::addr_t GetTableLoadAddress() const { return m_load_addr; }
1581
1582private:
1583 // contents of _NXMapTable struct
1584 uint32_t m_count = 0;
1585 uint32_t m_num_buckets_minus_one = 0;
1586 lldb::addr_t m_buckets_ptr = LLDB_INVALID_ADDRESS;
1587 lldb_private::Process *m_process = nullptr;
1588 const_iterator m_end_iterator;
1590 size_t m_map_pair_size = 0;
1591 lldb::addr_t m_invalid_key = 0;
1592};
1593
1595
1597 const RemoteNXMapTable &hash_table) {
1598 m_count = hash_table.GetCount();
1600 m_buckets_ptr = hash_table.GetBucketDataPointer();
1601}
1602
1604 Process *process, AppleObjCRuntimeV2 *runtime,
1605 RemoteNXMapTable &hash_table) {
1606 if (!hash_table.ParseHeader(process, runtime->GetISAHashTablePointer())) {
1607 return false; // Failed to parse the header, no need to update anything
1608 }
1609
1610 // Check with out current signature and return true if the count, number of
1611 // buckets or the hash table address changes.
1612 if (m_count == hash_table.GetCount() &&
1613 m_num_buckets == hash_table.GetBucketCount() &&
1614 m_buckets_ptr == hash_table.GetBucketDataPointer()) {
1615 // Hash table hasn't changed
1616 return false;
1617 }
1618 // Hash table data has changed, we need to update
1619 return true;
1620}
1621
1624 ObjCLanguageRuntime::ClassDescriptorSP class_descriptor_sp;
1625 if (auto *non_pointer_isa_cache = GetNonPointerIsaCache())
1626 class_descriptor_sp = non_pointer_isa_cache->GetClassDescriptor(isa);
1627 if (!class_descriptor_sp)
1628 class_descriptor_sp = ObjCLanguageRuntime::GetClassDescriptorFromISA(isa);
1629 return class_descriptor_sp;
1630}
1631
1634 ValueObjectSet seen;
1635 return GetClassDescriptorImpl(valobj, seen);
1636}
1637
1640 ValueObjectSet &seen) {
1641 seen.insert(&valobj);
1642
1643 ClassDescriptorSP objc_class_sp;
1644 if (valobj.IsBaseClass()) {
1645 ValueObject *parent = valobj.GetParent();
1646 // Fail if there's a cycle in our parent chain.
1647 if (!parent || seen.count(parent))
1648 return nullptr;
1649 if (ClassDescriptorSP parent_descriptor_sp =
1650 GetClassDescriptorImpl(*parent, seen))
1651 return parent_descriptor_sp->GetSuperclass();
1652 return nullptr;
1653 }
1654 // if we get an invalid VO (which might still happen when playing around with
1655 // pointers returned by the expression parser, don't consider this a valid
1656 // ObjC object)
1657 if (!valobj.GetCompilerType().IsValid())
1658 return objc_class_sp;
1659 addr_t isa_pointer = valobj.GetPointerValue().address;
1660 if (isa_pointer == LLDB_INVALID_ADDRESS)
1661 return objc_class_sp;
1662
1663 // tagged pointer
1664 if (IsTaggedPointer(isa_pointer))
1665 return m_tagged_pointer_vendor_up->GetClassDescriptor(isa_pointer);
1666 ExecutionContext exe_ctx(valobj.GetExecutionContextRef());
1667
1668 Process *process = exe_ctx.GetProcessPtr();
1669 if (!process)
1670 return objc_class_sp;
1671
1672 llvm::Expected<lldb::addr_t> isa_or_err =
1673 process->ReadPointerFromMemory(isa_pointer);
1674 if (!isa_or_err) {
1675 llvm::consumeError(isa_or_err.takeError());
1676 return objc_class_sp;
1677 }
1678 ObjCISA isa = *isa_or_err;
1679
1680 objc_class_sp = GetClassDescriptorFromISA(isa);
1681 if (!objc_class_sp) {
1682 if (ABISP abi_sp = process->GetABI())
1683 isa = abi_sp->FixCodeAddress(isa);
1684 objc_class_sp = GetClassDescriptorFromISA(isa);
1685 }
1686
1687 if (isa && !objc_class_sp) {
1689 LLDB_LOGF(log,
1690 "0x%" PRIx64 ": AppleObjCRuntimeV2::GetClassDescriptor() ISA was "
1691 "not in class descriptor cache 0x%" PRIx64,
1692 isa_pointer, isa);
1693 }
1694 return objc_class_sp;
1695}
1700
1701 Process *process = GetProcess();
1702 ModuleSP objc_module_sp(GetObjCModule());
1703
1704 if (!objc_module_sp)
1705 return LLDB_INVALID_ADDRESS;
1706
1707 static ConstString g_gdb_objc_obfuscator(
1708 "objc_debug_taggedpointer_obfuscator");
1709
1710 const Symbol *symbol = objc_module_sp->FindFirstSymbolWithNameAndType(
1711 g_gdb_objc_obfuscator, lldb::eSymbolTypeAny);
1712 if (symbol) {
1713 lldb::addr_t g_gdb_obj_obfuscator_ptr =
1714 symbol->GetLoadAddress(&process->GetTarget());
1715
1716 if (g_gdb_obj_obfuscator_ptr != LLDB_INVALID_ADDRESS)
1718 llvm::expectedToOptional(
1719 process->ReadPointerFromMemory(g_gdb_obj_obfuscator_ptr))
1720 .value_or(LLDB_INVALID_ADDRESS);
1721 }
1722 // If we don't have a correct value at this point, there must be no
1723 // obfuscation.
1726
1728}
1729
1732 Process *process = GetProcess();
1733
1734 ModuleSP objc_module_sp(GetObjCModule());
1735
1736 if (!objc_module_sp)
1737 return LLDB_INVALID_ADDRESS;
1738
1739 static ConstString g_gdb_objc_realized_classes("gdb_objc_realized_classes");
1740
1741 const Symbol *symbol = objc_module_sp->FindFirstSymbolWithNameAndType(
1742 g_gdb_objc_realized_classes, lldb::eSymbolTypeAny);
1743 if (symbol) {
1744 lldb::addr_t gdb_objc_realized_classes_ptr =
1745 symbol->GetLoadAddress(&process->GetTarget());
1746
1747 if (gdb_objc_realized_classes_ptr != LLDB_INVALID_ADDRESS)
1749 llvm::expectedToOptional(
1750 process->ReadPointerFromMemory(gdb_objc_realized_classes_ptr))
1751 .value_or(LLDB_INVALID_ADDRESS);
1752 }
1753 }
1754 return m_isa_hash_table_ptr;
1755}
1756
1757std::unique_ptr<AppleObjCRuntimeV2::SharedCacheImageHeaders>
1759 AppleObjCRuntimeV2 &runtime) {
1761 Process *process = runtime.GetProcess();
1762 ModuleSP objc_module_sp(runtime.GetObjCModule());
1763 if (!objc_module_sp || !process)
1764 return nullptr;
1765
1766 const Symbol *symbol = objc_module_sp->FindFirstSymbolWithNameAndType(
1767 ConstString("objc_debug_headerInfoRWs"), lldb::eSymbolTypeAny);
1768 if (!symbol) {
1769 LLDB_LOG(log, "Symbol 'objc_debug_headerInfoRWs' unavailable. Some "
1770 "information concerning the shared cache may be unavailable");
1771 return nullptr;
1772 }
1773
1774 lldb::addr_t objc_debug_headerInfoRWs_addr =
1775 symbol->GetLoadAddress(&process->GetTarget());
1776 if (objc_debug_headerInfoRWs_addr == LLDB_INVALID_ADDRESS) {
1777 LLDB_LOG(log, "Symbol 'objc_debug_headerInfoRWs' was found but we were "
1778 "unable to get its load address");
1779 return nullptr;
1780 }
1781
1782 llvm::Expected<lldb::addr_t> objc_debug_headerInfoRWs_ptr_or_err =
1783 process->ReadPointerFromMemory(objc_debug_headerInfoRWs_addr);
1784 if (!objc_debug_headerInfoRWs_ptr_or_err) {
1785 llvm::consumeError(objc_debug_headerInfoRWs_ptr_or_err.takeError());
1786 LLDB_LOG(log,
1787 "Failed to read address of 'objc_debug_headerInfoRWs' at {0:x}",
1788 objc_debug_headerInfoRWs_addr);
1789 return nullptr;
1790 }
1791 lldb::addr_t objc_debug_headerInfoRWs_ptr =
1792 *objc_debug_headerInfoRWs_ptr_or_err;
1793
1794 const size_t metadata_size =
1795 sizeof(uint32_t) + sizeof(uint32_t); // count + entsize
1796 DataBufferHeap metadata_buffer(metadata_size, '\0');
1797 Status error;
1798 process->ReadMemory(objc_debug_headerInfoRWs_ptr, metadata_buffer.GetBytes(),
1799 metadata_size, error);
1800 if (error.Fail()) {
1801 LLDB_LOG(log,
1802 "Unable to read metadata for 'objc_debug_headerInfoRWs' at {0:x}",
1803 objc_debug_headerInfoRWs_ptr);
1804 return nullptr;
1805 }
1806
1807 DataExtractor metadata_extractor(metadata_buffer.GetBytes(), metadata_size,
1808 process->GetByteOrder(),
1809 process->GetAddressByteSize());
1810 lldb::offset_t cursor = 0;
1811 uint32_t count = metadata_extractor.GetU32_unchecked(&cursor);
1812 uint32_t entsize = metadata_extractor.GetU32_unchecked(&cursor);
1813 if (count == 0 || entsize == 0) {
1814 LLDB_LOG(log,
1815 "'objc_debug_headerInfoRWs' had count {0} with entsize {1}. These "
1816 "should both be non-zero.",
1817 count, entsize);
1818 return nullptr;
1819 }
1820
1821 std::unique_ptr<SharedCacheImageHeaders> shared_cache_image_headers(
1822 new SharedCacheImageHeaders(runtime, objc_debug_headerInfoRWs_ptr, count,
1823 entsize));
1824 if (auto Err = shared_cache_image_headers->UpdateIfNeeded()) {
1825 LLDB_LOG_ERROR(log, std::move(Err),
1826 "Failed to update SharedCacheImageHeaders: {0}");
1827 return nullptr;
1828 }
1829
1830 return shared_cache_image_headers;
1831}
1832
1834 if (!m_needs_update)
1835 return llvm::Error::success();
1836
1837 Process *process = m_runtime.GetProcess();
1838 constexpr lldb::addr_t metadata_size =
1839 sizeof(uint32_t) + sizeof(uint32_t); // count + entsize
1840
1841 /// Sanity check: m_count and m_entsize are external input, guard against
1842 /// invalid values using an arbitrary 1GB maximum size.
1843 const size_t memory_needed = static_cast<size_t>(m_count) * m_entsize;
1844 if (memory_needed > 1024 * 1024 * 1024)
1845 return llvm::createStringError(
1846 "SharedCacheImageHeaders require too much memory");
1847
1848 const lldb::addr_t first_header_addr = m_headerInfoRWs_ptr + metadata_size;
1849
1850 llvm::SmallVector<Range<addr_t, size_t>> mem_ranges =
1851 llvm::to_vector(llvm::map_range(llvm::seq(m_count), [&](uint32_t i) {
1852 return Range<addr_t, size_t>(first_header_addr + (i * m_entsize),
1853 m_entsize);
1854 }));
1855
1856 llvm::SmallVector<uint8_t, 0> buffer(memory_needed, 0);
1857 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> read_results =
1858 process->ReadMemoryRanges(mem_ranges, buffer);
1859
1860 for (auto [i, header_data] : llvm::enumerate(read_results)) {
1861 if (header_data.size() != m_entsize)
1862 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1863 "Failed to read memory from inferior when "
1864 "populating SharedCacheImageHeaders");
1865
1866 DataExtractor header_extractor(header_data.data(), m_entsize,
1867 process->GetByteOrder(),
1868 process->GetAddressByteSize());
1869 lldb::offset_t cursor = 0;
1870 bool is_loaded = false;
1871 if (m_entsize == 4) {
1872 uint32_t header = header_extractor.GetU32_unchecked(&cursor);
1873 if (header & 1)
1874 is_loaded = true;
1875 } else {
1876 uint64_t header = header_extractor.GetU64_unchecked(&cursor);
1877 if (header & 1)
1878 is_loaded = true;
1880
1881 if (is_loaded)
1882 m_loaded_images.set(i);
1883 else
1884 m_loaded_images.reset(i);
1885 }
1886 m_needs_update = false;
1887 m_version++;
1888 return llvm::Error::success();
1889}
1890
1892 uint16_t image_index) {
1893 if (image_index >= m_count)
1894 return false;
1895 if (auto Err = UpdateIfNeeded()) {
1897 LLDB_LOG_ERROR(log, std::move(Err),
1898 "Failed to update SharedCacheImageHeaders: {0}");
1899 }
1900 return m_loaded_images.test(image_index);
1901}
1902
1904 if (auto Err = UpdateIfNeeded()) {
1906 LLDB_LOG_ERROR(log, std::move(Err),
1907 "Failed to update SharedCacheImageHeaders: {0}");
1908 }
1909 return m_version;
1910}
1911
1912std::unique_ptr<UtilityFunction>
1914 ExecutionContext &exe_ctx, Helper helper, std::string code,
1915 std::string name) {
1917
1918 LLDB_LOG(log, "Creating utility function {0}", name);
1919
1920 TypeSystemClangSP scratch_ts_sp =
1922 if (!scratch_ts_sp)
1923 return {};
1924
1925 auto utility_fn_or_error = exe_ctx.GetTargetRef().CreateUtilityFunction(
1926 std::move(code), std::move(name), eLanguageTypeC, exe_ctx);
1927 if (!utility_fn_or_error) {
1929 log, utility_fn_or_error.takeError(),
1930 "Failed to get utility function for dynamic info extractor: {0}");
1931 return {};
1932 }
1933
1934 // Make some types for our arguments.
1935 CompilerType clang_uint32_t_type =
1936 scratch_ts_sp->GetBuiltinTypeForEncodingAndBitSize(eEncodingUint, 32);
1937 CompilerType clang_void_pointer_type =
1938 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
1939
1940 // Make the runner function for our implementation utility function.
1941 ValueList arguments;
1942 Value value;
1944 value.SetCompilerType(clang_void_pointer_type);
1945 arguments.PushValue(value);
1946 arguments.PushValue(value);
1948 value.SetCompilerType(clang_uint32_t_type);
1949 arguments.PushValue(value);
1950
1951 // objc_getRealizedClassList_trylock takes an additional buffer and length.
1953 value.SetCompilerType(clang_void_pointer_type);
1954 arguments.PushValue(value);
1955 value.SetCompilerType(clang_uint32_t_type);
1956 arguments.PushValue(value);
1957 }
1958
1959 arguments.PushValue(value);
1960
1961 std::unique_ptr<UtilityFunction> utility_fn = std::move(*utility_fn_or_error);
1962
1963 Status error;
1964 utility_fn->MakeFunctionCaller(clang_uint32_t_type, arguments,
1965 exe_ctx.GetThreadSP(), error);
1966
1967 if (error.Fail()) {
1968 LLDB_LOG(log,
1969 "Failed to make function caller for implementation lookup: {0}.",
1970 error.AsCString());
1971 return {};
1972 }
1973
1974 return utility_fn;
1975}
1987 return m_gdb_objc_realized_classes_helper.utility_function.get();
1988 }
1990 if (!m_objc_copyRealizedClassList_helper.utility_function)
1991 m_objc_copyRealizedClassList_helper.utility_function =
1992 GetClassInfoUtilityFunctionImpl(exe_ctx, helper,
1995 return m_objc_copyRealizedClassList_helper.utility_function.get();
1996 }
1997 case objc_getRealizedClassList_trylock: {
1998 if (!m_objc_getRealizedClassList_trylock_helper.utility_function)
1999 m_objc_getRealizedClassList_trylock_helper.utility_function =
2000 GetClassInfoUtilityFunctionImpl(exe_ctx, helper,
2003 return m_objc_getRealizedClassList_trylock_helper.utility_function.get();
2004 }
2005 }
2006 llvm_unreachable("Unexpected helper");
2007}
2008
2011 switch (helper) {
2012 case gdb_objc_realized_classes:
2013 return m_gdb_objc_realized_classes_helper.args;
2014 case objc_copyRealizedClassList:
2015 return m_objc_copyRealizedClassList_helper.args;
2016 case objc_getRealizedClassList_trylock:
2017 return m_objc_getRealizedClassList_trylock_helper.args;
2018 }
2019 llvm_unreachable("Unexpected helper");
2021
2024 ExecutionContext &exe_ctx) const {
2025 if (!m_runtime.m_has_objc_copyRealizedClassList &&
2026 !m_runtime.m_has_objc_getRealizedClassList_trylock)
2028
2029 if (Process *process = m_runtime.GetProcess()) {
2030 if (DynamicLoader *loader = process->GetDynamicLoader()) {
2031 if (loader->IsFullyInitialized()) {
2032 switch (exe_ctx.GetTargetRef().GetDynamicClassInfoHelper()) {
2034 [[fallthrough]];
2036 if (m_runtime.m_has_objc_getRealizedClassList_trylock)
2038 [[fallthrough]];
2040 if (m_runtime.m_has_objc_copyRealizedClassList)
2042 [[fallthrough]];
2045 }
2046 }
2047 }
2048 }
2049
2051}
2052
2053std::unique_ptr<UtilityFunction>
2057
2058 LLDB_LOG(log, "Creating utility function {0}",
2060
2061 TypeSystemClangSP scratch_ts_sp =
2063 if (!scratch_ts_sp)
2064 return {};
2065
2066 // If the inferior objc.dylib has the class_getNameRaw function, use that in
2067 // our jitted expression. Else fall back to the old class_getName.
2068 static ConstString g_class_getName_symbol_name("class_getName");
2069 static ConstString g_class_getNameRaw_symbol_name(
2070 "objc_debug_class_getNameRaw");
2071
2072 ConstString class_name_getter_function_name =
2073 m_runtime.HasSymbol(g_class_getNameRaw_symbol_name)
2074 ? g_class_getNameRaw_symbol_name
2075 : g_class_getName_symbol_name;
2076
2077 // Substitute in the correct class_getName / class_getNameRaw function name,
2078 // concatenate the two parts of our expression text. The format string has
2079 // two %s's, so provide the name twice.
2080 std::string shared_class_expression;
2081 llvm::raw_string_ostream(shared_class_expression) << llvm::formatv(
2082 g_shared_cache_class_name_funcptr, class_name_getter_function_name,
2083 class_name_getter_function_name);
2084
2085 shared_class_expression += g_get_shared_cache_class_info_definitions;
2086 shared_class_expression += g_get_shared_cache_class_info_body;
2087
2088 auto utility_fn_or_error = exe_ctx.GetTargetRef().CreateUtilityFunction(
2089 std::move(shared_class_expression), g_get_shared_cache_class_info_name,
2090 eLanguageTypeC, exe_ctx);
2091
2092 if (!utility_fn_or_error) {
2094 log, utility_fn_or_error.takeError(),
2095 "Failed to get utility function for shared class info extractor: {0}");
2096 return nullptr;
2097 }
2098
2099 // Make some types for our arguments.
2100 CompilerType clang_uint32_t_type =
2101 scratch_ts_sp->GetBuiltinTypeForEncodingAndBitSize(eEncodingUint, 32);
2102 CompilerType clang_void_pointer_type =
2103 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
2104 CompilerType clang_uint64_t_pointer_type =
2105 scratch_ts_sp->GetBuiltinTypeForEncodingAndBitSize(eEncodingUint, 64)
2106 .GetPointerType();
2107 CompilerType clang_uint32_t_pointer_type =
2108 scratch_ts_sp->GetBuiltinTypeForEncodingAndBitSize(eEncodingUint, 32)
2109 .GetPointerType();
2110
2111 // Next make the function caller for our implementation utility function.
2112 ValueList arguments;
2113 Value value;
2115 value.SetCompilerType(clang_void_pointer_type);
2116 arguments.PushValue(value);
2117 arguments.PushValue(value);
2118 arguments.PushValue(value);
2121 value.SetCompilerType(clang_uint64_t_pointer_type);
2122 arguments.PushValue(value);
2123
2125 value.SetCompilerType(clang_uint32_t_type);
2126 arguments.PushValue(value);
2129 value.SetCompilerType(clang_uint32_t_pointer_type);
2130 arguments.PushValue(value);
2131
2133 value.SetCompilerType(clang_uint32_t_type);
2134 arguments.PushValue(value);
2135
2136 std::unique_ptr<UtilityFunction> utility_fn = std::move(*utility_fn_or_error);
2137
2138 Status error;
2139 utility_fn->MakeFunctionCaller(clang_uint32_t_type, arguments,
2140 exe_ctx.GetThreadSP(), error);
2141
2142 if (error.Fail()) {
2143 LLDB_LOG(log,
2144 "Failed to make function caller for implementation lookup: {0}.",
2145 error.AsCString());
2146 return {};
2147 }
2148
2149 return utility_fn;
2150}
2151
2154 ExecutionContext &exe_ctx) {
2155 if (!m_utility_function)
2156 m_utility_function = GetClassInfoUtilityFunctionImpl(exe_ctx);
2157 return m_utility_function.get();
2158}
2159
2160AppleObjCRuntimeV2::DescriptorMapUpdateResult
2162 RemoteNXMapTable &hash_table) {
2163 Process *process = m_runtime.GetProcess();
2164 if (process == nullptr)
2166
2167 uint32_t num_class_infos = 0;
2168
2170
2171 ExecutionContext exe_ctx;
2172
2173 ThreadSP thread_sp = process->GetThreadList().GetExpressionExecutionThread();
2174
2175 if (!thread_sp)
2177
2178 if (!thread_sp->SafeToCallFunctions())
2180
2181 thread_sp->CalculateExecutionContext(exe_ctx);
2182 TypeSystemClangSP scratch_ts_sp =
2184
2185 if (!scratch_ts_sp)
2187
2188 Address function_address;
2189
2190 const uint32_t addr_size = process->GetAddressByteSize();
2191
2192 Status err;
2193
2194 // Compute which helper we're going to use for this update.
2195 const DynamicClassInfoExtractor::Helper helper = ComputeHelper(exe_ctx);
2196
2197 // Read the total number of classes from the hash table
2198 const uint32_t num_classes =
2200 ? hash_table.GetCount()
2201 : m_runtime.m_realized_class_generation_count;
2202 if (num_classes == 0) {
2203 LLDB_LOGF(log, "No dynamic classes found.");
2205 }
2206
2207 UtilityFunction *get_class_info_code =
2208 GetClassInfoUtilityFunction(exe_ctx, helper);
2209 if (!get_class_info_code) {
2210 // The callee will have already logged a useful error message.
2212 }
2213
2214 FunctionCaller *get_class_info_function =
2215 get_class_info_code->GetFunctionCaller();
2216
2217 if (!get_class_info_function) {
2218 LLDB_LOGF(log, "Failed to get implementation lookup function caller.");
2220 }
2221
2222 ValueList arguments = get_class_info_function->GetArgumentValues();
2223
2224 DiagnosticManager diagnostics;
2225
2226 const uint32_t class_info_byte_size = addr_size + 4;
2227 const uint32_t class_infos_byte_size = num_classes * class_info_byte_size;
2228 lldb::addr_t class_infos_addr = process->AllocateMemory(
2229 class_infos_byte_size, ePermissionsReadable | ePermissionsWritable, err);
2230
2231 if (class_infos_addr == LLDB_INVALID_ADDRESS) {
2232 LLDB_LOGF(log,
2233 "unable to allocate %" PRIu32
2234 " bytes in process for shared cache read",
2235 class_infos_byte_size);
2237 }
2238
2239 llvm::scope_exit deallocate_class_infos([&] {
2240 // Deallocate the memory we allocated for the ClassInfo array
2241 if (class_infos_addr != LLDB_INVALID_ADDRESS)
2242 process->DeallocateMemory(class_infos_addr);
2243 });
2244
2245 lldb::addr_t class_buffer_addr = LLDB_INVALID_ADDRESS;
2246 const uint32_t class_byte_size = addr_size;
2247 const uint32_t class_buffer_len = num_classes;
2248 const uint32_t class_buffer_byte_size = class_buffer_len * class_byte_size;
2249 if (helper == Helper::objc_getRealizedClassList_trylock) {
2250 class_buffer_addr = process->AllocateMemory(
2251 class_buffer_byte_size, ePermissionsReadable | ePermissionsWritable,
2252 err);
2253 if (class_buffer_addr == LLDB_INVALID_ADDRESS) {
2254 LLDB_LOGF(log,
2255 "unable to allocate %" PRIu32
2256 " bytes in process for shared cache read",
2257 class_buffer_byte_size);
2259 }
2260 }
2261
2262 llvm::scope_exit deallocate_class_buffer([&] {
2263 // Deallocate the memory we allocated for the Class array
2264 if (class_buffer_addr != LLDB_INVALID_ADDRESS)
2265 process->DeallocateMemory(class_buffer_addr);
2266 });
2267
2268 std::lock_guard<std::mutex> guard(m_mutex);
2269
2270 // Fill in our function argument values
2271 uint32_t index = 0;
2272 arguments.GetValueAtIndex(index++)->GetScalar() =
2273 hash_table.GetTableLoadAddress();
2274 arguments.GetValueAtIndex(index++)->GetScalar() = class_infos_addr;
2275 arguments.GetValueAtIndex(index++)->GetScalar() = class_infos_byte_size;
2276
2277 if (class_buffer_addr != LLDB_INVALID_ADDRESS) {
2278 arguments.GetValueAtIndex(index++)->GetScalar() = class_buffer_addr;
2279 arguments.GetValueAtIndex(index++)->GetScalar() = class_buffer_len;
2280 }
2281
2282 // Only dump the runtime classes from the expression evaluation if the log is
2283 // verbose:
2284 Log *type_log = GetLog(LLDBLog::Types);
2285 bool dump_log = type_log && type_log->GetVerbose();
2286
2287 arguments.GetValueAtIndex(index++)->GetScalar() = dump_log ? 1 : 0;
2288
2289 bool success = false;
2290
2291 diagnostics.Clear();
2292
2293 // Write our function arguments into the process so we can run our function
2294 if (get_class_info_function->WriteFunctionArguments(
2295 exe_ctx, GetClassInfoArgs(helper), arguments, diagnostics)) {
2296 EvaluateExpressionOptions options;
2297 options.SetUnwindOnError(true);
2298 options.SetTryAllThreads(false);
2299 options.SetStopOthers(true);
2300 options.SetIgnoreBreakpoints(true);
2301 options.SetTimeout(process->GetUtilityExpressionTimeout());
2302 options.SetIsForUtilityExpr(true);
2303
2304 CompilerType clang_uint32_t_type =
2305 scratch_ts_sp->GetBuiltinTypeForEncodingAndBitSize(eEncodingUint, 32);
2306
2307 Value return_value;
2309 return_value.SetCompilerType(clang_uint32_t_type);
2310 return_value.GetScalar() = 0;
2311
2312 diagnostics.Clear();
2313
2314 // Run the function
2315 ExpressionResults results = get_class_info_function->ExecuteFunction(
2316 exe_ctx, &GetClassInfoArgs(helper), options, diagnostics, return_value);
2318 if (results == eExpressionCompleted) {
2319 // The result is the number of ClassInfo structures that were filled in
2320 num_class_infos = return_value.GetScalar().ULong();
2321 LLDB_LOG(log, "Discovered {0} Objective-C classes", num_class_infos);
2322 if (num_class_infos > 0) {
2323 // Read the ClassInfo structures
2324 DataBufferHeap buffer(num_class_infos * class_info_byte_size, 0);
2325 if (process->ReadMemory(class_infos_addr, buffer.GetBytes(),
2326 buffer.GetByteSize(),
2327 err) == buffer.GetByteSize()) {
2328 DataExtractor class_infos_data(buffer.GetBytes(),
2329 buffer.GetByteSize(),
2330 process->GetByteOrder(), addr_size);
2331 m_runtime.ParseClassInfoArray(class_infos_data, num_class_infos);
2332 }
2333 }
2334 success = true;
2335 } else {
2336 if (log) {
2337 LLDB_LOGF(log, "Error evaluating our find class name function.");
2338 diagnostics.Dump(log);
2339 }
2340 }
2341 } else {
2342 if (log) {
2343 LLDB_LOGF(log, "Error writing function arguments.");
2344 diagnostics.Dump(log);
2345 }
2346 }
2347
2348 return DescriptorMapUpdateResult(success, false, num_class_infos);
2349}
2350
2351uint32_t AppleObjCRuntimeV2::ParseClassInfoArray(const DataExtractor &data,
2352 uint32_t num_class_infos) {
2353 // Parses an array of "num_class_infos" packed ClassInfo structures:
2354 //
2355 // struct ClassInfo
2356 // {
2357 // Class isa;
2358 // uint32_t hash;
2359 // } __attribute__((__packed__));
2360
2361 Log *log = GetLog(LLDBLog::Types);
2362 bool should_log = log && log->GetVerbose();
2363
2364 uint32_t num_parsed = 0;
2365
2366 // Iterate through all ClassInfo structures
2367 lldb::offset_t offset = 0;
2368 for (uint32_t i = 0; i < num_class_infos; ++i) {
2369 ObjCISA isa = data.GetAddress(&offset);
2370
2371 if (isa == 0) {
2372 if (should_log)
2373 LLDB_LOGF(
2374 log, "AppleObjCRuntimeV2 found NULL isa, ignoring this class info");
2375 continue;
2376 }
2377 // Check if we already know about this ISA, if we do, the info will never
2378 // change, so we can just skip it.
2379 if (ISAIsCached(isa)) {
2380 if (should_log)
2381 LLDB_LOGF(log,
2382 "AppleObjCRuntimeV2 found cached isa=0x%" PRIx64
2383 ", ignoring this class info",
2384 isa);
2385 offset += 4;
2386 } else {
2387 // Read the 32 bit hash for the class name
2388 const uint32_t name_hash = data.GetU32(&offset);
2389 ClassDescriptorSP descriptor_sp(
2390 new ClassDescriptorV2(*this, isa, nullptr));
2391
2392 // The code in g_get_shared_cache_class_info_body sets the value of the
2393 // hash to 0 to signal a demangled symbol. We use class_getName() in that
2394 // code to find the class name, but this returns a demangled name for
2395 // Swift symbols. For those symbols, recompute the hash here by reading
2396 // their name from the runtime.
2397 if (name_hash)
2398 AddClass(isa, descriptor_sp, name_hash);
2399 else
2400 AddClass(isa, descriptor_sp,
2401 descriptor_sp->GetClassName().AsCString(nullptr));
2402 num_parsed++;
2403 if (should_log)
2404 LLDB_LOGF(log,
2405 "AppleObjCRuntimeV2 added isa=0x%" PRIx64
2406 ", hash=0x%8.8x, name=%s",
2407 isa, name_hash,
2408 descriptor_sp->GetClassName().AsCString("<unknown>"));
2409 }
2410 }
2411 if (should_log)
2412 LLDB_LOGF(log, "AppleObjCRuntimeV2 parsed %" PRIu32 " class infos",
2413 num_parsed);
2414 return num_parsed;
2415}
2416
2418 if (!m_objc_module_sp)
2419 return false;
2420 if (const Symbol *symbol = m_objc_module_sp->FindFirstSymbolWithNameAndType(
2421 Name, lldb::eSymbolTypeCode)) {
2422 if (symbol->ValueIsAddress() || symbol->GetAddressRef().IsValid())
2423 return true;
2424 }
2425 return false;
2426}
2427
2428AppleObjCRuntimeV2::DescriptorMapUpdateResult
2430 Process *process = m_runtime.GetProcess();
2431 if (process == nullptr)
2433
2435
2436 ExecutionContext exe_ctx;
2437
2438 ThreadSP thread_sp = process->GetThreadList().GetExpressionExecutionThread();
2439
2440 if (!thread_sp)
2442
2443 if (!thread_sp->SafeToCallFunctions())
2445
2446 thread_sp->CalculateExecutionContext(exe_ctx);
2447 TypeSystemClangSP scratch_ts_sp =
2449
2450 if (!scratch_ts_sp)
2452
2453 Address function_address;
2454
2455 const uint32_t addr_size = process->GetAddressByteSize();
2456
2457 Status err;
2458
2459 uint32_t num_class_infos = 0;
2460
2461 const lldb::addr_t objc_opt_ptr = m_runtime.GetSharedCacheReadOnlyAddress();
2462 const lldb::addr_t shared_cache_base_addr =
2463 m_runtime.GetSharedCacheBaseAddress();
2464
2465 if (objc_opt_ptr == LLDB_INVALID_ADDRESS ||
2466 shared_cache_base_addr == LLDB_INVALID_ADDRESS)
2468
2469 // The number of entries to pre-allocate room for.
2470 // Each entry is (addrsize + 4) bytes
2471 const uint32_t max_num_classes_in_buffer = 212992;
2472
2473 UtilityFunction *get_class_info_code = GetClassInfoUtilityFunction(exe_ctx);
2474 if (!get_class_info_code) {
2475 // The callee will have already logged a useful error message.
2477 }
2478
2479 FunctionCaller *get_shared_cache_class_info_function =
2480 get_class_info_code->GetFunctionCaller();
2481
2482 if (!get_shared_cache_class_info_function) {
2483 LLDB_LOGF(log, "Failed to get implementation lookup function caller.");
2485 }
2486
2487 ValueList arguments =
2488 get_shared_cache_class_info_function->GetArgumentValues();
2489
2490 DiagnosticManager diagnostics;
2491
2492 const uint32_t class_info_byte_size = addr_size + 4;
2493 const uint32_t class_infos_byte_size =
2494 max_num_classes_in_buffer * class_info_byte_size;
2495 lldb::addr_t class_infos_addr = process->AllocateMemory(
2496 class_infos_byte_size, ePermissionsReadable | ePermissionsWritable, err);
2497 const uint32_t relative_selector_offset_addr_size = 64;
2498 lldb::addr_t relative_selector_offset_addr =
2499 process->AllocateMemory(relative_selector_offset_addr_size,
2500 ePermissionsReadable | ePermissionsWritable, err);
2501 constexpr uint32_t class_info_start_idx_byte_size = sizeof(uint32_t);
2502 lldb::addr_t class_info_start_idx_addr =
2503 process->AllocateMemory(class_info_start_idx_byte_size,
2504 ePermissionsReadable | ePermissionsWritable, err);
2505
2506 if (class_infos_addr == LLDB_INVALID_ADDRESS ||
2507 relative_selector_offset_addr == LLDB_INVALID_ADDRESS ||
2508 class_info_start_idx_addr == LLDB_INVALID_ADDRESS) {
2509 LLDB_LOGF(log,
2510 "unable to allocate %" PRIu32
2511 " bytes in process for shared cache read",
2512 class_infos_byte_size);
2514 }
2515
2516 const uint32_t start_idx_init_value = 0;
2517 size_t bytes_written = process->WriteMemory(
2518 class_info_start_idx_addr, &start_idx_init_value, sizeof(uint32_t), err);
2519 if (bytes_written != sizeof(uint32_t)) {
2520 LLDB_LOGF(log,
2521 "unable to write %" PRIu32
2522 " bytes in process for shared cache read",
2523 class_infos_byte_size);
2525 }
2526
2527 std::lock_guard<std::mutex> guard(m_mutex);
2528
2529 // Fill in our function argument values
2530 arguments.GetValueAtIndex(0)->GetScalar() = objc_opt_ptr;
2531 arguments.GetValueAtIndex(1)->GetScalar() = shared_cache_base_addr;
2532 arguments.GetValueAtIndex(2)->GetScalar() = class_infos_addr;
2533 arguments.GetValueAtIndex(3)->GetScalar() = relative_selector_offset_addr;
2534 arguments.GetValueAtIndex(4)->GetScalar() = class_infos_byte_size;
2535 arguments.GetValueAtIndex(5)->GetScalar() = class_info_start_idx_addr;
2536 // Only dump the runtime classes from the expression evaluation if the log is
2537 // verbose:
2538 Log *type_log = GetLog(LLDBLog::Types);
2539 bool dump_log = type_log && type_log->GetVerbose();
2540
2541 arguments.GetValueAtIndex(6)->GetScalar() = dump_log ? 1 : 0;
2542
2543 bool success = false;
2544
2545 diagnostics.Clear();
2546
2547 // Write our function arguments into the process so we can run our function
2548 if (get_shared_cache_class_info_function->WriteFunctionArguments(
2549 exe_ctx, m_args, arguments, diagnostics)) {
2550 EvaluateExpressionOptions options;
2551 options.SetUnwindOnError(true);
2552 options.SetTryAllThreads(false);
2553 options.SetStopOthers(true);
2554 options.SetIgnoreBreakpoints(true);
2555 options.SetTimeout(process->GetUtilityExpressionTimeout());
2556 options.SetIsForUtilityExpr(true);
2557
2558 CompilerType clang_uint32_t_type =
2559 scratch_ts_sp->GetBuiltinTypeForEncodingAndBitSize(eEncodingUint, 32);
2560
2561 Value return_value;
2563 return_value.SetCompilerType(clang_uint32_t_type);
2564 return_value.GetScalar() = 0;
2565
2566 diagnostics.Clear();
2567
2568 uint32_t num_class_infos_read = 0;
2569 bool already_read_relative_selector_offset = false;
2570
2571 do {
2572 // Run the function.
2573 ExpressionResults results =
2574 get_shared_cache_class_info_function->ExecuteFunction(
2575 exe_ctx, &m_args, options, diagnostics, return_value);
2576
2577 if (results == eExpressionCompleted) {
2578 // The result is the number of ClassInfo structures that were filled in.
2579 num_class_infos_read = return_value.GetScalar().ULong();
2580 num_class_infos += num_class_infos_read;
2581 LLDB_LOG(log, "Discovered {0} Objective-C classes in the shared cache",
2582 num_class_infos_read);
2583 if (num_class_infos_read > 0) {
2584 success = true;
2585
2586 // Read the relative selector offset. This only needs to occur once no
2587 // matter how many times the function is called.
2588 if (!already_read_relative_selector_offset) {
2589 DataBufferHeap relative_selector_offset_buffer(64, 0);
2590 if (process->ReadMemory(
2591 relative_selector_offset_addr,
2592 relative_selector_offset_buffer.GetBytes(),
2593 relative_selector_offset_buffer.GetByteSize(),
2594 err) == relative_selector_offset_buffer.GetByteSize()) {
2595 DataExtractor relative_selector_offset_data(
2596 relative_selector_offset_buffer.GetBytes(),
2597 relative_selector_offset_buffer.GetByteSize(),
2598 process->GetByteOrder(), addr_size);
2599 lldb::offset_t offset = 0;
2600 uint64_t relative_selector_offset =
2601 relative_selector_offset_data.GetU64(&offset);
2602 if (relative_selector_offset > 0) {
2603 // The offset is relative to the objc_opt struct.
2604 m_runtime.SetRelativeSelectorBaseAddr(objc_opt_ptr +
2605 relative_selector_offset);
2606 }
2607 }
2608 already_read_relative_selector_offset = true;
2609 }
2610
2611 // Read the ClassInfo structures
2612 DataBufferHeap class_infos_buffer(
2613 num_class_infos_read * class_info_byte_size, 0);
2614 if (process->ReadMemory(class_infos_addr,
2615 class_infos_buffer.GetBytes(),
2616 class_infos_buffer.GetByteSize(),
2617 err) == class_infos_buffer.GetByteSize()) {
2618 DataExtractor class_infos_data(class_infos_buffer.GetBytes(),
2619 class_infos_buffer.GetByteSize(),
2620 process->GetByteOrder(), addr_size);
2621
2622 m_runtime.ParseClassInfoArray(class_infos_data,
2623 num_class_infos_read);
2624 }
2625 }
2626 } else if (log) {
2627 LLDB_LOGF(log, "Error evaluating our find class name function.");
2628 diagnostics.Dump(log);
2629 break;
2630 }
2631 } while (num_class_infos_read == max_num_classes_in_buffer);
2632 } else if (log) {
2633 LLDB_LOGF(log, "Error writing function arguments.");
2634 diagnostics.Dump(log);
2635 }
2636
2637 LLDB_LOG(log, "Processed {0} Objective-C classes total from the shared cache",
2638 num_class_infos);
2639 // Cleanup memory we allocated in the process.
2640 process->DeallocateMemory(relative_selector_offset_addr);
2641 process->DeallocateMemory(class_info_start_idx_addr);
2642 process->DeallocateMemory(class_infos_addr);
2643
2644 return DescriptorMapUpdateResult(success, false, num_class_infos);
2646
2648 Process *process = GetProcess();
2649
2650 if (process) {
2651 ModuleSP objc_module_sp(GetObjCModule());
2652
2653 if (objc_module_sp) {
2654 ObjectFile *objc_object = objc_module_sp->GetObjectFile();
2655
2656 if (objc_object) {
2657 SectionList *section_list = objc_module_sp->GetSectionList();
2658
2659 if (section_list) {
2660 SectionSP text_segment_sp(section_list->FindSectionByName("__TEXT"));
2661
2662 if (text_segment_sp) {
2663 SectionSP objc_opt_section_sp(
2664 text_segment_sp->GetChildren().FindSectionByName(
2665 "__objc_opt_ro"));
2666
2667 if (objc_opt_section_sp) {
2668 return objc_opt_section_sp->GetLoadBaseAddress(
2669 &process->GetTarget());
2670 }
2671 }
2672 }
2673 }
2674 }
2675 }
2676 return LLDB_INVALID_ADDRESS;
2677}
2678
2680 StructuredData::ObjectSP info = m_process->GetSharedCacheInfo();
2681 if (!info)
2682 return LLDB_INVALID_ADDRESS;
2683
2684 StructuredData::Dictionary *info_dict = info->GetAsDictionary();
2685 if (!info_dict)
2686 return LLDB_INVALID_ADDRESS;
2687
2689 info_dict->GetValueForKey("shared_cache_base_address");
2690 if (!value)
2691 return LLDB_INVALID_ADDRESS;
2692
2693 return value->GetUnsignedIntegerValue(LLDB_INVALID_ADDRESS);
2694}
2695
2698
2700
2701 // Else we need to check with our process to see when the map was updated.
2702 Process *process = GetProcess();
2703
2704 if (process) {
2705 RemoteNXMapTable hash_table;
2706
2707 // Update the process stop ID that indicates the last time we updated the
2708 // map, whether it was successful or not.
2710
2711 // Ask the runtime is the realized class generation count changed. Unlike
2712 // the hash table, this accounts for lazily named classes.
2713 const bool class_count_changed = RealizedClassGenerationCountChanged();
2714
2715 if (!m_hash_signature.NeedsUpdate(process, this, hash_table) &&
2716 !class_count_changed)
2717 return;
2718
2719 m_hash_signature.UpdateSignature(hash_table);
2720
2721 // Grab the dynamically loaded Objective-C classes from memory.
2722 DescriptorMapUpdateResult dynamic_update_result =
2723 m_dynamic_class_info_extractor.UpdateISAToDescriptorMap(hash_table);
2724
2725 // Now get the objc classes that are baked into the Objective-C runtime in
2726 // the shared cache, but only once per process as this data never changes
2727 if (!m_loaded_objc_opt) {
2728 // it is legitimately possible for the shared cache to be empty - in that
2729 // case, the dynamic hash table will contain all the class information we
2730 // need; the situation we're trying to detect is one where we aren't
2731 // seeing class information from the runtime - in order to detect that
2732 // vs. just the shared cache being empty or sparsely populated, we set an
2733 // arbitrary (very low) threshold for the number of classes that we want
2734 // to see in a "good" scenario - anything below that is suspicious
2735 // (Foundation alone has thousands of classes)
2736 const uint32_t num_classes_to_warn_at = 500;
2737
2738 DescriptorMapUpdateResult shared_cache_update_result =
2739 m_shared_cache_class_info_extractor.UpdateISAToDescriptorMap();
2741 LLDB_LOGF(log,
2742 "attempted to read objc class data - results: "
2743 "[dynamic_update]: ran: %s, retry: %s, count: %" PRIu32
2744 " [shared_cache_update]: ran: %s, retry: %s, count: %" PRIu32,
2745 dynamic_update_result.m_update_ran ? "yes" : "no",
2746 dynamic_update_result.m_retry_update ? "yes" : "no",
2747 dynamic_update_result.m_num_found,
2748 shared_cache_update_result.m_update_ran ? "yes" : "no",
2749 shared_cache_update_result.m_retry_update ? "yes" : "no",
2750 shared_cache_update_result.m_num_found);
2751
2752 // warn if:
2753 // - we could not run either expression
2754 // - we found fewer than num_classes_to_warn_at classes total
2755 if (dynamic_update_result.m_retry_update ||
2756 shared_cache_update_result.m_retry_update)
2758 else if ((!shared_cache_update_result.m_update_ran) ||
2759 (!dynamic_update_result.m_update_ran))
2762 else if (dynamic_update_result.m_num_found +
2763 shared_cache_update_result.m_num_found <
2764 num_classes_to_warn_at)
2766 else
2767 m_loaded_objc_opt = true;
2768 }
2769 } else {
2771 }
2772}
2773
2775 Process *process = GetProcess();
2776 if (!process)
2777 return false;
2778
2779 Status error;
2780 uint64_t objc_debug_realized_class_generation_count =
2782 process, ConstString("objc_debug_realized_class_generation_count"),
2783 GetObjCModule(), error);
2784 if (error.Fail())
2785 return false;
2786
2788 objc_debug_realized_class_generation_count)
2789 return false;
2790
2792 LLDB_LOG(log,
2793 "objc_debug_realized_class_generation_count changed from {0} to {1}",
2795 objc_debug_realized_class_generation_count);
2796
2798 objc_debug_realized_class_generation_count;
2799
2800 return true;
2801}
2802
2803static bool DoesProcessHaveSharedCache(Process &process) {
2804 PlatformSP platform_sp = process.GetTarget().GetPlatform();
2805 if (!platform_sp)
2806 return true; // this should not happen
2807
2808 llvm::StringRef platform_plugin_name_sr = platform_sp->GetPluginName();
2809 if (platform_plugin_name_sr.ends_with("-simulator"))
2810 return false;
2811
2812 return true;
2814
2816 SharedCacheWarningReason reason) {
2818 // Simulators do not have the objc_opt_ro class table so don't actually
2819 // complain to the user
2820 return;
2821 }
2822
2823 Debugger &debugger(GetProcess()->GetTarget().GetDebugger());
2824 switch (reason) {
2826 Debugger::ReportWarning("could not find Objective-C class data in "
2827 "the process. This may reduce the quality of type "
2828 "information available\n",
2829 debugger.GetID(), &m_no_classes_cached_warning);
2830 break;
2833 "could not execute support code to read "
2834 "Objective-C class data in the process. This may "
2835 "reduce the quality of type information available\n",
2836 debugger.GetID(), &m_no_classes_cached_warning);
2837 break;
2840 "could not execute support code to read Objective-C class data because "
2841 "it's not yet safe to do so, and will be retried later\n",
2842 debugger.GetID(), nullptr);
2843 break;
2844 }
2845}
2846
2848 if (!m_objc_module_sp)
2849 return;
2851 ObjectFile *object_file = m_objc_module_sp->GetObjectFile();
2852 if (!object_file)
2853 return;
2854
2855 if (!object_file->IsInMemory())
2856 return;
2858 if (!GetProcess()->IsLiveDebugSession())
2859 return;
2860
2861 Target &target = GetProcess()->GetTarget();
2862 Debugger &debugger = target.GetDebugger();
2863
2864 std::string buffer;
2865 llvm::raw_string_ostream os(buffer);
2866
2867 os << "libobjc.A.dylib is being read from process memory. This "
2868 "indicates that LLDB could not ";
2869 if (PlatformSP platform_sp = target.GetPlatform()) {
2870 if (platform_sp->IsHost()) {
2871 os << "read from the host's in-memory shared cache";
2872 } else {
2873 os << "find the on-disk shared cache for this device";
2874 }
2875 } else {
2876 os << "read from the shared cache";
2877 }
2878 os << ". This will likely reduce debugging performance\n";
2879
2880 Debugger::ReportWarning(buffer, debugger.GetID(),
2882}
2883
2885 if (!m_decl_vendor_up)
2886 m_decl_vendor_up = std::make_unique<AppleObjCDeclVendor>(*this);
2887
2888 return m_decl_vendor_up.get();
2889}
2890
2893
2894 const char *name_cstr = name.AsCString(nullptr);
2895
2896 if (name_cstr) {
2897 llvm::StringRef name_strref(name_cstr);
2898
2899 llvm::StringRef ivar_prefix("OBJC_IVAR_$_");
2900 llvm::StringRef class_prefix("OBJC_CLASS_$_");
2901
2902 if (name_strref.starts_with(ivar_prefix)) {
2903 llvm::StringRef ivar_skipped_prefix =
2904 name_strref.substr(ivar_prefix.size());
2905 std::pair<llvm::StringRef, llvm::StringRef> class_and_ivar =
2906 ivar_skipped_prefix.split('.');
2907
2908 if (!class_and_ivar.first.empty() && !class_and_ivar.second.empty()) {
2909 const ConstString class_name_cs(class_and_ivar.first);
2910 ClassDescriptorSP descriptor =
2912
2913 if (descriptor) {
2914 const ConstString ivar_name_cs(class_and_ivar.second);
2915 const char *ivar_name_cstr = ivar_name_cs.AsCString(nullptr);
2916
2917 auto ivar_func = [&ret,
2918 ivar_name_cstr](const char *name, const char *type,
2919 lldb::addr_t offset_addr,
2920 uint64_t size) -> lldb::addr_t {
2921 if (!strcmp(name, ivar_name_cstr)) {
2922 ret = offset_addr;
2923 return true;
2924 }
2925 return false;
2926 };
2927
2928 descriptor->Describe(
2929 std::function<void(ObjCISA)>(nullptr),
2930 std::function<bool(const char *, const char *)>(nullptr),
2931 std::function<bool(const char *, const char *)>(nullptr),
2932 ivar_func);
2933 }
2934 }
2935 } else if (name_strref.starts_with(class_prefix)) {
2936 llvm::StringRef class_skipped_prefix =
2937 name_strref.substr(class_prefix.size());
2938 const ConstString class_name_cs(class_skipped_prefix);
2939 ClassDescriptorSP descriptor =
2940 GetClassDescriptorFromClassName(class_name_cs);
2941
2942 if (descriptor)
2943 ret = descriptor->GetISA();
2944 }
2945 }
2946
2947 return ret;
2948}
2949
2950AppleObjCRuntimeV2::NonPointerISACache *
2952 AppleObjCRuntimeV2 &runtime, const lldb::ModuleSP &objc_module_sp) {
2953 Process *process(runtime.GetProcess());
2954
2955 Log *log = GetLog(LLDBLog::Types);
2956
2957 // Batch read all the ISA-related symbols in one go.
2958 enum ISASymbol {
2959 kMagicMask,
2960 kMagicValue,
2961 kClassMask,
2962 kIndexedMagicMask,
2963 kIndexedMagicValue,
2964 kIndexedIndexMask,
2965 kIndexedIndexShift,
2966 kIndexedClasses,
2967 kISASymbolCount,
2968 };
2969 llvm::SmallVector<RuntimeGlobalSymbolSpec> specs = {
2970 {ConstString("objc_debug_isa_magic_mask")},
2971 {ConstString("objc_debug_isa_magic_value")},
2972 {ConstString("objc_debug_isa_class_mask")},
2973 {ConstString("objc_debug_indexed_isa_magic_mask")},
2974 {ConstString("objc_debug_indexed_isa_magic_value")},
2975 {ConstString("objc_debug_indexed_isa_index_mask")},
2976 {ConstString("objc_debug_indexed_isa_index_shift")},
2977 {ConstString("objc_indexed_classes"), /*read_value=*/false},
2978 };
2979 assert(specs.size() == kISASymbolCount);
2980
2981 auto results =
2982 ExtractRuntimeGlobalSymbolsBatched(process, objc_module_sp, specs);
2983
2984 // Check required symbols.
2985 if (!results[kMagicMask].success || !results[kMagicValue].success ||
2986 !results[kClassMask].success)
2987 return nullptr;
2988
2989 auto objc_debug_isa_magic_mask = results[kMagicMask].value;
2990 auto objc_debug_isa_magic_value = results[kMagicValue].value;
2991 auto objc_debug_isa_class_mask = results[kClassMask].value;
2992
2993 if (log)
2994 log->PutCString("AOCRT::NPI: Found all the non-indexed ISA masks");
2995
2996 // Check optional indexed ISA symbols.
2997 bool foundError = !results[kIndexedMagicMask].success ||
2998 !results[kIndexedMagicValue].success ||
2999 !results[kIndexedIndexMask].success ||
3000 !results[kIndexedIndexShift].success ||
3001 !results[kIndexedClasses].success;
3002
3003 auto objc_debug_indexed_isa_magic_mask = results[kIndexedMagicMask].value;
3004 auto objc_debug_indexed_isa_magic_value = results[kIndexedMagicValue].value;
3005 auto objc_debug_indexed_isa_index_mask = results[kIndexedIndexMask].value;
3006 auto objc_debug_indexed_isa_index_shift = results[kIndexedIndexShift].value;
3007 auto objc_indexed_classes = results[kIndexedClasses].value;
3008
3009 if (log && !foundError)
3010 log->PutCString("AOCRT::NPI: Found all the indexed ISA masks");
3011
3012 // we might want to have some rules to outlaw these other values (e.g if the
3013 // mask is zero but the value is non-zero, ...)
3014
3015 return new NonPointerISACache(
3016 runtime, objc_module_sp, objc_debug_isa_class_mask,
3017 objc_debug_isa_magic_mask, objc_debug_isa_magic_value,
3018 objc_debug_indexed_isa_magic_mask, objc_debug_indexed_isa_magic_value,
3019 objc_debug_indexed_isa_index_mask, objc_debug_indexed_isa_index_shift,
3020 foundError ? 0 : objc_indexed_classes);
3021}
3022
3025 AppleObjCRuntimeV2 &runtime, const lldb::ModuleSP &objc_module_sp) {
3026 Process *process(runtime.GetProcess());
3027
3028 // Batch read all tagged pointer symbols in one go.
3029 enum TaggedPtrSymbol {
3030 kMask,
3031 kSlotShift,
3032 kSlotMask,
3033 kPayloadLshift,
3034 kPayloadRshift,
3035 kClasses,
3036 kExtMask,
3037 kExtSlotShift,
3038 kExtSlotMask,
3039 kExtClasses,
3040 kExtPayloadLshift,
3041 kExtPayloadRshift,
3042 kTaggedPtrSymbolCount,
3043 };
3044 llvm::SmallVector<RuntimeGlobalSymbolSpec> specs = {
3045 {ConstString("objc_debug_taggedpointer_mask")},
3046 {ConstString("objc_debug_taggedpointer_slot_shift"), true, 4},
3047 {ConstString("objc_debug_taggedpointer_slot_mask"), true, 4},
3048 {ConstString("objc_debug_taggedpointer_payload_lshift"), true, 4},
3049 {ConstString("objc_debug_taggedpointer_payload_rshift"), true, 4},
3050 {ConstString("objc_debug_taggedpointer_classes"), false},
3051 {ConstString("objc_debug_taggedpointer_ext_mask")},
3052 {ConstString("objc_debug_taggedpointer_ext_slot_shift"), true, 4},
3053 {ConstString("objc_debug_taggedpointer_ext_slot_mask"), true, 4},
3054 {ConstString("objc_debug_taggedpointer_ext_classes"), false},
3055 {ConstString("objc_debug_taggedpointer_ext_payload_lshift"), true, 4},
3056 {ConstString("objc_debug_taggedpointer_ext_payload_rshift"), true, 4},
3057 };
3058 assert(specs.size() == kTaggedPtrSymbolCount);
3059
3060 auto results =
3061 ExtractRuntimeGlobalSymbolsBatched(process, objc_module_sp, specs);
3062
3063 // Check required symbols.
3064 bool required_success =
3065 results[kMask].success && results[kSlotShift].success &&
3066 results[kSlotMask].success && results[kPayloadLshift].success &&
3067 results[kPayloadRshift].success && results[kClasses].success;
3068
3069 if (!required_success)
3070 return new TaggedPointerVendorLegacy(runtime);
3071
3072 auto objc_debug_taggedpointer_mask = results[kMask].value;
3073 auto objc_debug_taggedpointer_slot_shift = results[kSlotShift].value;
3074 auto objc_debug_taggedpointer_slot_mask = results[kSlotMask].value;
3075 auto objc_debug_taggedpointer_payload_lshift = results[kPayloadLshift].value;
3076 auto objc_debug_taggedpointer_payload_rshift = results[kPayloadRshift].value;
3077 auto objc_debug_taggedpointer_classes = results[kClasses].value;
3078
3079 // Check if extended symbols are all present.
3080 bool extended_success =
3081 results[kExtMask].success && results[kExtSlotShift].success &&
3082 results[kExtSlotMask].success && results[kExtClasses].success &&
3083 results[kExtPayloadLshift].success && results[kExtPayloadRshift].success;
3084
3085 if (extended_success) {
3086 auto objc_debug_taggedpointer_ext_mask = results[kExtMask].value;
3087 auto objc_debug_taggedpointer_ext_slot_shift = results[kExtSlotShift].value;
3088 auto objc_debug_taggedpointer_ext_slot_mask = results[kExtSlotMask].value;
3089 auto objc_debug_taggedpointer_ext_classes = results[kExtClasses].value;
3090 auto objc_debug_taggedpointer_ext_payload_lshift =
3091 results[kExtPayloadLshift].value;
3092 auto objc_debug_taggedpointer_ext_payload_rshift =
3093 results[kExtPayloadRshift].value;
3094
3095 return new TaggedPointerVendorExtended(
3096 runtime, objc_debug_taggedpointer_mask,
3097 objc_debug_taggedpointer_ext_mask, objc_debug_taggedpointer_slot_shift,
3098 objc_debug_taggedpointer_ext_slot_shift,
3099 objc_debug_taggedpointer_slot_mask,
3100 objc_debug_taggedpointer_ext_slot_mask,
3101 objc_debug_taggedpointer_payload_lshift,
3102 objc_debug_taggedpointer_payload_rshift,
3103 objc_debug_taggedpointer_ext_payload_lshift,
3104 objc_debug_taggedpointer_ext_payload_rshift,
3105 objc_debug_taggedpointer_classes, objc_debug_taggedpointer_ext_classes);
3106 }
3107
3108 // we might want to have some rules to outlaw these values (e.g if the
3109 // table's address is zero)
3110
3112 runtime, objc_debug_taggedpointer_mask,
3113 objc_debug_taggedpointer_slot_shift, objc_debug_taggedpointer_slot_mask,
3114 objc_debug_taggedpointer_payload_lshift,
3115 objc_debug_taggedpointer_payload_rshift,
3116 objc_debug_taggedpointer_classes);
3117}
3118
3120 lldb::addr_t ptr) {
3121 return (ptr & 1);
3122}
3123
3124std::unique_ptr<ObjCLanguageRuntime::ClassDescriptor>
3126 lldb::addr_t ptr) {
3127 if (!IsPossibleTaggedPointer(ptr))
3128 return nullptr;
3129
3130 uint32_t foundation_version = m_runtime.GetFoundationVersion();
3131
3132 if (foundation_version == LLDB_INVALID_MODULE_VERSION)
3133 return nullptr;
3134
3135 uint64_t class_bits = (ptr & 0xE) >> 1;
3136 ConstString name;
3137
3138 static ConstString g_NSAtom("NSAtom");
3139 static ConstString g_NSNumber("NSNumber");
3140 static ConstString g_NSDateTS("NSDateTS");
3141 static ConstString g_NSManagedObject("NSManagedObject");
3142 static ConstString g_NSDate("NSDate");
3143
3144 if (foundation_version >= 900) {
3145 switch (class_bits) {
3146 case 0:
3147 name = g_NSAtom;
3148 break;
3149 case 3:
3150 name = g_NSNumber;
3151 break;
3152 case 4:
3153 name = g_NSDateTS;
3154 break;
3155 case 5:
3156 name = g_NSManagedObject;
3157 break;
3158 case 6:
3159 name = g_NSDate;
3160 break;
3161 default:
3162 return nullptr;
3163 }
3164 } else {
3165 switch (class_bits) {
3166 case 1:
3167 name = g_NSNumber;
3168 break;
3169 case 5:
3170 name = g_NSManagedObject;
3171 break;
3172 case 6:
3173 name = g_NSDate;
3174 break;
3175 case 7:
3176 name = g_NSDateTS;
3177 break;
3178 default:
3179 return nullptr;
3180 }
3181 }
3182
3183 lldb::addr_t unobfuscated = ptr ^ m_runtime.GetTaggedPointerObfuscator();
3184 return std::make_unique<ClassDescriptorV2Tagged>(name, unobfuscated);
3185}
3186
3189 AppleObjCRuntimeV2 &runtime, uint64_t objc_debug_taggedpointer_mask,
3190 uint32_t objc_debug_taggedpointer_slot_shift,
3191 uint32_t objc_debug_taggedpointer_slot_mask,
3192 uint32_t objc_debug_taggedpointer_payload_lshift,
3193 uint32_t objc_debug_taggedpointer_payload_rshift,
3194 lldb::addr_t objc_debug_taggedpointer_classes)
3195 : TaggedPointerVendorV2(runtime), m_cache(),
3196 m_objc_debug_taggedpointer_mask(objc_debug_taggedpointer_mask),
3197 m_objc_debug_taggedpointer_slot_shift(
3198 objc_debug_taggedpointer_slot_shift),
3199 m_objc_debug_taggedpointer_slot_mask(objc_debug_taggedpointer_slot_mask),
3200 m_objc_debug_taggedpointer_payload_lshift(
3201 objc_debug_taggedpointer_payload_lshift),
3202 m_objc_debug_taggedpointer_payload_rshift(
3203 objc_debug_taggedpointer_payload_rshift),
3204 m_objc_debug_taggedpointer_classes(objc_debug_taggedpointer_classes) {}
3205
3208 return (ptr & m_objc_debug_taggedpointer_mask) != 0;
3209}
3210
3211std::unique_ptr<ObjCLanguageRuntime::ClassDescriptor>
3213 lldb::addr_t ptr) {
3214 ClassDescriptorSP actual_class_descriptor_sp;
3215 uint64_t unobfuscated = (ptr) ^ m_runtime.GetTaggedPointerObfuscator();
3216
3217 if (!IsPossibleTaggedPointer(unobfuscated))
3218 return nullptr;
3219
3220 uintptr_t slot = (ptr >> m_objc_debug_taggedpointer_slot_shift) &
3221 m_objc_debug_taggedpointer_slot_mask;
3222
3223 CacheIterator iterator = m_cache.find(slot), end = m_cache.end();
3224 if (iterator != end) {
3225 actual_class_descriptor_sp = iterator->second;
3226 } else {
3227 Process *process(m_runtime.GetProcess());
3228 uintptr_t slot_ptr = slot * process->GetAddressByteSize() +
3230 llvm::Expected<lldb::addr_t> slot_data_or_err =
3231 process->ReadPointerFromMemory(slot_ptr);
3232 if (!slot_data_or_err) {
3233 llvm::consumeError(slot_data_or_err.takeError());
3234 return nullptr;
3235 }
3236 uintptr_t slot_data = *slot_data_or_err;
3237 if (slot_data == 0)
3238 return nullptr;
3239 actual_class_descriptor_sp =
3240 m_runtime.GetClassDescriptorFromISA((ObjCISA)slot_data);
3241 if (!actual_class_descriptor_sp) {
3242 if (ABISP abi_sp = process->GetABI()) {
3243 ObjCISA fixed_isa = abi_sp->FixCodeAddress((ObjCISA)slot_data);
3244 actual_class_descriptor_sp =
3245 m_runtime.GetClassDescriptorFromISA(fixed_isa);
3246 }
3247 }
3248 if (!actual_class_descriptor_sp)
3249 return nullptr;
3250 m_cache[slot] = actual_class_descriptor_sp;
3251 }
3252
3253 uint64_t data_payload =
3254 ((unobfuscated << m_objc_debug_taggedpointer_payload_lshift) >>
3255 m_objc_debug_taggedpointer_payload_rshift);
3256 int64_t data_payload_signed =
3257 ((int64_t)(unobfuscated << m_objc_debug_taggedpointer_payload_lshift) >>
3258 m_objc_debug_taggedpointer_payload_rshift);
3259 return std::make_unique<ClassDescriptorV2Tagged>(
3260 actual_class_descriptor_sp, data_payload, data_payload_signed);
3261}
3264 AppleObjCRuntimeV2 &runtime, uint64_t objc_debug_taggedpointer_mask,
3265 uint64_t objc_debug_taggedpointer_ext_mask,
3266 uint32_t objc_debug_taggedpointer_slot_shift,
3267 uint32_t objc_debug_taggedpointer_ext_slot_shift,
3268 uint32_t objc_debug_taggedpointer_slot_mask,
3269 uint32_t objc_debug_taggedpointer_ext_slot_mask,
3270 uint32_t objc_debug_taggedpointer_payload_lshift,
3271 uint32_t objc_debug_taggedpointer_payload_rshift,
3272 uint32_t objc_debug_taggedpointer_ext_payload_lshift,
3273 uint32_t objc_debug_taggedpointer_ext_payload_rshift,
3274 lldb::addr_t objc_debug_taggedpointer_classes,
3275 lldb::addr_t objc_debug_taggedpointer_ext_classes)
3277 runtime, objc_debug_taggedpointer_mask,
3278 objc_debug_taggedpointer_slot_shift,
3279 objc_debug_taggedpointer_slot_mask,
3280 objc_debug_taggedpointer_payload_lshift,
3281 objc_debug_taggedpointer_payload_rshift,
3282 objc_debug_taggedpointer_classes),
3283 m_ext_cache(),
3284 m_objc_debug_taggedpointer_ext_mask(objc_debug_taggedpointer_ext_mask),
3286 objc_debug_taggedpointer_ext_slot_shift),
3288 objc_debug_taggedpointer_ext_slot_mask),
3290 objc_debug_taggedpointer_ext_payload_lshift),
3292 objc_debug_taggedpointer_ext_payload_rshift),
3294 objc_debug_taggedpointer_ext_classes) {}
3295
3298 if (!IsPossibleTaggedPointer(ptr))
3299 return false;
3300
3301 if (m_objc_debug_taggedpointer_ext_mask == 0)
3302 return false;
3303
3304 return ((ptr & m_objc_debug_taggedpointer_ext_mask) ==
3305 m_objc_debug_taggedpointer_ext_mask);
3306}
3307
3308std::unique_ptr<ObjCLanguageRuntime::ClassDescriptor>
3310 lldb::addr_t ptr) {
3311 ClassDescriptorSP actual_class_descriptor_sp;
3312 uint64_t unobfuscated = (ptr) ^ m_runtime.GetTaggedPointerObfuscator();
3313
3314 if (!IsPossibleTaggedPointer(unobfuscated))
3315 return nullptr;
3316
3317 if (!IsPossibleExtendedTaggedPointer(unobfuscated))
3319
3320 uintptr_t slot = (ptr >> m_objc_debug_taggedpointer_ext_slot_shift) &
3321 m_objc_debug_taggedpointer_ext_slot_mask;
3322
3323 CacheIterator iterator = m_ext_cache.find(slot), end = m_ext_cache.end();
3324 if (iterator != end) {
3325 actual_class_descriptor_sp = iterator->second;
3326 } else {
3327 Process *process(m_runtime.GetProcess());
3328 uintptr_t slot_ptr = slot * process->GetAddressByteSize() +
3329 m_objc_debug_taggedpointer_ext_classes;
3330 llvm::Expected<lldb::addr_t> slot_data_or_err =
3331 process->ReadPointerFromMemory(slot_ptr);
3332 if (!slot_data_or_err) {
3333 llvm::consumeError(slot_data_or_err.takeError());
3334 return nullptr;
3335 }
3336 uintptr_t slot_data = *slot_data_or_err;
3337 if (slot_data == 0)
3338 return nullptr;
3339 actual_class_descriptor_sp =
3340 m_runtime.GetClassDescriptorFromISA((ObjCISA)slot_data);
3341 if (!actual_class_descriptor_sp)
3342 return nullptr;
3343 m_ext_cache[slot] = actual_class_descriptor_sp;
3345
3346 uint64_t data_payload = (((uint64_t)unobfuscated
3347 << m_objc_debug_taggedpointer_ext_payload_lshift) >>
3348 m_objc_debug_taggedpointer_ext_payload_rshift);
3349 int64_t data_payload_signed =
3350 ((int64_t)((uint64_t)unobfuscated
3351 << m_objc_debug_taggedpointer_ext_payload_lshift) >>
3352 m_objc_debug_taggedpointer_ext_payload_rshift);
3353
3354 return std::make_unique<ClassDescriptorV2Tagged>(
3355 actual_class_descriptor_sp, data_payload, data_payload_signed);
3356}
3357
3359 AppleObjCRuntimeV2 &runtime, const ModuleSP &objc_module_sp,
3360 uint64_t objc_debug_isa_class_mask, uint64_t objc_debug_isa_magic_mask,
3361 uint64_t objc_debug_isa_magic_value,
3362 uint64_t objc_debug_indexed_isa_magic_mask,
3363 uint64_t objc_debug_indexed_isa_magic_value,
3364 uint64_t objc_debug_indexed_isa_index_mask,
3365 uint64_t objc_debug_indexed_isa_index_shift,
3366 lldb::addr_t objc_indexed_classes)
3367 : m_runtime(runtime), m_cache(), m_objc_module_wp(objc_module_sp),
3368 m_objc_debug_isa_class_mask(objc_debug_isa_class_mask),
3369 m_objc_debug_isa_magic_mask(objc_debug_isa_magic_mask),
3370 m_objc_debug_isa_magic_value(objc_debug_isa_magic_value),
3371 m_objc_debug_indexed_isa_magic_mask(objc_debug_indexed_isa_magic_mask),
3372 m_objc_debug_indexed_isa_magic_value(objc_debug_indexed_isa_magic_value),
3373 m_objc_debug_indexed_isa_index_mask(objc_debug_indexed_isa_index_mask),
3374 m_objc_debug_indexed_isa_index_shift(objc_debug_indexed_isa_index_shift),
3375 m_objc_indexed_classes(objc_indexed_classes), m_indexed_isa_cache() {}
3376
3379 ObjCISA real_isa = 0;
3380 if (!EvaluateNonPointerISA(isa, real_isa))
3382 auto cache_iter = m_cache.find(real_isa);
3383 if (cache_iter != m_cache.end())
3384 return cache_iter->second;
3385 auto descriptor_sp =
3386 m_runtime.ObjCLanguageRuntime::GetClassDescriptorFromISA(real_isa);
3387 if (descriptor_sp) // cache only positive matches since the table might grow
3388 m_cache[real_isa] = descriptor_sp;
3389 return descriptor_sp;
3390}
3391
3393 ObjCISA isa, ObjCISA &ret_isa) {
3394 Log *log = GetLog(LLDBLog::Types);
3395
3396 LLDB_LOGF(log, "AOCRT::NPI Evaluate(isa = 0x%" PRIx64 ")", (uint64_t)isa);
3397
3398 if ((isa & ~m_objc_debug_isa_class_mask) == 0)
3399 return false;
3400
3401 // If all of the indexed ISA variables are set, then its possible that this
3402 // ISA is indexed, and we should first try to get its value using the index.
3403 // Note, we check these variables first as the ObjC runtime will set at least
3404 // one of their values to 0 if they aren't needed.
3405 if (m_objc_debug_indexed_isa_magic_mask &&
3406 m_objc_debug_indexed_isa_magic_value &&
3407 m_objc_debug_indexed_isa_index_mask &&
3408 m_objc_debug_indexed_isa_index_shift && m_objc_indexed_classes) {
3409 if ((isa & ~m_objc_debug_indexed_isa_index_mask) == 0)
3410 return false;
3411
3412 if ((isa & m_objc_debug_indexed_isa_magic_mask) ==
3413 m_objc_debug_indexed_isa_magic_value) {
3414 // Magic bits are correct, so try extract the index.
3415 uintptr_t index = (isa & m_objc_debug_indexed_isa_index_mask) >>
3416 m_objc_debug_indexed_isa_index_shift;
3417 // If the index is out of bounds of the length of the array then check if
3418 // the array has been updated. If that is the case then we should try
3419 // read the count again, and update the cache if the count has been
3420 // updated.
3421 if (index > m_indexed_isa_cache.size()) {
3422 LLDB_LOGF(log,
3423 "AOCRT::NPI (index = %" PRIu64
3424 ") exceeds cache (size = %" PRIu64 ")",
3425 (uint64_t)index, (uint64_t)m_indexed_isa_cache.size());
3426
3427 Process *process(m_runtime.GetProcess());
3428
3429 ModuleSP objc_module_sp(m_objc_module_wp.lock());
3430 if (!objc_module_sp)
3431 return false;
3432
3433 Status error;
3434 auto objc_indexed_classes_count = ExtractRuntimeGlobalSymbol(
3435 process, ConstString("objc_indexed_classes_count"), objc_module_sp,
3436 error);
3437 if (error.Fail())
3438 return false;
3439
3440 LLDB_LOGF(log, "AOCRT::NPI (new class count = %" PRIu64 ")",
3441 (uint64_t)objc_indexed_classes_count);
3442
3443 if (objc_indexed_classes_count > m_indexed_isa_cache.size()) {
3444 // Read the class entries we don't have. We should just read all of
3445 // them instead of just the one we need as then we can cache those we
3446 // may need later.
3447 auto num_new_classes =
3448 objc_indexed_classes_count - m_indexed_isa_cache.size();
3449 const uint32_t addr_size = process->GetAddressByteSize();
3450 DataBufferHeap buffer(num_new_classes * addr_size, 0);
3451
3452 lldb::addr_t last_read_class =
3453 m_objc_indexed_classes + (m_indexed_isa_cache.size() * addr_size);
3454 size_t bytes_read = process->ReadMemory(
3455 last_read_class, buffer.GetBytes(), buffer.GetByteSize(), error);
3456 if (error.Fail() || bytes_read != buffer.GetByteSize())
3457 return false;
3458
3459 LLDB_LOGF(log, "AOCRT::NPI (read new classes count = %" PRIu64 ")",
3460 (uint64_t)num_new_classes);
3461
3462 // Append the new entries to the existing cache.
3463 DataExtractor data(buffer.GetBytes(), buffer.GetByteSize(),
3464 process->GetByteOrder(),
3465 process->GetAddressByteSize());
3466
3467 lldb::offset_t offset = 0;
3468 for (unsigned i = 0; i != num_new_classes; ++i)
3469 m_indexed_isa_cache.push_back(data.GetAddress(&offset));
3471 }
3472
3473 // If the index is still out of range then this isn't a pointer.
3474 if (index >= m_indexed_isa_cache.size())
3475 return false;
3476
3477 LLDB_LOGF(log, "AOCRT::NPI Evaluate(ret_isa = 0x%" PRIx64 ")",
3478 (uint64_t)m_indexed_isa_cache[index]);
3480 ret_isa = m_indexed_isa_cache[index];
3481 return (ret_isa != 0); // this is a pointer so 0 is not a valid value
3482 }
3483
3484 return false;
3485 }
3486
3487 // Definitely not an indexed ISA, so try to use a mask to extract the pointer
3488 // from the ISA.
3489 if ((isa & m_objc_debug_isa_magic_mask) == m_objc_debug_isa_magic_value) {
3490 ret_isa = isa & m_objc_debug_isa_class_mask;
3491 return (ret_isa != 0); // this is a pointer so 0 is not a valid value
3492 }
3493 return false;
3494}
3495
3499 std::make_shared<AppleObjCTypeEncodingParser>(*this);
3500 return m_encoding_to_type_sp;
3501}
3502
3505 ObjCISA ret = isa;
3506
3507 if (auto *non_pointer_isa_cache = GetNonPointerIsaCache())
3508 non_pointer_isa_cache->EvaluateNonPointerISA(isa, ret);
3509
3510 return ret;
3511}
3512
3515 return true;
3516
3517 static ConstString g_dunder_kCFBooleanFalse("__kCFBooleanFalse");
3518 static ConstString g_dunder_kCFBooleanTrue("__kCFBooleanTrue");
3519 static ConstString g_kCFBooleanFalse("kCFBooleanFalse");
3520 static ConstString g_kCFBooleanTrue("kCFBooleanTrue");
3522 static ModuleSpec corefoundation_module_spec(FileSpec("CoreFoundation"));
3523
3524 ModuleSP corefoundation_module_sp =
3526 corefoundation_module_spec);
3527
3528 if (!corefoundation_module_sp)
3529 return false;
3531 auto get_symbol = [this, &corefoundation_module_sp](
3532 ConstString sym, ConstString real_sym) -> lldb::addr_t {
3533 const Symbol *symbol =
3534 corefoundation_module_sp->FindFirstSymbolWithNameAndType(
3536 if (symbol)
3537 return symbol->GetLoadAddress(&GetProcess()->GetTarget());
3538
3539 symbol = corefoundation_module_sp->FindFirstSymbolWithNameAndType(
3540 real_sym, lldb::eSymbolTypeData);
3541 if (!symbol)
3542 return LLDB_INVALID_ADDRESS;
3543
3544 lldb::addr_t addr = symbol->GetLoadAddress(&GetProcess()->GetTarget());
3545 return llvm::expectedToOptional(GetProcess()->ReadPointerFromMemory(addr))
3546 .value_or(LLDB_INVALID_ADDRESS);
3548
3549 lldb::addr_t false_addr = get_symbol(g_dunder_kCFBooleanFalse, g_kCFBooleanFalse);
3550 lldb::addr_t true_addr = get_symbol(g_dunder_kCFBooleanTrue, g_kCFBooleanTrue);
3551
3552 return (m_CFBoolean_values = {false_addr, true_addr}).operator bool();
3553}
3554
3556 lldb::addr_t &cf_false) {
3558 cf_true = m_CFBoolean_values->second;
3559 cf_false = m_CFBoolean_values->first;
3560 } else
3561 this->AppleObjCRuntime::GetValuesForGlobalCFBooleans(cf_true, cf_false);
3562}
3563
3564void AppleObjCRuntimeV2::ModulesDidLoad(const ModuleList &module_list) {
3567 m_shared_cache_image_headers_up->SetNeedsUpdate();
3569
3574 }
3576 return m_shared_cache_image_headers_up->IsImageLoaded(image_index);
3577
3578 return false;
3579}
3580
3585 }
3587 return m_shared_cache_image_headers_up->GetVersion();
3588
3589 return std::nullopt;
3590}
3591
3594 auto dict_up = std::make_unique<StructuredData::Dictionary>();
3595 dict_up->AddItem("Objective-C runtime version",
3596 std::make_unique<StructuredData::UnsignedInteger>(2));
3597 return dict_up;
3598}
3599
3600#pragma mark Frame recognizers
3601
3602class ObjCExceptionRecognizedStackFrame : public RecognizedStackFrame {
3603public:
3604 ObjCExceptionRecognizedStackFrame(StackFrameSP frame_sp) {
3605 ThreadSP thread_sp = frame_sp->GetThread();
3606 ProcessSP process_sp = thread_sp->GetProcess();
3607
3608 const lldb::ABISP &abi = process_sp->GetABI();
3609 if (!abi)
3610 return;
3612 TypeSystemClangSP scratch_ts_sp =
3613 ScratchTypeSystemClang::GetForTarget(process_sp->GetTarget());
3614 if (!scratch_ts_sp)
3615 return;
3616 CompilerType voidstar =
3617 scratch_ts_sp->GetBasicType(lldb::eBasicTypeVoid).GetPointerType();
3618
3619 ValueList args;
3620 Value input_value;
3621 input_value.SetCompilerType(voidstar);
3622 args.PushValue(input_value);
3623
3624 if (!abi->GetArgumentValues(*thread_sp, args))
3625 return;
3626
3627 addr_t exception_addr = args.GetValueAtIndex(0)->GetScalar().ULongLong();
3628
3629 Value value(exception_addr);
3630 value.SetCompilerType(voidstar);
3631 exception = ValueObjectConstResult::Create(frame_sp.get(), value,
3632 ConstString("exception"));
3634 *exception, eValueTypeVariableArgument);
3635 exception = exception->GetDynamicValue(eDynamicDontRunTarget);
3636
3637 m_arguments = std::make_shared<ValueObjectList>();
3638 m_arguments->Append(exception);
3639
3640 m_stop_desc = "hit Objective-C exception";
3641 }
3642
3644
3645 lldb::ValueObjectSP GetExceptionObject() override { return exception; }
3646};
3647
3648class ObjCExceptionThrowFrameRecognizer : public StackFrameRecognizer {
3650 RecognizeFrame(lldb::StackFrameSP frame) override {
3652 new ObjCExceptionRecognizedStackFrame(frame));
3653 };
3654 std::string GetName() override {
3655 return "ObjC Exception Throw StackFrame Recognizer";
3656 }
3657};
3658
3659static void RegisterObjCExceptionRecognizer(Process *process) {
3660 FileSpec module;
3661 ConstString function;
3662 std::tie(module, function) = AppleObjCRuntime::GetExceptionThrowLocation();
3663 std::vector<ConstString> symbols = {function};
3664
3666 StackFrameRecognizerSP(new ObjCExceptionThrowFrameRecognizer()),
3667 ConstString(module.GetFilename()), symbols,
3669 /*first_instruction_only*/ true);
3670}
static const char * g_get_dynamic_class_info_name
static void RegisterObjCExceptionRecognizer(Process *process)
static llvm::SmallVector< RuntimeGlobalSymbolResult > ExtractRuntimeGlobalSymbolsBatched(Process *process, const ModuleSP &module_sp, llvm::ArrayRef< RuntimeGlobalSymbolSpec > specs)
Batched version of ExtractRuntimeGlobalSymbol.
static const char * g_get_dynamic_class_info3_body
static const char * g_get_dynamic_class_info2_body
static const char * g_get_shared_cache_class_info_name
static const char * g_get_dynamic_class_info3_name
static uint64_t ExtractRuntimeGlobalSymbol(Process *process, ConstString name, const ModuleSP &module_sp, Status &error, bool read_value=true, uint8_t byte_size=0, uint64_t default_value=LLDB_INVALID_ADDRESS, SymbolType sym_type=lldb::eSymbolTypeData)
static constexpr OptionDefinition g_objc_classtable_dump_options[]
static const char * g_get_shared_cache_class_info_body
static const char * g_shared_cache_class_name_funcptr
static const char * g_get_dynamic_class_info_body
static const char * g_get_dynamic_class_info2_name
static const char * g_get_shared_cache_class_info_definitions
static bool DoesProcessHaveSharedCache(Process &process)
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOGF(log,...)
Definition Log.h:389
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
#define LLDB_SCOPED_TIMER()
Definition Timer.h:83
static llvm::StringRef GetName(XcodeSDK::Type type)
Definition XcodeSDK.cpp:21
CommandObjectMultiwordObjC_ClassTable(CommandInterpreter &interpreter)
~CommandObjectMultiwordObjC_ClassTable() override=default
~CommandObjectMultiwordObjC_TaggedPointer_Info() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectMultiwordObjC_TaggedPointer_Info(CommandInterpreter &interpreter)
CommandObjectMultiwordObjC_TaggedPointer(CommandInterpreter &interpreter)
~CommandObjectMultiwordObjC_TaggedPointer() override=default
~CommandObjectMultiwordObjC() override=default
CommandObjectMultiwordObjC(CommandInterpreter &interpreter)
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
void OptionParsingStarting(ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
~CommandObjectObjC_ClassTable_Dump() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectObjC_ClassTable_Dump(CommandInterpreter &interpreter)
const_iterator(RemoteNXMapTable &parent, int index)
lldb_private::Process * m_process
bool ParseHeader(Process *process, lldb::addr_t load_addr)
std::pair< ConstString, ObjCLanguageRuntime::ObjCISA > element
lldb::addr_t GetTableLoadAddress() const
uint32_t GetCount() const
lldb::addr_t GetBucketDataPointer() const
uint32_t GetBucketCount() const
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
void SetRawAddress(lldb::addr_t addr)
Definition Address.h:441
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
UtilityFunction * GetClassInfoUtilityFunction(ExecutionContext &exe_ctx, Helper helper)
Helper ComputeHelper(ExecutionContext &exe_ctx) const
Compute which helper to use.
DescriptorMapUpdateResult UpdateISAToDescriptorMap(RemoteNXMapTable &hash_table)
std::unique_ptr< UtilityFunction > GetClassInfoUtilityFunctionImpl(ExecutionContext &exe_ctx, Helper helper, std::string code, std::string name)
void UpdateSignature(const RemoteNXMapTable &hash_table)
bool NeedsUpdate(Process *process, AppleObjCRuntimeV2 *runtime, RemoteNXMapTable &hash_table)
NonPointerISACache(AppleObjCRuntimeV2 &runtime, const lldb::ModuleSP &objc_module_sp, uint64_t objc_debug_isa_class_mask, uint64_t objc_debug_isa_magic_mask, uint64_t objc_debug_isa_magic_value, uint64_t objc_debug_indexed_isa_magic_mask, uint64_t objc_debug_indexed_isa_magic_value, uint64_t objc_debug_indexed_isa_index_mask, uint64_t objc_debug_indexed_isa_index_shift, lldb::addr_t objc_indexed_classes)
bool EvaluateNonPointerISA(ObjCISA isa, ObjCISA &ret_isa)
ObjCLanguageRuntime::ClassDescriptorSP GetClassDescriptor(ObjCISA isa)
static NonPointerISACache * CreateInstance(AppleObjCRuntimeV2 &runtime, const lldb::ModuleSP &objc_module_sp)
std::map< ObjCISA, ObjCLanguageRuntime::ClassDescriptorSP > m_cache
UtilityFunction * GetClassInfoUtilityFunction(ExecutionContext &exe_ctx)
std::unique_ptr< UtilityFunction > GetClassInfoUtilityFunctionImpl(ExecutionContext &exe_ctx)
static std::unique_ptr< SharedCacheImageHeaders > CreateSharedCacheImageHeaders(AppleObjCRuntimeV2 &runtime)
std::unique_ptr< ObjCLanguageRuntime::ClassDescriptor > GetClassDescriptor(lldb::addr_t ptr) override
TaggedPointerVendorExtended(AppleObjCRuntimeV2 &runtime, uint64_t objc_debug_taggedpointer_mask, uint64_t objc_debug_taggedpointer_ext_mask, uint32_t objc_debug_taggedpointer_slot_shift, uint32_t objc_debug_taggedpointer_ext_slot_shift, uint32_t objc_debug_taggedpointer_slot_mask, uint32_t objc_debug_taggedpointer_ext_slot_mask, uint32_t objc_debug_taggedpointer_payload_lshift, uint32_t objc_debug_taggedpointer_payload_rshift, uint32_t objc_debug_taggedpointer_ext_payload_lshift, uint32_t objc_debug_taggedpointer_ext_payload_rshift, lldb::addr_t objc_debug_taggedpointer_classes, lldb::addr_t objc_debug_taggedpointer_ext_classes)
std::unique_ptr< ObjCLanguageRuntime::ClassDescriptor > GetClassDescriptor(lldb::addr_t ptr) override
TaggedPointerVendorRuntimeAssisted(AppleObjCRuntimeV2 &runtime, uint64_t objc_debug_taggedpointer_mask, uint32_t objc_debug_taggedpointer_slot_shift, uint32_t objc_debug_taggedpointer_slot_mask, uint32_t objc_debug_taggedpointer_payload_lshift, uint32_t objc_debug_taggedpointer_payload_rshift, lldb::addr_t objc_debug_taggedpointer_classes)
std::unique_ptr< ObjCLanguageRuntime::ClassDescriptor > GetClassDescriptor(lldb::addr_t ptr) override
static TaggedPointerVendorV2 * CreateInstance(AppleObjCRuntimeV2 &runtime, const lldb::ModuleSP &objc_module_sp)
llvm::Expected< std::unique_ptr< UtilityFunction > > CreateObjectChecker(std::string name, ExecutionContext &exe_ctx) override
bool IsTaggedPointer(lldb::addr_t ptr) override
uint32_t ParseClassInfoArray(const lldb_private::DataExtractor &data, uint32_t num_class_infos)
llvm::SmallPtrSet< ValueObject *, 8 > ValueObjectSet
bool RealizedClassGenerationCountChanged()
Update the generation count of realized classes.
static llvm::StringRef GetPluginNameStatic()
EncodingToTypeSP GetEncodingToType() override
AppleObjCRuntimeV2(Process *process, const lldb::ModuleSP &objc_module_sp)
bool GetDynamicTypeAndAddress(ValueObject &in_value, lldb::DynamicValueType use_dynamic, TypeAndOrName &class_type_or_name, Address &address, Value::ValueType &value_type, llvm::ArrayRef< uint8_t > &local_buffer) override
This call should return true if it could set the name and/or the type Sets address to the address of ...
NonPointerISACache * GetNonPointerIsaCache()
size_t GetByteOffsetForIvar(CompilerType &parent_ast_type, const char *ivar_name) override
StructuredData::ObjectSP GetLanguageSpecificData(SymbolContext sc) override
Language runtime plugins can use this API to report language-specific runtime information about this ...
SharedCacheClassInfoExtractor m_shared_cache_class_info_extractor
DynamicClassInfoExtractor m_dynamic_class_info_extractor
ClassDescriptorSP GetClassDescriptorFromISA(ObjCISA isa) override
std::unique_ptr< SharedCacheImageHeaders > m_shared_cache_image_headers_up
lldb::addr_t LookupRuntimeSymbol(ConstString name) override
ClassDescriptorSP GetClassDescriptor(ValueObject &valobj) override
void ModulesDidLoad(const ModuleList &module_list) override
Called when modules have been loaded in the process.
bool IsSharedCacheImageLoaded(uint16_t image_index)
std::optional< std::pair< lldb::addr_t, lldb::addr_t > > m_CFBoolean_values
std::unique_ptr< DeclVendor > m_decl_vendor_up
ObjCISA GetPointerISA(ObjCISA isa) override
std::unique_ptr< TaggedPointerVendor > m_tagged_pointer_vendor_up
std::unique_ptr< NonPointerISACache > m_non_pointer_isa_cache_up
void GetValuesForGlobalCFBooleans(lldb::addr_t &cf_true, lldb::addr_t &cf_false) override
lldb::BreakpointResolverSP CreateExceptionResolver(const lldb::BreakpointSP &bkpt, bool catch_bp, bool throw_bp) override
LanguageRuntime * GetPreferredLanguageRuntime(ValueObject &in_value) override
Return the preferred language runtime instance, which in most cases will be the current instance.
std::optional< uint64_t > GetSharedCacheImageHeaderVersion()
ClassDescriptorSP GetClassDescriptorImpl(ValueObject &valobj, ValueObjectSet &seen)
void WarnIfNoClassesCached(SharedCacheWarningReason reason)
static lldb_private::LanguageRuntime * CreateInstance(Process *process, lldb::LanguageType language)
virtual void GetValuesForGlobalCFBooleans(lldb::addr_t &cf_true, lldb::addr_t &cf_false)
static std::tuple< FileSpec, ConstString > GetExceptionThrowLocation()
static ObjCRuntimeVersions GetObjCVersion(Process *process, lldb::ModuleSP &objc_module_sp)
void ModulesDidLoad(const ModuleList &module_list) override
Called when modules have been loaded in the process.
bool CouldHaveDynamicValue(ValueObject &in_value) override
A command line argument class.
Definition Args.h:33
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition Args.h:120
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx.
Definition Args.cpp:273
bool LoadSubCommand(llvm::StringRef cmd_name, const lldb::CommandObjectSP &command_obj) override
CommandObjectMultiword(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
CommandObjectParsed(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
void AddSimpleArgumentList(lldb::CommandArgumentType arg_type, ArgumentRepetitionType repetition_type=eArgRepeatPlain)
void AppendError(llvm::StringRef in_string)
void SetStatus(lldb::ReturnStatus status)
void AppendErrorWithFormatv(const char *format, Args &&...args)
Generic representation of a type in a programming language.
ConstString GetTypeName(bool BaseOnly=false) const
A uniqued constant string class.
Definition ConstString.h:40
bool IsEmpty() const
Test for empty string.
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
const char * AsCString(const char *value_if_empty) const
Get the string value as a C string.
A subclass of DataBuffer that stores a data buffer on the heap.
lldb::offset_t GetByteSize() const override
Get the number of bytes in the data buffer.
An data extractor class.
virtual uint32_t GetU32_unchecked(lldb::offset_t *offset_ptr) const
uint32_t GetU32(lldb::offset_t *offset_ptr) const
Extract a uint32_t value from *offset_ptr.
uint64_t GetAddress(lldb::offset_t *offset_ptr) const
Extract an address from *offset_ptr.
virtual uint64_t GetU64_unchecked(lldb::offset_t *offset_ptr) const
A class to manage flag bits.
Definition Debugger.h:100
static void ReportWarning(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report warning events.
A plug-in interface definition class for dynamic loaders.
void SetUnwindOnError(bool unwind=false)
Definition Target.h:402
void SetTryAllThreads(bool try_others=true)
Definition Target.h:435
void SetTimeout(const Timeout< std::micro > &timeout)
Definition Target.h:423
void SetStopOthers(bool stop_others=true)
Definition Target.h:439
void SetIgnoreBreakpoints(bool ignore=false)
Definition Target.h:406
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
const lldb::ThreadSP & GetThreadSP() const
Get accessor to get the thread shared pointer.
Target & GetTargetRef() const
Returns a reference to the target object.
A file utility class.
Definition FileSpec.h:56
llvm::StringRef GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:248
ValueList GetArgumentValues() const
lldb::ExpressionResults ExecuteFunction(ExecutionContext &exe_ctx, lldb::addr_t *args_addr_ptr, const EvaluateExpressionOptions &options, DiagnosticManager &diagnostic_manager, Value &results)
Run the function this FunctionCaller was created with.
bool WriteFunctionArguments(ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, DiagnosticManager &diagnostic_manager)
Insert the default function argument struct.
void PutCString(const char *cstr)
Definition Log.cpp:162
bool GetVerbose() const
Definition Log.cpp:329
A collection class for Module objects.
Definition ModuleList.h:125
lldb::ModuleSP FindFirstModule(const ModuleSpec &module_spec) const
Finds the first module whose file specification matches module_spec.
void FindSymbolsWithNameAndType(ConstString name, lldb::SymbolType symbol_type, SymbolContextList &sc_list) const
virtual std::unique_ptr< ClassDescriptor > GetClassDescriptor(lldb::addr_t ptr)=0
virtual bool IsPossibleTaggedPointer(lldb::addr_t ptr)=0
std::shared_ptr< ClassDescriptor > ClassDescriptorSP
bool AddClass(ObjCISA isa, const ClassDescriptorSP &descriptor_sp)
std::pair< ISAToDescriptorIterator, ISAToDescriptorIterator > GetDescriptorIteratorPair(bool update_if_needed=true)
virtual TaggedPointerVendor * GetTaggedPointerVendor()
lldb::TypeSP LookupInCompleteClassCache(ConstString &name)
ClassDescriptorSP GetNonKVOClassDescriptor(ValueObject &in_value)
virtual ClassDescriptorSP GetClassDescriptorFromISA(ObjCISA isa)
static ObjCLanguageRuntime * Get(Process &process)
virtual ClassDescriptorSP GetClassDescriptorFromClassName(ConstString class_name)
static lldb::BreakpointPreconditionSP GetBreakpointExceptionPrecondition(lldb::LanguageType language, bool throw_bp)
std::shared_ptr< EncodingToType > EncodingToTypeSP
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:46
bool IsInMemory() const
Returns true if the object file exists only in memory.
Definition ObjectFile.h:691
A command line option parsing protocol class.
Definition Options.h:58
std::vector< Option > m_getopt_table
Definition Options.h:198
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
std::chrono::seconds GetUtilityExpressionTimeout() const
Definition Process.cpp:361
A plug-in interface definition class for debugging a process.
Definition Process.h:367
ThreadList & GetThreadList()
Definition Process.h:2408
lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error)
The public interface to allocating memory in the process.
Definition Process.cpp:2748
virtual size_t ReadMemory(const ProcessAddress &process_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
Definition Process.cpp:2081
llvm::SmallVector< std::optional< uint64_t > > ReadUnsignedIntegersFromMemory(llvm::ArrayRef< lldb::addr_t > addresses, unsigned byte_size)
Use Process::ReadMemoryRanges to efficiently read multiple unsigned integers from memory at once.
Definition Process.cpp:2512
lldb::ByteOrder GetByteOrder() const
Definition Process.cpp:3973
llvm::Expected< lldb::addr_t > ReadPointerFromMemory(lldb::addr_t vm_addr)
Definition Process.cpp:2561
uint64_t ReadUnsignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size, uint64_t fail_value, Status &error)
Reads an unsigned integer of the specified byte size from process memory.
Definition Process.cpp:2500
Status DeallocateMemory(lldb::addr_t ptr)
The public interface to deallocating memory in the process.
Definition Process.cpp:2811
uint32_t GetAddressByteSize() const
Definition Process.cpp:3977
uint32_t GetStopID() const
Definition Process.h:1513
size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error)
Write memory to a process.
Definition Process.cpp:2610
virtual DynamicLoader * GetDynamicLoader()
Get the dynamic loader plug-in for this process.
Definition Process.cpp:3154
llvm::SmallVector< llvm::MutableArrayRef< uint8_t > > ReadMemoryRanges(llvm::ArrayRef< Range< lldb::addr_t, size_t > > ranges, llvm::MutableArrayRef< uint8_t > buffer)
Read from multiple memory ranges and write the results into buffer.
Definition Process.cpp:2112
const lldb::ABISP & GetABI()
Definition Process.cpp:1506
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1266
Process * m_process
Definition Runtime.h:29
Process * GetProcess()
Definition Runtime.h:22
Target & GetTargetRef()
Definition Runtime.h:23
unsigned long long ULongLong(unsigned long long fail_value=0) const
Definition Scalar.cpp:366
unsigned long ULong(unsigned long fail_value=0) const
Definition Scalar.cpp:358
static lldb::TypeSystemClangSP GetForTarget(Target &target, std::optional< IsolatedASTKind > ast_kind=DefaultAST, bool create_on_demand=true)
Returns the scratch TypeSystemClang for the given target.
lldb::SectionSP FindSectionByName(llvm::StringRef section_name) const
Definition Section.cpp:562
void AddRecognizer(lldb::StackFrameRecognizerSP recognizer, ConstString module, llvm::ArrayRef< ConstString > symbols, Mangled::NamePreference symbol_mangling, bool first_instruction_only=true)
Add a new recognizer that triggers on a given symbol name.
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Success() const
Test for success condition.
Definition Status.cpp:303
void Format(const char *format, Args &&... args)
Forwards the arguments to llvm::formatv and writes to the stream.
Definition Stream.h:370
ObjectSP GetValueForKey(llvm::StringRef key) const
std::shared_ptr< Object > ObjectSP
Defines a list of symbol context objects.
bool GetContextAtIndex(size_t idx, SymbolContext &sc) const
Get accessor for a symbol context at index idx.
uint32_t GetSize() const
Get accessor for a symbol context list size.
Defines a symbol context baton that can be handed other debug core functions.
Symbol * symbol
The Symbol for a given query.
lldb::addr_t GetLoadAddress(Target *target) const
Definition Symbol.cpp:605
bool ValueIsAddress() const
Definition Symbol.cpp:191
Address & GetAddressRef()
Definition Symbol.h:78
DynamicClassInfoHelper GetDynamicClassInfoHelper() const
Definition Target.cpp:5529
Debugger & GetDebugger() const
Definition Target.h:1337
StackFrameRecognizerManager & GetFrameRecognizerManager()
Definition Target.h:2004
llvm::Expected< std::unique_ptr< UtilityFunction > > CreateUtilityFunction(std::string expression, std::string name, lldb::LanguageType language, ExecutionContext &exe_ctx)
Creates and installs a UtilityFunction for the given language.
Definition Target.cpp:2870
lldb::PlatformSP GetPlatform()
Definition Target.h:1980
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1254
lldb::ThreadSP GetExpressionExecutionThread()
Sometimes you can find the name of the type corresponding to an object, but we don't have debug infor...
Definition Type.h:780
void SetName(ConstString type_name)
Definition Type.cpp:911
void SetCompilerType(CompilerType compiler_type)
Definition Type.cpp:931
void SetTypeSP(lldb::TypeSP type_sp)
Definition Type.cpp:923
"lldb/Expression/UtilityFunction.h" Encapsulates a bit of source code that provides a function that i...
FunctionCaller * GetFunctionCaller()
void PushValue(const Value &value)
Definition Value.cpp:698
Value * GetValueAtIndex(size_t idx)
Definition Value.cpp:702
static lldb::ValueObjectSP Create(ExecutionContextScope *exe_scope, lldb::ByteOrder byte_order, uint32_t addr_byte_size, lldb::addr_t address=LLDB_INVALID_ADDRESS, ValueObjectManager *manager=nullptr)
These routines create ValueObjectConstResult ValueObjects from various data sources.
static lldb::ValueObjectSP Create(ValueObject &parent, lldb::ValueType type)
lldb::ProcessSP GetProcessSP() const
virtual bool IsBaseClass()
lldb::TargetSP GetTargetSP() const
CompilerType GetCompilerType()
virtual ValueObject * GetParent()
const ExecutionContextRef & GetExecutionContextRef() const
const Scalar & GetScalar() const
See comment on m_scalar to understand what GetScalar returns.
Definition Value.h:114
ValueType
Type that describes Value::m_value.
Definition Value.h:42
@ Scalar
A raw scalar value.
Definition Value.h:46
void SetCompilerType(const CompilerType &compiler_type)
Definition Value.cpp:276
void SetValueType(ValueType value_type)
Definition Value.h:90
uint8_t * GetBytes()
Get a pointer to the data.
Definition DataBuffer.h:108
#define UINT64_MAX
#define LLDB_INVALID_MODULE_VERSION
#define LLDB_OPT_SET_ALL
#define UNUSED_IF_ASSERT_DISABLED(x)
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
#define LLDB_INVALID_IVAR_OFFSET
llvm::Error exception(const char *s=nullptr)
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
const Scalar operator*(Scalar lhs, Scalar rhs)
Definition Scalar.cpp:577
bool operator!=(const Address &lhs, const Address &rhs)
Definition Address.cpp:1011
@ eDynamicClassInfoHelperCopyRealizedClassList
Definition Target.h:83
@ eDynamicClassInfoHelperGetRealizedClassList
Definition Target.h:84
@ eDynamicClassInfoHelperAuto
Definition Target.h:81
@ eDynamicClassInfoHelperRealizedClassesStruct
Definition Target.h:82
std::shared_ptr< lldb_private::ABI > ABISP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::RecognizedStackFrame > RecognizedStackFrameSP
std::shared_ptr< lldb_private::BreakpointResolver > BreakpointResolverSP
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::CommandObject > CommandObjectSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
std::shared_ptr< lldb_private::Platform > PlatformSP
uint64_t offset_t
Definition lldb-types.h:86
LanguageType
Programming language type.
@ eLanguageTypeUnknown
Unknown or invalid language value.
@ eLanguageTypeC
Non-standardized C, such as K&R.
@ eLanguageTypeObjC
Objective-C.
std::shared_ptr< lldb_private::Breakpoint > BreakpointSP
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
std::shared_ptr< lldb_private::Type > TypeSP
std::shared_ptr< lldb_private::Process > ProcessSP
SymbolType
Symbol types.
@ eSymbolTypeObjCIVar
@ eEncodingUint
unsigned integer
@ eReturnStatusFailed
@ eReturnStatusSuccessFinishResult
@ eArgTypeRegularExpression
@ eValueTypeVariableArgument
function argument variables
std::shared_ptr< lldb_private::TypeSystemClang > TypeSystemClangSP
std::shared_ptr< lldb_private::StackFrameRecognizer > StackFrameRecognizerSP
std::shared_ptr< lldb_private::Section > SectionSP
uint64_t addr_t
Definition lldb-types.h:80
@ eDynamicDontRunTarget
bool LLDB_API operator==(const SBAddress &lhs, const SBAddress &rhs)
Definition SBAddress.cpp:62
std::shared_ptr< lldb_private::Module > ModuleSP
static DescriptorMapUpdateResult Success(uint32_t found)
static lldb::addr_t ToRawAddress(const ExecutionContext *exe_ctx, llvm::StringRef s, lldb::addr_t fail_value, Status *error_ptr)
As for ToAddress but do not remove non-address bits from the result.
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition UserID.h:47