]> git.saurik.com Git - apple/objc4.git/blob - test/test.h
objc4-756.2.tar.gz
[apple/objc4.git] / test / test.h
1 // test.h
2 // Common definitions for trivial test harness
3
4
5 #ifndef TEST_H
6 #define TEST_H
7
8 #include <stdio.h>
9 #include <dlfcn.h>
10 #include <stdlib.h>
11 #include <stdarg.h>
12 #include <string.h>
13 #include <libgen.h>
14 #include <unistd.h>
15 #include <pthread.h>
16 #if __cplusplus
17 #include <atomic>
18 using namespace std;
19 #else
20 #include <stdatomic.h>
21 #endif
22 #include <sys/errno.h>
23 #include <sys/param.h>
24 #include <malloc/malloc.h>
25 #include <mach/mach.h>
26 #include <mach/vm_param.h>
27 #include <mach/mach_time.h>
28 #include <objc/objc.h>
29 #include <objc/runtime.h>
30 #include <objc/message.h>
31 #include <objc/objc-abi.h>
32 #include <objc/objc-auto.h>
33 #include <objc/objc-internal.h>
34 #include <TargetConditionals.h>
35
36 #if __has_include(<ptrauth.h>)
37 # include <ptrauth.h>
38 #endif
39
40 #include "../runtime/isa.h"
41
42 #if __cplusplus
43 # define EXTERN_C extern "C"
44 #else
45 # define EXTERN_C /*empty*/
46 #endif
47
48
49 // Test output
50
51 static inline void succeed(const char *name) __attribute__((noreturn));
52 static inline void succeed(const char *name)
53 {
54 if (name) {
55 char path[MAXPATHLEN+1];
56 strcpy(path, name);
57 fprintf(stderr, "OK: %s\n", basename(path));
58 } else {
59 fprintf(stderr, "OK\n");
60 }
61 exit(0);
62 }
63
64 static inline void fail(const char *msg, ...) __attribute__((noreturn));
65 static inline void fail(const char *msg, ...)
66 {
67 if (msg) {
68 char *msg2;
69 asprintf(&msg2, "BAD: %s\n", msg);
70 va_list v;
71 va_start(v, msg);
72 vfprintf(stderr, msg2, v);
73 va_end(v);
74 free(msg2);
75 } else {
76 fprintf(stderr, "BAD\n");
77 }
78 exit(1);
79 }
80
81 #define testassert(cond) \
82 ((void) (((cond) != 0) ? (void)0 : __testassert(#cond, __FILE__, __LINE__)))
83 #define __testassert(cond, file, line) \
84 (fail("failed assertion '%s' at %s:%u", cond, __FILE__, __LINE__))
85
86 /* time-sensitive assertion, disabled under valgrind */
87 #define timecheck(name, time, fast, slow) \
88 if (getenv("VALGRIND") && 0 != strcmp(getenv("VALGRIND"), "NO")) { \
89 /* valgrind; do nothing */ \
90 } else if (time > slow) { \
91 fprintf(stderr, "SLOW: %s %llu, expected %llu..%llu\n", \
92 name, (uint64_t)(time), (uint64_t)(fast), (uint64_t)(slow)); \
93 } else if (time < fast) { \
94 fprintf(stderr, "FAST: %s %llu, expected %llu..%llu\n", \
95 name, (uint64_t)(time), (uint64_t)(fast), (uint64_t)(slow)); \
96 } else { \
97 testprintf("time: %s %llu, expected %llu..%llu\n", \
98 name, (uint64_t)(time), (uint64_t)(fast), (uint64_t)(slow)); \
99 }
100
101
102 // Return true if testprintf() output is enabled.
103 static inline bool testverbose(void)
104 {
105 static int verbose = -1;
106 if (verbose < 0) verbose = atoi(getenv("VERBOSE") ?: "0");
107
108 // VERBOSE=1 prints test harness info only
109 // VERBOSE=2 prints test info
110 return verbose >= 2;
111 }
112
113 // Print debugging info when VERBOSE=2 is set,
114 // without disturbing the test's expected output.
115 static inline void testprintf(const char *msg, ...)
116 {
117 if (msg && testverbose()) {
118 char *msg2;
119 asprintf(&msg2, "VERBOSE: %s", msg);
120 va_list v;
121 va_start(v, msg);
122 vfprintf(stderr, msg2, v);
123 va_end(v);
124 free(msg2);
125 }
126 }
127
128 // complain to output, but don't fail the test
129 // Use when warning that some test is being temporarily skipped
130 // because of something like a compiler bug.
131 static inline void testwarn(const char *msg, ...)
132 {
133 if (msg) {
134 char *msg2;
135 asprintf(&msg2, "WARN: %s\n", msg);
136 va_list v;
137 va_start(v, msg);
138 vfprintf(stderr, msg2, v);
139 va_end(v);
140 free(msg2);
141 }
142 }
143
144 static inline void testnoop() { }
145
146 // Prevent deprecation warnings from some runtime functions.
147
148 static inline void test_objc_flush_caches(Class cls)
149 {
150 #pragma clang diagnostic push
151 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
152 _objc_flush_caches(cls);
153 #pragma clang diagnostic pop
154 }
155 #define _objc_flush_caches(c) test_objc_flush_caches(c)
156
157
158 static inline Class test_class_setSuperclass(Class cls, Class supercls)
159 {
160 #pragma clang diagnostic push
161 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
162 return class_setSuperclass(cls, supercls);
163 #pragma clang diagnostic pop
164 }
165 #define class_setSuperclass(c, s) test_class_setSuperclass(c, s)
166
167
168 static inline void testcollect()
169 {
170 _objc_flush_caches(nil);
171 }
172
173
174 // Synchronously run test code on another thread.
175
176 // The block object is unsafe_unretained because we must not allow
177 // ARC to retain them in non-Foundation tests
178 typedef void(^testblock_t)(void);
179 static __unsafe_unretained testblock_t testcodehack;
180 static inline void *_testthread(void *arg __unused)
181 {
182 testcodehack();
183 return NULL;
184 }
185 static inline void testonthread(__unsafe_unretained testblock_t code)
186 {
187 pthread_t th;
188 testcodehack = code; // force GC not-thread-local, avoid ARC void* casts
189 pthread_create(&th, NULL, _testthread, NULL);
190 pthread_join(th, NULL);
191 }
192
193 /* Make sure libobjc does not call global operator new.
194 Any test that DOES need to call global operator new must
195 `#define TEST_CALLS_OPERATOR_NEW` before including test.h.
196 */
197 #if __cplusplus && !defined(TEST_CALLS_OPERATOR_NEW)
198 #pragma clang diagnostic push
199 #pragma clang diagnostic ignored "-Winline-new-delete"
200 #import <new>
201 inline void* operator new(std::size_t) throw (std::bad_alloc) { fail("called global operator new"); }
202 inline void* operator new[](std::size_t) throw (std::bad_alloc) { fail("called global operator new[]"); }
203 inline void* operator new(std::size_t, const std::nothrow_t&) throw() { fail("called global operator new(nothrow)"); }
204 inline void* operator new[](std::size_t, const std::nothrow_t&) throw() { fail("called global operator new[](nothrow)"); }
205 inline void operator delete(void*) throw() { fail("called global operator delete"); }
206 inline void operator delete[](void*) throw() { fail("called global operator delete[]"); }
207 inline void operator delete(void*, const std::nothrow_t&) throw() { fail("called global operator delete(nothrow)"); }
208 inline void operator delete[](void*, const std::nothrow_t&) throw() { fail("called global operator delete[](nothrow)"); }
209 #pragma clang diagnostic pop
210 #endif
211
212
213 /* Leak checking
214 Fails if total malloc memory in use at leak_check(n)
215 is more than n bytes above that at leak_mark().
216 */
217
218 static inline void leak_recorder(task_t task __unused, void *ctx, unsigned type __unused, vm_range_t *ranges, unsigned count)
219 {
220 size_t *inuse = (size_t *)ctx;
221 while (count--) {
222 *inuse += ranges[count].size;
223 }
224 }
225
226 static inline size_t leak_inuse(void)
227 {
228 size_t total = 0;
229 vm_address_t *zones;
230 unsigned count;
231 malloc_get_all_zones(mach_task_self(), NULL, &zones, &count);
232 for (unsigned i = 0; i < count; i++) {
233 size_t inuse = 0;
234 malloc_zone_t *zone = (malloc_zone_t *)zones[i];
235 if (!zone->introspect || !zone->introspect->enumerator) continue;
236
237 // skip DispatchContinuations because it sometimes claims to be
238 // using lots of memory that then goes away later
239 if (0 == strcmp(zone->zone_name, "DispatchContinuations")) continue;
240
241 zone->introspect->enumerator(mach_task_self(), &inuse, MALLOC_PTR_IN_USE_RANGE_TYPE, (vm_address_t)zone, NULL, leak_recorder);
242 // fprintf(stderr, "%zu in use for zone %s\n", inuse, zone->zone_name);
243 total += inuse;
244 }
245
246 return total;
247 }
248
249
250 static inline void leak_dump_heap(const char *msg)
251 {
252 fprintf(stderr, "%s\n", msg);
253
254 // Make `heap` write to stderr
255 int outfd = dup(STDOUT_FILENO);
256 dup2(STDERR_FILENO, STDOUT_FILENO);
257 pid_t pid = getpid();
258 char cmd[256];
259 // environment variables reset for iOS simulator use
260 sprintf(cmd, "DYLD_LIBRARY_PATH= DYLD_ROOT_PATH= /usr/bin/heap -addresses all %d", (int)pid);
261
262 #pragma clang diagnostic push
263 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
264 system(cmd);
265 #pragma clang diagnostic pop
266
267 dup2(outfd, STDOUT_FILENO);
268 close(outfd);
269 }
270
271 static size_t _leak_start;
272 static inline void leak_mark(void)
273 {
274 testcollect();
275 if (getenv("LEAK_HEAP")) {
276 leak_dump_heap("HEAP AT leak_mark");
277 }
278 _leak_start = leak_inuse();
279 }
280
281 #define leak_check(n) \
282 do { \
283 const char *_check = getenv("LEAK_CHECK"); \
284 size_t inuse; \
285 if (_check && 0 == strcmp(_check, "NO")) break; \
286 testcollect(); \
287 if (getenv("LEAK_HEAP")) { \
288 leak_dump_heap("HEAP AT leak_check"); \
289 } \
290 inuse = leak_inuse(); \
291 if (inuse > _leak_start + n) { \
292 fprintf(stderr, "BAD: %zu bytes leaked at %s:%u " \
293 "(try LEAK_HEAP and HANG_ON_LEAK to debug)\n", \
294 inuse - _leak_start, __FILE__, __LINE__); \
295 if (getenv("HANG_ON_LEAK")) { \
296 fprintf(stderr, "Hanging after leaks detected. " \
297 "Leaks command:\n"); \
298 fprintf(stderr, "leaks %d\n", getpid()); \
299 while (1) sleep(1); \
300 } \
301 } \
302 } while (0)
303
304 // true when running under Guard Malloc
305 static inline bool is_guardmalloc(void)
306 {
307 const char *env = getenv("GUARDMALLOC");
308 return (env && 0 == strcmp(env, "1"));
309 }
310
311 // true when running a debug build of libobjc
312 static inline bool is_debug(void)
313 {
314 static int debugness = -1;
315 if (debugness == -1) {
316 debugness = dlsym(RTLD_DEFAULT, "_objc_isDebugBuild") ? 1 : 0;
317 }
318 return (bool)debugness;
319 }
320
321
322 /* Memory management compatibility macros */
323
324 static id self_fn(id x) __attribute__((used));
325 static id self_fn(id x) { return x; }
326
327 #if __has_feature(objc_arc_weak)
328 // __weak
329 # define WEAK_STORE(dst, val) (dst = (val))
330 # define WEAK_LOAD(src) (src)
331 #else
332 // no __weak
333 # define WEAK_STORE(dst, val) objc_storeWeak((id *)&dst, val)
334 # define WEAK_LOAD(src) objc_loadWeak((id *)&src)
335 #endif
336
337 #if __has_feature(objc_arc)
338 // ARC
339 # define RELEASE_VAR(x) x = nil
340 # define SUPER_DEALLOC()
341 # define RETAIN(x) (self_fn(x))
342 # define RELEASE_VALUE(x) ((void)self_fn(x))
343 # define AUTORELEASE(x) (self_fn(x))
344
345 #else
346 // MRC
347 # define RELEASE_VAR(x) do { [x release]; x = nil; } while (0)
348 # define SUPER_DEALLOC() [super dealloc]
349 # define RETAIN(x) [x retain]
350 # define RELEASE_VALUE(x) [x release]
351 # define AUTORELEASE(x) [x autorelease]
352 #endif
353
354 /* gcc compatibility macros */
355 /* <rdar://problem/9412038> @autoreleasepool should generate objc_autoreleasePoolPush/Pop on 10.7/5.0 */
356 //#if !defined(__clang__)
357 # define PUSH_POOL { void *pool = objc_autoreleasePoolPush();
358 # define POP_POOL objc_autoreleasePoolPop(pool); }
359 //#else
360 //# define PUSH_POOL @autoreleasepool
361 //# define POP_POOL
362 //#endif
363
364 #if __OBJC__
365
366 /* General purpose root class */
367
368 OBJC_ROOT_CLASS
369 @interface TestRoot {
370 @public
371 Class isa;
372 }
373
374 +(void) load;
375 +(void) initialize;
376
377 -(id) self;
378 -(Class) class;
379 -(Class) superclass;
380
381 +(id) new;
382 +(id) alloc;
383 +(id) allocWithZone:(void*)zone;
384 -(id) copy;
385 -(id) mutableCopy;
386 -(id) init;
387 -(void) dealloc;
388 @end
389 @interface TestRoot (RR)
390 -(id) retain;
391 -(oneway void) release;
392 -(id) autorelease;
393 -(unsigned long) retainCount;
394 -(id) copyWithZone:(void *)zone;
395 -(id) mutableCopyWithZone:(void*)zone;
396 @end
397
398 // incremented for each call of TestRoot's methods
399 extern atomic_int TestRootLoad;
400 extern atomic_int TestRootInitialize;
401 extern atomic_int TestRootAlloc;
402 extern atomic_int TestRootAllocWithZone;
403 extern atomic_int TestRootCopy;
404 extern atomic_int TestRootCopyWithZone;
405 extern atomic_int TestRootMutableCopy;
406 extern atomic_int TestRootMutableCopyWithZone;
407 extern atomic_int TestRootInit;
408 extern atomic_int TestRootDealloc;
409 extern atomic_int TestRootRetain;
410 extern atomic_int TestRootRelease;
411 extern atomic_int TestRootAutorelease;
412 extern atomic_int TestRootRetainCount;
413 extern atomic_int TestRootTryRetain;
414 extern atomic_int TestRootIsDeallocating;
415 extern atomic_int TestRootPlusRetain;
416 extern atomic_int TestRootPlusRelease;
417 extern atomic_int TestRootPlusAutorelease;
418 extern atomic_int TestRootPlusRetainCount;
419
420 #endif
421
422
423 // Struct that does not return in registers on any architecture
424
425 struct stret {
426 int a;
427 int b;
428 int c;
429 int d;
430 int e;
431 int f;
432 int g;
433 int h;
434 int i;
435 int j;
436 };
437
438 static inline BOOL stret_equal(struct stret a, struct stret b)
439 {
440 return (a.a == b.a &&
441 a.b == b.b &&
442 a.c == b.c &&
443 a.d == b.d &&
444 a.e == b.e &&
445 a.f == b.f &&
446 a.g == b.g &&
447 a.h == b.h &&
448 a.i == b.i &&
449 a.j == b.j);
450 }
451
452 static struct stret STRET_RESULT __attribute__((used)) = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
453
454
455 #if TARGET_OS_SIMULATOR
456 // Force cwd to executable's directory during launch.
457 // sim used to do this but simctl does not.
458 #include <crt_externs.h>
459 __attribute__((constructor))
460 static void hack_cwd(void)
461 {
462 if (!getenv("HACKED_CWD")) {
463 chdir(dirname((*_NSGetArgv())[0]));
464 setenv("HACKED_CWD", "1", 1);
465 }
466 }
467 #endif
468
469 #endif