|
| 1 | +// RUN: %empty-directory(%t) |
| 2 | +// RUN: %target-clang %s -isysroot %sdk -L%swift_obj_root/lib/swift/%target-os-abi -lswiftCore -o %t/objc-getclass |
| 3 | +// RUN: %target-codesign %t/objc-getclass |
| 4 | +// RUN: %target-run %t/objc-getclass %S/Inputs/objc-getclass.txt |
| 5 | + |
| 6 | +// REQUIRES: executable_test |
| 7 | +// REQUIRES: objc_interop |
| 8 | + |
| 9 | +#include <objc/runtime.h> |
| 10 | +#include <dlfcn.h> |
| 11 | +#include <stdio.h> |
| 12 | +#include <ctype.h> |
| 13 | +#include <errno.h> |
| 14 | +#include <string.h> |
| 15 | + |
| 16 | +static BOOL dummyHook(const char * _Nonnull name, |
| 17 | + Class _Nullable * _Nonnull outClass) { |
| 18 | + return NO; |
| 19 | +} |
| 20 | + |
| 21 | +int main(int argc, char **argv) { |
| 22 | + if (argc != 2) { |
| 23 | + fprintf(stderr, "usage: objc-getclass <input.txt>\n" |
| 24 | + "\n" |
| 25 | + "Test demangling class names to get classes.\n"); |
| 26 | + return 0; |
| 27 | + } |
| 28 | + |
| 29 | + // Find the class-by-mangled-name hook |
| 30 | + objc_hook_getClass getObjCClassByMangledName = NULL; |
| 31 | + |
| 32 | + if (__builtin_available(macOS 10.14.4, iOS 12.2, tvOS 12.2, watchOS 5.2, *)) { |
| 33 | + objc_hook_getClass dummy = NULL; |
| 34 | + objc_setHook_getClass(dummyHook, &getObjCClassByMangledName); |
| 35 | + objc_setHook_getClass(getObjCClassByMangledName, &dummy); |
| 36 | + } else { |
| 37 | + fprintf(stderr, "objc-getclass: macOS version is too old\n"); |
| 38 | + return 1; |
| 39 | + } |
| 40 | + |
| 41 | + // Open the input file |
| 42 | + FILE *fp = fopen(argv[1], "rt"); |
| 43 | + if (!fp) { |
| 44 | + fprintf(stderr, "objc-getclass: unable to open \"%s\" - %s\n", |
| 45 | + argv[1], strerror(errno)); |
| 46 | + } |
| 47 | + |
| 48 | + // Input file is a list of manglings; we don't really care what classes they |
| 49 | + // resolve to here; this test is about whether or not they actually crash or |
| 50 | + // assert. |
| 51 | + char *line = NULL; |
| 52 | + size_t linecap = 0; |
| 53 | + ssize_t linelen = 0; |
| 54 | + |
| 55 | + while ((linelen = getline(&line, &linecap, fp)) > 0) { |
| 56 | + char *mangling = line; |
| 57 | + |
| 58 | + // Trim whitespace |
| 59 | + while (isspace(*mangling)) |
| 60 | + ++mangling; |
| 61 | + |
| 62 | + char *end = line + linelen; |
| 63 | + while (end > line && isspace(end[-1])) |
| 64 | + --end; |
| 65 | + *end = '\0'; |
| 66 | + |
| 67 | + // Skip comments and blank lines |
| 68 | + if (*mangling == '#' || !*mangling) |
| 69 | + continue; |
| 70 | + |
| 71 | + // Try to get a class |
| 72 | + Class outClass = nil; |
| 73 | + BOOL result = getObjCClassByMangledName(mangling, &outClass); |
| 74 | + |
| 75 | + if (result) |
| 76 | + printf("%s -> %s\n", mangling, class_getName(outClass)); |
| 77 | + else |
| 78 | + printf("%s not found\n", mangling); |
| 79 | + } |
| 80 | + |
| 81 | + fclose(fp); |
| 82 | + |
| 83 | + return 0; |
| 84 | +} |
0 commit comments