]> git.saurik.com Git - apple/security.git/blob - OSX/regressions/test/testenv.m
81f8d59666bbb36906c798435bda4b3f6d374faa
[apple/security.git] / OSX / regressions / test / testenv.m
1 /*
2 * Copyright (c) 2005-2007,2009-2014 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 *
23 * testenv.c
24 */
25
26 /*
27 * This is to fool os services to not provide the Keychain manager
28 * interface tht doens't work since we don't have unified headers
29 * between iOS and OS X. rdar://23405418/
30 */
31 #define __KEYCHAINCORE__ 1
32
33
34 #import <Foundation/Foundation.h>
35 #include <fcntl.h>
36 #include <stdarg.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <sys/stat.h>
40 #include <sys/types.h>
41 #include <unistd.h>
42 #include <stdbool.h>
43 #include <time.h>
44 #include <sys/time.h>
45
46 #include "testmore.h"
47 #include "testenv.h"
48
49 #include <utilities/debugging.h>
50 #include <utilities/SecCFRelease.h>
51 #include <utilities/SecCFWrappers.h>
52 #include <utilities/SecFileLocations.h>
53
54 #include <dispatch/dispatch.h>
55
56
57 int test_strict_bats = 1;
58 int test_verbose = 0;
59 int test_onebatstest = 0;
60 int test_check_leaks = 0;
61 char **test_skip_leaks_test = NULL;
62
63 #ifdef NO_SERVER
64 #include <securityd/spi.h>
65
66 static int current_dir = -1;
67 static char scratch_dir[50];
68 static char *home_var;
69
70 static int
71 rmdir_recursive(const char *path)
72 {
73 #if (!TARGET_IPHONE_SIMULATOR)
74 char command_buf[256];
75 if (strlen(path) + 10 > sizeof(command_buf) || strchr(path, '\''))
76 {
77 fprintf(stdout, "# rmdir_recursive: invalid path: %s", path);
78 return -1;
79 }
80
81 sprintf(command_buf, "/bin/rm -rf '%s'", path);
82 return system(command_buf);
83 #else
84 fprintf(stdout, "# rmdir_recursive: simulator can't rmdir, leaving path: %s\n", path);
85 return 0;
86 #endif
87 }
88 #endif
89
90 static int tests_init(void) {
91 int ok = 0;
92 #ifdef NO_SERVER
93
94 setup("tests_init");
95
96 // Get TMP directory
97 NSError* error = nil;
98 NSString* pid = [NSString stringWithFormat: @"tst-%d", [[NSProcessInfo processInfo] processIdentifier]];
99 NSURL* tmpDirURL = [[NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES] URLByAppendingPathComponent:pid];
100
101 ok = ok(tmpDirURL, "Got error setting up tmp dir: %@", error);
102
103 ok = ok && ok([[NSFileManager defaultManager] createDirectoryAtURL:tmpDirURL
104 withIntermediateDirectories:NO
105 attributes:NULL
106 error:&error],
107 "Failed to make %@: %@", tmpDirURL, error);
108
109 NSURL* libraryURL = [tmpDirURL URLByAppendingPathComponent:@"Library"];
110 NSURL* preferencesURL = [tmpDirURL URLByAppendingPathComponent:@"Preferences"];
111
112 ok = (ok && ok_unix(current_dir = open(".", O_RDONLY), "open")
113 && ok_unix(chdir([tmpDirURL fileSystemRepresentation]), "chdir")
114 && ok_unix(setenv("HOME", [tmpDirURL fileSystemRepresentation], 1), "setenv")
115 && ok(home_var = getenv("HOME"), "getenv"));
116
117 ok = ok && ok([[NSFileManager defaultManager] createDirectoryAtURL:libraryURL
118 withIntermediateDirectories:NO
119 attributes:NULL
120 error:&error],
121 "Failed to make %@: %@", libraryURL, error);
122
123 ok = ok && ok([[NSFileManager defaultManager] createDirectoryAtURL:preferencesURL
124 withIntermediateDirectories:NO
125 attributes:NULL
126 error:&error],
127 "Failed to make %@: %@", preferencesURL, error);
128
129 if (ok > 0)
130 securityd_init((__bridge CFURLRef) tmpDirURL);
131
132 #endif
133
134 return ok;
135 }
136
137 static void
138 tests_end(void)
139 {
140 #ifdef NO_SERVER
141 setup("tests_end");
142
143 /* Restore previous cwd and remove scratch dir. */
144 ok_unix(fchdir(current_dir), "fchdir");
145 ok_unix(close(current_dir), "close");
146 ok_unix(rmdir_recursive(scratch_dir), "rmdir_recursive");
147 #endif
148 }
149
150 static void usage(const char *progname)
151 {
152 fprintf(stderr, "usage: %s [-w][testname [testargs] ...]\n", progname);
153 exit(1);
154 }
155
156 /* run one test, described by test, return info in test struct */
157 static int tests_run_test(struct one_test_s *test, int argc, char * const *argv)
158 {
159 int ch;
160
161 while ((ch = getopt(argc, argv, "v")) != -1)
162 {
163 switch (ch)
164 {
165 case 'v':
166 test_verbose++;
167 break;
168 default:
169 usage(argv[0]);
170 }
171 }
172
173 if (test_onebatstest)
174 fprintf(stdout, "[TEST] %s\n", test->name);
175 else
176 fprintf(stdout, "[BEGIN] %s\n", test->name);
177
178 const char *token = "PASS";
179 if (test->entry == NULL) {
180 fprintf(stdout, "%s:%d: error, no entry\n", __FILE__, __LINE__);
181 test->failed_tests = 1;
182 } else {
183 struct timeval start, stop;
184 gettimeofday(&start, NULL);
185 @autoreleasepool {
186 test->entry(argc, argv);
187 }
188 gettimeofday(&stop, NULL);
189 /* this may overflow... */
190 test->duration = (stop.tv_sec-start.tv_sec) * 1000 + (stop.tv_usec / 1000) - (start.tv_usec / 1000);
191 if (test_plan_ok()) {
192 token = "WARN";
193 }
194 }
195
196 /*
197 * Check if we have any leaks, allow skipping test
198 */
199
200 if (test_check_leaks) {
201 char *cmd = NULL;
202 int ret = 0;
203
204 asprintf(&cmd, "leaks %d >/dev/null", getpid());
205 if (cmd) {
206 ret = system(cmd);
207 free(cmd);
208 }
209 if (ret != 0) {
210 unsigned n = 0;
211 fprintf(stdout, "leaks found in test %s\n", test->name);
212
213 if (test_skip_leaks_test) {
214 while (test_skip_leaks_test[n]) {
215 if (strcmp(test_skip_leaks_test[n], test->name) == 0) {
216 fprintf(stdout, "test %s known to be leaky, skipping\n", test->name);
217 ret = 0;
218 break;
219 }
220 }
221 }
222 if (ret) {
223 token = "FAIL";
224 }
225 } else {
226 if (test_skip_leaks_test) {
227 unsigned n = 0;
228
229 while (test_skip_leaks_test[n]) {
230 if (strcmp(test_skip_leaks_test[n], test->name) == 0) {
231 fprintf(stdout, "leaks didn't find leak in test %s, yet it was ignore\n", test->name);
232 token = "FAIL";
233 break;
234 }
235 }
236 }
237
238 }
239 }
240
241 test_plan_final(&test->failed_tests, &test->todo_pass_tests, &test->todo_tests,
242 &test->actual_tests, &test->planned_tests,
243 &test->plan_file, &test->plan_line);
244 if (test_verbose) {
245 // TODO Use ccperf timing and printing routines that use proper si scaling
246 fprintf(stdout, "%s took %lu ms\n", test->name, test->duration);
247 }
248 if (test->failed_tests) {
249 token = "FAIL";
250 }
251 fprintf(stdout, "[%s] %s\n", token, test->name);
252
253 return test->failed_tests;
254 }
255
256 static int strcmp_under_is_dash(const char *s, const char *t) {
257 for (;;) {
258 char a = *s++, b = *t++;
259 if (a != b) {
260 if (a != '_' || b != '-')
261 return a - b;
262 } else if (a == 0) {
263 return 0;
264 }
265 }
266 }
267
268 static int tests_named_index(const char *testcase)
269 {
270 int i;
271
272 for (i = 0; testlist[i].name; ++i) {
273 if (strcmp_under_is_dash(testlist[i].name, testcase) == 0) {
274 return i;
275 }
276 }
277
278 return -1;
279 }
280
281 static int tests_run_all(int argc, char * const *argv)
282 {
283 int curroptind = optind;
284 int i;
285 int failcount=0;
286
287 for (i = 0; testlist[i].name; ++i) {
288 if(!testlist[i].off) {
289 @autoreleasepool {
290 failcount+=tests_run_test(&testlist[i], argc, argv);
291 }
292 optind = curroptind;
293 }
294 }
295
296 return failcount;
297 }
298
299 static void
300 tests_summary(const char *progname) {
301 int failed_tests = 0;
302 int todo_pass_tests = 0;
303 int todo_tests = 0;
304 int actual_tests = 0;
305 int planned_tests = 0;
306
307 // First compute the totals to help decide if we need to print headers or not.
308 for (int i = 0; testlist[i].name; ++i) {
309 if (!testlist[i].off) {
310 failed_tests += testlist[i].failed_tests;
311 todo_pass_tests += testlist[i].todo_pass_tests;
312 todo_tests += testlist[i].todo_tests;
313 actual_tests += testlist[i].actual_tests;
314 planned_tests += testlist[i].planned_tests;
315 }
316 }
317
318 if (!test_onebatstest) {
319 fprintf(stdout, "[%s] %s\n", failed_tests ? "FAIL" : (actual_tests == planned_tests ? "PASS" : "WARN"), progname);
320 }
321
322 fprintf(stdout, "[SUMMARY]\n");
323
324 // -v -v makes the summary verbose as well.
325 fprintf(stdout, "Test name failed !failed todo total plan\n");
326 if (test_verbose > 1 || failed_tests || todo_pass_tests || actual_tests != planned_tests || (test_verbose && todo_tests)) {
327 fprintf(stdout, "============================================================================================\n");
328 }
329 for (int i = 0; testlist[i].name; ++i) {
330 if (!testlist[i].off) {
331 const char *token = NULL;
332 if (testlist[i].failed_tests) {
333 token = "FAIL";
334 } else if (testlist[i].actual_tests != testlist[i].planned_tests) {
335 token = "WARN";
336 } else if (testlist[i].todo_pass_tests) {
337 token = "WARN";
338 } else if (test_verbose > 1 || (test_verbose && testlist[i].todo_tests)) {
339 token = "PASS";
340 }
341 if (token) {
342 fprintf(stdout, "[%s] %-50s %6d %6d %6d %6d %6d\n", token, testlist[i].name, testlist[i].failed_tests, testlist[i].todo_pass_tests, testlist[i].todo_tests, testlist[i].actual_tests, testlist[i].planned_tests);
343 }
344 }
345 }
346 if (test_verbose > 1 || failed_tests || todo_pass_tests || actual_tests != planned_tests || (test_verbose && todo_tests)) {
347 fprintf(stdout, "============================================================================================\n");
348 }
349 fprintf(stdout, "Totals %6d %6d %6d %6d %6d\n", failed_tests, todo_pass_tests, todo_tests, actual_tests, planned_tests);
350
351 }
352
353 #define ASYNC_LOGGING 0
354 #define DATE_LOGGING 0
355
356 int
357 tests_begin(int argc, char * const *argv) {
358 const char *testcase = NULL;
359 bool initialized = false;
360 __block bool print_security_logs = false;
361 int testix = -1;
362 int failcount = 0;
363 int ch;
364 int loop = 0;
365 int list = 0;
366
367 #if ASYNC_LOGGING
368 dispatch_queue_t show_queue = dispatch_queue_create("sec log queue", DISPATCH_QUEUE_SERIAL);
369 #endif
370
371
372 #if USEOLDLOGGING
373 security_log_handler handle_logs = ^(int level, CFStringRef scope, const char *function, const char *file, int line, CFStringRef message) {
374 time_t now = time(NULL);
375
376 #if DATE_LOGGING
377 char *date = ctime(&now);
378 date[19] = '\0';
379 CFStringRef logStr = CFStringCreateWithFormat(kCFAllocatorDefault, NULL,
380 CFSTR("%s %@{} %s %@\n"), date + 4,
381 scope ? scope : CFSTR(""), function, message);
382 #else
383 CFStringRef logStr = CFStringCreateWithFormat(kCFAllocatorDefault, NULL,
384 CFSTR("%lu %@{} %s %@\n"), now,
385 scope ? scope : CFSTR(""), function, message);
386 #endif
387 #if ASYNC_LOGGING
388 dispatch_async(show_queue, ^{ CFShow(logStr); CFReleaseSafe(logStr); });
389 #else
390 CFShow(logStr);
391 CFReleaseSafe(logStr);
392 #endif
393 };
394 #endif
395
396
397 for (;;) {
398 while (!testcase && (ch = getopt(argc, argv, "blL1vwqs")) != -1)
399 {
400 switch (ch)
401 {
402 case 's':
403 if (!print_security_logs) {
404 //add_security_log_handler(handle_logs);
405 print_security_logs = true;
406 }
407 break;
408
409 case 'b':
410 test_strict_bats = 0;
411 break;
412
413 case 'v':
414 test_verbose++;
415 break;
416
417 case 'w':
418 sleep(100);
419 break;
420 case 'l':
421 loop=1;
422 break;
423 case 'L':
424 list=1;
425 break;
426 case '1':
427 test_onebatstest=1;
428 break;
429 case '?':
430 default:
431 printf("invalid option %c\n",ch);
432 usage(argv[0]);
433 }
434 }
435
436 if (optind < argc) {
437 testix = tests_named_index(argv[optind]);
438 if(testix<0) {
439 printf("invalid test %s\n",argv[optind]);
440 usage(argv[0]);
441 }
442 }
443
444 if(!print_security_logs) secLogDisable();
445
446
447 if (!list && !initialized && !test_onebatstest)
448 fprintf(stdout, "[TEST] %s\n", getprogname());
449 if (testix < 0) {
450 if (!initialized) {
451 tests_init();
452 initialized = true;
453 (void)initialized;
454 if (!list)
455 failcount+=tests_run_all(argc, argv);
456 }
457 break;
458 } else {
459 if (!initialized) {
460 tests_init();
461 initialized = true;
462 for (int i = 0; testlist[i].name; ++i) {
463 testlist[i].off = 1;
464 }
465 }
466 optind++;
467 testlist[testix].off = 0;
468 if (!list) {
469 @autoreleasepool {
470 failcount+=tests_run_test(&testlist[testix], argc, argv);
471 }
472 }
473 testix = -1;
474 }
475 }
476 if (list) {
477 for (int i = 0; testlist[i].name; ++i) {
478 if (!testlist[i].off) {
479 fprintf(stdout, "%s\n", testlist[i].name);
480 }
481 }
482 } else {
483 tests_summary(getprogname());
484 }
485
486 // remove_security_log_handler(handle_logs);
487 fflush(stdout);
488
489
490 /* Cleanups */
491 tests_end();
492
493 if (loop) {
494 printf("Looping until key press 'q'. You can run leaks now.\n");
495 while(getchar()!='q');
496 }
497
498 return failcount;
499 }
500