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