2 // Common definitions for trivial test harness
20 #include <stdatomic.h>
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>
36 #if __has_include(<ptrauth.h>)
40 #include "../runtime/isa.h"
43 # define EXTERN_C extern "C"
45 # define EXTERN_C /*empty*/
51 static inline void succeed(const char *name
) __attribute__((noreturn
));
52 static inline void succeed(const char *name
)
55 char path
[MAXPATHLEN
+1];
57 fprintf(stderr
, "OK: %s\n", basename(path
));
59 fprintf(stderr
, "OK\n");
64 static inline void fail(const char *msg
, ...) __attribute__((noreturn
));
65 static inline void fail(const char *msg
, ...)
69 asprintf(&msg2
, "BAD: %s\n", msg
);
72 vfprintf(stderr
, msg2
, v
);
76 fprintf(stderr
, "BAD\n");
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__))
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)); \
97 testprintf("time: %s %llu, expected %llu..%llu\n", \
98 name, (uint64_t)(time), (uint64_t)(fast), (uint64_t)(slow)); \
102 // Return true if testprintf() output is enabled.
103 static inline bool testverbose(void)
105 static int verbose
= -1;
106 if (verbose
< 0) verbose
= atoi(getenv("VERBOSE") ?: "0");
108 // VERBOSE=1 prints test harness info only
109 // VERBOSE=2 prints test info
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
, ...)
117 if (msg
&& testverbose()) {
119 asprintf(&msg2
, "VERBOSE: %s", msg
);
122 vfprintf(stderr
, msg2
, v
);
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
, ...)
135 asprintf(&msg2
, "WARN: %s\n", msg
);
138 vfprintf(stderr
, msg2
, v
);
144 static inline void testnoop() { }
146 // Prevent deprecation warnings from some runtime functions.
148 static inline void test_objc_flush_caches(Class cls
)
150 #pragma clang diagnostic push
151 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
152 _objc_flush_caches(cls
);
153 #pragma clang diagnostic pop
155 #define _objc_flush_caches(c) test_objc_flush_caches(c)
158 static inline Class
test_class_setSuperclass(Class cls
, Class supercls
)
160 #pragma clang diagnostic push
161 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
162 return class_setSuperclass(cls
, supercls
);
163 #pragma clang diagnostic pop
165 #define class_setSuperclass(c, s) test_class_setSuperclass(c, s)
168 static inline void testcollect()
170 _objc_flush_caches(nil
);
174 // Synchronously run test code on another thread.
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
)
185 static inline void testonthread(__unsafe_unretained testblock_t code
)
188 testcodehack
= code
; // force GC not-thread-local, avoid ARC void* casts
189 pthread_create(&th
, NULL
, _testthread
, NULL
);
190 pthread_join(th
, NULL
);
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.
197 #if __cplusplus && !defined(TEST_CALLS_OPERATOR_NEW)
198 #pragma clang diagnostic push
199 #pragma clang diagnostic ignored "-Winline-new-delete"
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
214 Fails if total malloc memory in use at leak_check(n)
215 is more than n bytes above that at leak_mark().
218 static inline void leak_recorder(task_t task __unused
, void *ctx
, unsigned type __unused
, vm_range_t
*ranges
, unsigned count
)
220 size_t *inuse
= (size_t *)ctx
;
222 *inuse
+= ranges
[count
].size
;
226 static inline size_t leak_inuse(void)
231 malloc_get_all_zones(mach_task_self(), NULL
, &zones
, &count
);
232 for (unsigned i
= 0; i
< count
; i
++) {
234 malloc_zone_t
*zone
= (malloc_zone_t
*)zones
[i
];
235 if (!zone
->introspect
|| !zone
->introspect
->enumerator
) continue;
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;
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);
250 static inline void leak_dump_heap(const char *msg
)
252 fprintf(stderr
, "%s\n", msg
);
254 // Make `heap` write to stderr
255 int outfd
= dup(STDOUT_FILENO
);
256 dup2(STDERR_FILENO
, STDOUT_FILENO
);
257 pid_t pid
= getpid();
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
);
262 #pragma clang diagnostic push
263 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
265 #pragma clang diagnostic pop
267 dup2(outfd
, STDOUT_FILENO
);
271 static size_t _leak_start
;
272 static inline void leak_mark(void)
275 if (getenv("LEAK_HEAP")) {
276 leak_dump_heap("HEAP AT leak_mark");
278 _leak_start
= leak_inuse();
281 #define leak_check(n) \
283 const char *_check = getenv("LEAK_CHECK"); \
285 if (_check && 0 == strcmp(_check, "NO")) break; \
287 if (getenv("LEAK_HEAP")) { \
288 leak_dump_heap("HEAP AT leak_check"); \
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); \
304 // true when running under Guard Malloc
305 static inline bool is_guardmalloc(void)
307 const char *env
= getenv("GUARDMALLOC");
308 return (env
&& 0 == strcmp(env
, "1"));
311 // true when running a debug build of libobjc
312 static inline bool is_debug(void)
314 static int debugness
= -1;
315 if (debugness
== -1) {
316 debugness
= dlsym(RTLD_DEFAULT
, "_objc_isDebugBuild") ? 1 : 0;
318 return (bool)debugness
;
322 /* Memory management compatibility macros */
324 static id
self_fn(id x
) __attribute__((used
));
325 static id
self_fn(id x
) { return x
; }
327 #if __has_feature(objc_arc_weak)
329 # define WEAK_STORE(dst, val) (dst = (val))
330 # define WEAK_LOAD(src) (src)
333 # define WEAK_STORE(dst, val) objc_storeWeak((id *)&dst, val)
334 # define WEAK_LOAD(src) objc_loadWeak((id *)&src)
337 #if __has_feature(objc_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))
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]
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); }
360 //# define PUSH_POOL @autoreleasepool
366 /* General purpose root class */
369 @interface TestRoot
{
383 +(id
) allocWithZone
:(void*)zone
;
389 @interface
TestRoot (RR
)
391 -(oneway
void) release
;
393 -(unsigned long) retainCount
;
394 -(id
) copyWithZone
:(void *)zone
;
395 -(id
) mutableCopyWithZone
:(void*)zone
;
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
;
423 // Struct that does not return in registers on any architecture
438 static inline BOOL
stret_equal(struct stret a
, struct stret b
)
440 return (a
.a
== b
.a
&&
452 static struct stret STRET_RESULT
__attribute__((used
)) = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
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)
462 if (!getenv("HACKED_CWD")) {
463 chdir(dirname((*_NSGetArgv())[0]));
464 setenv("HACKED_CWD", "1", 1);