cl: cl_mem_flags has CL_MEM_KERNEL_READ_AND_WRITE since 2.0
[piglit.git] / tests / util / piglit-util.c
blob0d5a9a9e4b5e8b6d8261e2c8d5b029256b192beb
1 /*
2 * Copyright (c) The Piglit project 2007
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * on the rights to use, copy, modify, merge, publish, distribute, sub
8 * license, and/or sell copies of the Software, and to permit persons to whom
9 * the Software is furnished to do so, subject to the following conditions:
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
18 * VA LINUX SYSTEM, IBM AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
19 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
20 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
21 * USE OR OTHER DEALINGS IN THE SOFTWARE.
24 #if defined(_WIN32)
25 #ifndef WIN32_LEAN_AND_MEAN
26 #define WIN32_LEAN_AND_MEAN
27 #endif
28 #include <windows.h>
29 #endif
31 #ifdef __linux__
32 #include <sys/types.h>
33 #include <sys/syscall.h>
34 #endif
36 #include <assert.h>
37 #include <math.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <errno.h>
42 #include <inttypes.h>
43 #include <time.h>
45 #if defined(PIGLIT_HAS_POSIX_CLOCK_MONOTONIC) && defined(PIGLIT_HAS_POSIX_TIMER_NOTIFY_THREAD)
46 #include <pthread.h>
47 #include <signal.h>
48 #endif
50 #include "config.h"
51 #if defined(HAVE_SYS_TIME_H) && defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_SETRLIMIT)
52 #include <sys/time.h>
53 #include <sys/resource.h>
54 #define USE_SETRLIMIT
55 #endif
57 #if defined(HAVE_FCNTL_H) && defined(HAVE_SYS_STAT_H) && defined(HAVE_SYS_TYPES_H) && defined(HAVE_UNISTD_H) && !defined(_WIN32)
58 # include <sys/types.h>
59 # include <sys/stat.h>
60 # include <fcntl.h>
61 # include <unistd.h>
62 #else
63 # define USE_STDIO
64 #endif
66 #if defined(HAVE_UNISTD_H)
67 #include <unistd.h> // for usleep
68 #endif
70 #ifdef _MSC_VER
71 #define strcasecmp _stricmp
72 #endif
74 #include "piglit-util.h"
77 #ifndef HAVE_ASPRINTF
79 /* Some versions of MinGW are missing _vscprintf's declaration, although they
80 * still provide the symbol in the import library.
82 #ifdef __MINGW32__
83 _CRTIMP int _vscprintf(const char *format, va_list argptr);
84 #endif
86 int asprintf(char **strp, const char *fmt, ...)
88 va_list args;
89 va_list args_copy;
90 int length;
91 size_t size;
93 va_start(args, fmt);
95 va_copy(args_copy, args);
97 #ifdef _WIN32
98 /* We need to use _vcsprintf to calculate the length as vsnprintf returns -1
99 * if the number of characters to write is greater than count.
101 length = _vscprintf(fmt, args_copy);
102 #else
103 char dummy;
104 length = vsnprintf(&dummy, sizeof dummy, fmt, args_copy);
105 #endif
107 va_end(args_copy);
109 assert(length >= 0);
110 size = length + 1;
112 *strp = malloc(size);
113 if (!*strp) {
114 return -1;
117 va_start(args, fmt);
118 vsnprintf(*strp, size, fmt, args);
119 va_end(args);
121 return length;
124 #endif /* HAVE_ASPRINTF */
127 * \brief Split \a string into an array of strings.
129 * The null-terminated string \a separators is a list of characters at
130 * which to perform the splits. For example, if separators is " ,", then
131 * the function will split the string at each occurrence of ' ' and ','.
133 const char**
134 piglit_split_string_to_array(const char *string, const char *separators)
136 char **strings, *string_copy;
137 int i, length, max_words;
139 length = strlen(string);
140 max_words = length / 2;
141 strings = malloc((sizeof(char*) * (max_words + 1)) +
142 (sizeof(char) * (length + 1)));
143 assert(strings != NULL);
145 string_copy = (char*) &strings[max_words + 1];
146 strcpy(string_copy, string);
148 strings[0] = strtok(string_copy, separators);
149 for (i = 0; strings[i] != NULL; ++i) {
150 strings[i + 1] = strtok(NULL, separators);
153 return (const char**) strings;
156 bool piglit_is_extension_in_array(const char **haystack, const char *needle)
158 if (needle[0] == 0)
159 return false;
161 while (*haystack != NULL) {
162 if (strcmp(*haystack, needle) == 0) {
163 return true;
165 haystack++;
168 return false;
171 bool piglit_is_extension_in_string(const char *haystack, const char *needle)
173 const unsigned needle_len = strlen(needle);
175 if (needle_len == 0)
176 return false;
178 while (true) {
179 const char *const s = strstr(haystack, needle);
181 if (s == NULL)
182 return false;
184 if (s[needle_len] == ' ' || s[needle_len] == '\0') {
185 return true;
188 /* strstr found an extension whose name begins with
189 * needle, but whose name is not equal to needle.
190 * Restart the search at s + needle_len so that we
191 * don't just find the same extension again and go
192 * into an infinite loop.
194 haystack = s + needle_len;
197 return false;
200 /** Returns the line in the program string given the character position. */
201 int piglit_find_line(const char *program, int position)
203 int i, line = 1;
204 for (i = 0; i < position; i++) {
205 if (program[i] == '0')
206 return -1; /* unknown line */
207 if (program[i] == '\n')
208 line++;
210 return line;
213 const char *
214 piglit_result_to_string(enum piglit_result result)
216 switch (result) {
217 case PIGLIT_FAIL: return "fail";
218 case PIGLIT_SKIP: return "skip";
219 case PIGLIT_WARN: return "warn";
220 case PIGLIT_PASS: return "pass";
222 return "Unknown result";
225 void
226 piglit_report_result(enum piglit_result result)
228 const char *result_str = piglit_result_to_string(result);
230 #ifdef PIGLIT_HAS_POSIX_TIMER_NOTIFY_THREAD
231 /* Ensure we only report one result in case we race with timeout */
232 static pthread_mutex_t result_lock = PTHREAD_MUTEX_INITIALIZER;
233 pthread_mutex_lock(&result_lock);
234 #endif
236 fflush(stderr);
238 printf("PIGLIT: {\"result\": \"%s\" }\n", result_str);
239 fflush(stdout);
241 switch(result) {
242 case PIGLIT_PASS:
243 case PIGLIT_SKIP:
244 case PIGLIT_WARN:
245 exit(0);
246 default:
247 exit(1);
251 #ifdef PIGLIT_HAS_POSIX_TIMER_NOTIFY_THREAD
252 static void
253 timeout_expired(union sigval val)
255 piglit_loge("Test timed out.");
256 piglit_report_result(val.sival_int);
258 #endif
260 void
261 piglit_set_timeout(double seconds, enum piglit_result timeout_result)
263 #ifdef PIGLIT_HAS_POSIX_TIMER_NOTIFY_THREAD
264 struct sigevent sev = {
265 .sigev_notify = SIGEV_THREAD,
266 .sigev_notify_function = timeout_expired,
267 .sigev_value = { .sival_int = timeout_result },
269 time_t sec = seconds;
270 struct itimerspec spec = {
271 .it_value = { .tv_sec = sec, .tv_nsec = (seconds - sec) * 1e9 },
273 timer_t timerid;
274 timer_create(CLOCK_MONOTONIC, &sev, &timerid);
275 timer_settime(timerid, 0, &spec, NULL);
276 #else
277 piglit_logi("Cannot abort this test for timeout on this platform");
278 #endif
281 void
282 piglit_report_subtest_result(enum piglit_result result, const char *format, ...)
284 const char *result_str = piglit_result_to_string(result);
285 va_list ap;
287 va_start(ap, format);
289 printf("PIGLIT: {\"subtest\": {\"");
290 vprintf(format, ap);
291 printf("\" : \"%s\"}}\n", result_str);
292 fflush(stdout);
294 va_end(ap);
298 static void
299 piglit_disable_error_message_boxes(void)
301 /* When Windows' error message boxes are disabled for this process (as
302 * is always the case when running through `piglit run`) we disable CRT
303 * message boxes too.
305 * This will disable the CRT message boxes for the main executable, but
306 * it will not disable message boxes for assertion failures inside
307 * OpenGL ICD, unless this test's executable and the OpenGL ICD DLL are
308 * both dynamically linked to the same CRT DLL. If the OpenGL ICD is
309 * statically linked to the CRT then it must do these calls itself.
311 #ifdef _WIN32
312 UINT uMode;
313 #if _WIN32_WINNT >= 0x0600
314 uMode = GetErrorMode();
315 #else
316 uMode = SetErrorMode(0);
317 SetErrorMode(uMode);
318 #endif
319 if (uMode & SEM_FAILCRITICALERRORS) {
320 /* Disable assertion failure message box.
321 * http://msdn.microsoft.com/en-us/library/sas1dkb2.aspx
323 _set_error_mode(_OUT_TO_STDERR);
325 #endif /* _WIN32 */
329 static void
330 piglit_set_line_buffering(void)
332 /* Windows doesn't immediately flush stdout/stderr after printf
333 * calls as we see on Linux. To get immediate flushing, we disable
334 * buffering here.
336 #ifdef _WIN32
337 setbuf(stdout, NULL);
338 setbuf(stderr, NULL);
339 #endif
343 void
344 piglit_general_init(void)
346 piglit_disable_error_message_boxes();
347 piglit_set_line_buffering();
351 void
352 piglit_set_rlimit(unsigned long lim)
354 #if defined(USE_SETRLIMIT) && defined(RLIMIT_AS)
355 struct rlimit rl;
356 if (getrlimit(RLIMIT_AS, &rl) != -1) {
357 piglit_logi("Address space limit = %lu, max = %lu",
358 (unsigned long) rl.rlim_cur,
359 (unsigned long) rl.rlim_max);
361 if (rl.rlim_max > lim) {
362 piglit_logi("Resetting limit to %lu", lim);
364 rl.rlim_cur = lim;
365 rl.rlim_max = lim;
366 if (setrlimit(RLIMIT_AS, &rl) == -1) {
367 piglit_loge("Could not set rlimit "
368 "due to: %s (%d)",
369 strerror(errno), errno);
373 #else
374 piglit_loge("Cannot reset rlimit on this platform");
375 #endif
378 /* Merges the PASS/FAIL/SKIP for @subtest into the overall result
379 * @all.
381 * The @all should start out initialized to PIGLIT_SKIP.
383 void
384 piglit_merge_result(enum piglit_result *all, enum piglit_result subtest)
386 switch (subtest) {
387 case PIGLIT_FAIL:
388 *all = PIGLIT_FAIL;
389 break;
390 case PIGLIT_WARN:
391 if (*all == PIGLIT_SKIP || *all == PIGLIT_PASS)
392 *all = PIGLIT_WARN;
393 break;
394 case PIGLIT_PASS:
395 if (*all == PIGLIT_SKIP)
396 *all = PIGLIT_PASS;
397 break;
398 case PIGLIT_SKIP:
399 break;
403 char *piglit_load_text_file(const char *file_name, unsigned *size)
405 char *text = NULL;
407 #if defined(USE_STDIO)
408 FILE *fp;
410 # ifdef HAVE_FOPEN_S
411 errno_t err;
413 if (file_name == NULL) {
414 return NULL;
417 err = fopen_s(&fp, file_name, "r");
419 if (err || (fp == NULL)) {
420 return NULL;
422 # else
423 fp = fopen(file_name, "r");
424 if (fp == NULL) {
425 return NULL;
427 # endif
429 if (fseek(fp, 0, SEEK_END) == 0) {
430 size_t len = (size_t) ftell(fp);
431 rewind(fp);
433 text = malloc(len + 1);
434 if (text != NULL) {
435 size_t total_read = 0;
437 do {
438 size_t bytes = fread(text + total_read, 1,
439 len - total_read, fp);
441 total_read += bytes;
442 if (feof(fp)) {
443 break;
446 if (ferror(fp)) {
447 free(text);
448 text = NULL;
449 break;
451 } while (total_read < len);
453 if (text != NULL) {
454 text[total_read] = '\0';
457 if (size != NULL) {
458 *size = total_read;
463 fclose(fp);
464 return text;
465 #else
466 struct stat st;
467 int fd = open(file_name, O_RDONLY);
469 if (fd < 0) {
470 return NULL;
473 if (fstat(fd, & st) == 0) {
474 ssize_t total_read = 0;
476 if (!S_ISREG(st.st_mode) &&
477 !S_ISLNK(st.st_mode)) {
478 /* not a regular file or symlink */
479 close(fd);
480 return NULL;
483 text = malloc(st.st_size + 1);
484 if (text != NULL) {
485 do {
486 ssize_t bytes = read(fd, text + total_read,
487 st.st_size - total_read);
488 if (bytes < 0) {
489 free(text);
490 text = NULL;
491 break;
494 if (bytes == 0) {
495 break;
498 total_read += bytes;
499 } while (total_read < st.st_size);
501 text[total_read] = '\0';
502 if (size != NULL) {
503 *size = total_read;
508 close(fd);
510 return text;
511 #endif
514 const char*
515 piglit_source_dir(void)
518 const char *s = getenv("PIGLIT_SOURCE_DIR");
520 if (s == NULL) {
521 piglit_loge("env var PIGLIT_SOURCE_DIR is undefined");
522 piglit_report_result(PIGLIT_FAIL);
525 return s;
528 size_t
529 piglit_join_paths(char buf[], size_t buf_size, int n, ...)
531 char *dest = buf;
532 size_t size_written = 0;
534 int i;
535 va_list va;
537 if (buf_size == 0 || n < 1)
538 return 0;
540 va_start(va, n);
542 i = 0;
543 while (true) {
544 const char *p = va_arg(va, const char*);
546 while (*p != 0) {
547 if (size_written == buf_size - 1)
548 goto write_null;
550 *dest = *p;
551 ++dest;
552 ++p;
553 ++size_written;
556 ++i;
557 if (i == n)
558 break;
560 *dest = PIGLIT_PATH_SEP;
561 ++dest;
562 ++size_written;
565 write_null:
566 *dest = '\0';
567 ++size_written;
569 va_end(va);
570 return size_written;
573 bool
574 piglit_time_is_monotonic(void)
576 #ifdef PIGLIT_HAS_POSIX_CLOCK_MONOTONIC
577 struct timespec t;
578 int r = clock_gettime(CLOCK_MONOTONIC, &t);
580 return r == 0 || (r == -1 && errno != EINVAL);
581 #else
582 return false;
583 #endif
586 int64_t
587 piglit_time_get_nano(void)
589 #if !defined(_WIN32)
590 struct timeval tv;
592 #ifdef PIGLIT_HAS_POSIX_CLOCK_MONOTONIC
593 struct timespec t;
594 int r = clock_gettime(CLOCK_MONOTONIC, &t);
596 if (r == 0 || (r == -1 && errno != EINVAL))
597 return (t.tv_sec * INT64_C(1000000000)) + t.tv_nsec;
598 #endif
600 gettimeofday(&tv, NULL);
601 return tv.tv_usec * INT64_C(1000) + tv.tv_sec * INT64_C(1000000000);
602 #else
603 static LARGE_INTEGER frequency;
604 LARGE_INTEGER counter;
606 if (!frequency.QuadPart)
607 QueryPerformanceFrequency(&frequency);
608 QueryPerformanceCounter(&counter);
609 return counter.QuadPart * INT64_C(1000000000)/frequency.QuadPart;
610 #endif
613 int64_t
614 piglit_delay_ns(int64_t time_ns)
616 int64_t start = piglit_time_get_nano();
617 int64_t end;
619 #ifdef __linux__
620 struct timespec ts;
622 ts.tv_sec = time_ns / 1000000000LL;
623 ts.tv_nsec = time_ns - ts.tv_sec * 1000000000LL;
625 while (nanosleep(&ts, &ts) == -1 && errno == EINTR)
627 #elif defined(_MSC_VER)
628 Sleep(time_ns / 1000000);
629 #else
630 usleep(time_ns / 1000);
631 #endif
633 end = piglit_time_get_nano();
635 return end - start;
639 * Search for an argument with the given name in the argument list.
640 * If it is found, remove it and return true.
642 bool
643 piglit_strip_arg(int *argc, char *argv[], const char *arg)
645 int i;
646 for (i = 1; i < *argc; i++) {
647 if (strcmp(argv[i], arg) != 0)
648 continue;
650 for (i += 1; i < *argc; ++i)
651 argv[i-1] = argv[i];
653 *argc -= 1;
654 return true;
657 return false;
660 void
661 piglit_parse_subtest_args(int *argc, char *argv[],
662 const struct piglit_subtest *subtests,
663 const char ***out_selected_subtests,
664 size_t *out_num_selected_subtests)
666 int j;
667 const char **selected_subtests = NULL;
668 size_t num_selected_subtests = 0;
670 const char *usage =
671 "usage:\n"
672 " %1$s\n"
673 " Run all subtests.\n"
674 "\n"
675 " %1$s -list-subtests\n"
676 " List all subtests.\n"
677 "\n"
678 " %1$s -subtest SUBTEST [-subtest SUBTEST [...]]\n"
679 " Run only the given subtests.\n"
680 "\n"
681 " %1$s -h|--help\n"
682 " Print this help message.\n"
685 for (j = 1; j < *argc; j++) {
686 if (streq(argv[j], "-h") || streq(argv[j], "--help")) {
687 printf(usage, basename(argv[0]));
688 exit(EXIT_SUCCESS);
689 } else if (streq(argv[j], "-subtest")) {
690 int i;
692 ++j;
693 if (j >= *argc) {
694 piglit_loge("-subtest requires an argument");
695 piglit_report_result(PIGLIT_FAIL);
698 if (!piglit_find_subtest(subtests, argv[j])) {
699 piglit_loge("Test defines no subtest with "
700 "name '%s'", argv[j]);
701 piglit_report_result(PIGLIT_FAIL);
704 selected_subtests =
705 realloc(selected_subtests,
706 (num_selected_subtests + 1)
707 * sizeof(char*));
708 selected_subtests[num_selected_subtests] = argv[j];
709 ++num_selected_subtests;
711 /* Remove 2 arguments from the command line. */
712 for (i = j + 1; i < *argc; i++) {
713 argv[i - 2] = argv[i];
715 *argc -= 2;
716 j -= 2;
717 } else if (streq(argv[j], "-list-subtests")) {
718 int i;
720 if (subtests == NULL) {
721 piglit_loge("Test defines no subtests!");
722 exit(EXIT_FAILURE);
725 for (i = 0; !PIGLIT_SUBTEST_END(&subtests[i]); ++i) {
726 printf("%s: %s\n",
727 subtests[i].option,
728 subtests[i].name);
731 exit(EXIT_SUCCESS);
735 *out_selected_subtests = selected_subtests;
736 *out_num_selected_subtests = num_selected_subtests;
740 const struct piglit_subtest *
741 piglit_find_subtest(const struct piglit_subtest *subtests, const char *name)
743 unsigned i;
744 if (!subtests)
745 return NULL;
746 for (i = 0; !PIGLIT_SUBTEST_END(&subtests[i]); i++) {
747 if (strcmp(subtests[i].option, name) == 0)
748 return &subtests[i];
751 return NULL;
754 enum piglit_result
755 piglit_run_selected_subtests(const struct piglit_subtest *all_subtests,
756 const char **selected_subtests,
757 size_t num_selected_subtests,
758 enum piglit_result previous_result)
760 enum piglit_result result = previous_result;
762 /* print JSON list of subtests */
763 printf("PIGLIT: {\"enumerate subtests\": [");
764 if (num_selected_subtests) {
765 const char *prefix = "";
766 for (int i = 0; i < num_selected_subtests; i++) {
767 const char *const name = selected_subtests[i];
768 const struct piglit_subtest *subtest =
769 piglit_find_subtest(all_subtests, name);
771 if (subtest == NULL) {
772 printf("]}\n");
773 fflush(stdout);
774 piglit_loge("Unknown subtest \"%s\"", name);
775 piglit_report_result(PIGLIT_FAIL);
777 printf("%s\"%s\"", prefix, name);
778 prefix = ", ";
781 } else {
782 const char *prefix = "";
783 for (int i = 0; !PIGLIT_SUBTEST_END(&all_subtests[i]); i++) {
784 printf("%s\"%s\"", prefix, all_subtests[i].name);
785 prefix = ", ";
788 printf("]}\n");
789 fflush(stdout);
791 if (num_selected_subtests) {
792 for (int i = 0; i < num_selected_subtests; i++) {
793 enum piglit_result subtest_result;
794 const char *const name = selected_subtests[i];
795 const struct piglit_subtest *subtest =
796 piglit_find_subtest(all_subtests, name);
798 subtest_result = subtest->subtest_func(subtest->data);
799 piglit_report_subtest_result(subtest_result, "%s",
800 subtest->name);
802 piglit_merge_result(&result, subtest_result);
804 } else {
805 for (int i = 0; !PIGLIT_SUBTEST_END(&all_subtests[i]); i++) {
806 const enum piglit_result subtest_result =
807 all_subtests[i].subtest_func(all_subtests[i].data);
808 piglit_report_subtest_result(subtest_result, "%s",
809 all_subtests[i].name);
811 piglit_merge_result(&result, subtest_result);
815 return result;
818 void
819 piglit_register_subtests(const char *names[])
821 printf("PIGLIT: {\"enumerate subtests\": [\"%s\"", names[0]);
822 for (int i = 1; names[i]; i++) {
823 printf(", \"%s\"", names[i]);
825 printf("]}\n");
826 fflush(stdout);
829 uint64_t
830 piglit_gettid(void)
832 #ifdef __linux__
833 return syscall(SYS_gettid);
834 #else
835 return 0;
836 #endif
840 size_t
841 piglit_get_page_size(void)
843 #if defined(_WIN32)
844 SYSTEM_INFO system_info;
845 GetSystemInfo(&system_info);
846 return system_info.dwPageSize;
847 #else
848 return sysconf(_SC_PAGESIZE);
849 #endif
853 void *
854 piglit_alloc_aligned(size_t alignment, size_t size)
856 #if defined(_WIN32)
857 return _aligned_malloc(size, alignment);
858 #else
859 void *p;
860 if (posix_memalign(&p, alignment, size) != 0) {
861 return NULL;
863 return p;
864 #endif
868 void
869 piglit_free_aligned(void *p)
871 #if defined(_WIN32)
872 _aligned_free(p);
873 #else
874 free(p);
875 #endif
880 * \brief Reads an environment variable and interprets its value as a boolean.
882 * Recognizes 0/false/no and 1/true/yes. Other values result in the
883 * \a default_value.
885 bool
886 piglit_env_var_as_boolean(const char *var_name, bool default_value)
888 const char *str = getenv(var_name);
889 if (str == NULL)
890 return default_value;
892 if (strcmp(str, "1") == 0 ||
893 strcasecmp(str, "true") == 0 ||
894 strcasecmp(str, "yes") == 0) {
895 return true;
896 } else if (strcmp(str, "0") == 0 ||
897 strcasecmp(str, "false") == 0 ||
898 strcasecmp(str, "no") == 0) {
899 return false;
900 } else {
901 return default_value;