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