-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathruntests.c
1789 lines (1621 loc) · 54.3 KB
/
runtests.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Run a set of tests, reporting results.
*
* Test suite driver that runs a set of tests implementing a subset of the
* Test Anything Protocol (TAP) and reports the results.
*
* Any bug reports, bug fixes, and improvements are very much welcome and
* should be sent to the e-mail address below. This program is part of C TAP
* Harness <https://www.eyrie.org/~eagle/software/c-tap-harness/>.
*
* Copyright 2000-2001, 2004, 2006-2019, 2022 Russ Allbery <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* SPDX-License-Identifier: MIT
*/
/*
* Usage:
*
* runtests [-hv] [-b <build-dir>] [-s <source-dir>] -l <test-list>
* runtests [-hv] [-b <build-dir>] [-s <source-dir>] <test> [<test> ...]
* runtests -o [-h] [-b <build-dir>] [-s <source-dir>] <test>
*
* In the first case, expects a list of executables located in the given file,
* one line per executable, possibly followed by a space-separated list of
* options. For each one, runs it as part of a test suite, reporting results.
* In the second case, use the same infrastructure, but run only the tests
* listed on the command line.
*
* Test output should start with a line containing the number of tests
* (numbered from 1 to this number), optionally preceded by "1..", although
* that line may be given anywhere in the output. Each additional line should
* be in the following format:
*
* ok <number>
* not ok <number>
* ok <number> # skip
* not ok <number> # todo
*
* where <number> is the number of the test. An optional comment is permitted
* after the number if preceded by whitespace. ok indicates success, not ok
* indicates failure. "# skip" and "# todo" are a special cases of a comment,
* and must start with exactly that formatting. They indicate the test was
* skipped for some reason (maybe because it doesn't apply to this platform)
* or is testing something known to currently fail. The text following either
* "# skip" or "# todo" and whitespace is the reason.
*
* As a special case, the first line of the output may be in the form:
*
* 1..0 # skip some reason
*
* which indicates that this entire test case should be skipped and gives a
* reason.
*
* Any other lines are ignored, although for compliance with the TAP protocol
* all lines other than the ones in the above format should be sent to
* standard error rather than standard output and start with #.
*
* This is a subset of TAP as documented in Test::Harness::TAP or
* TAP::Parser::Grammar, which comes with Perl.
*
* If the -o option is given, instead run a single test and display all of its
* output. This is intended for use with failing tests so that the person
* running the test suite can get more details about what failed.
*
* If built with the C preprocessor symbols C_TAP_SOURCE and C_TAP_BUILD
* defined, C TAP Harness will export those values in the environment so that
* tests can find the source and build directory and will look for tests under
* both directories. These paths can also be set with the -b and -s
* command-line options, which will override anything set at build time.
*
* If the -v option is given, or the C_TAP_VERBOSE environment variable is set,
* display the full output of each test as it runs rather than showing a
* summary of the results of each test.
*/
/* Required for fdopen(), getopt(), and putenv(). */
#if defined(__STRICT_ANSI__) || defined(PEDANTIC)
# ifndef _XOPEN_SOURCE
# define _XOPEN_SOURCE 500
# endif
#endif
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
/* sys/time.h must be included before sys/resource.h on some platforms. */
#include <sys/resource.h>
/* AIX 6.1 (and possibly later) doesn't have WCOREDUMP. */
#ifndef WCOREDUMP
# define WCOREDUMP(status) ((unsigned) (status) &0x80)
#endif
/*
* POSIX requires that these be defined in <unistd.h>, but they're not always
* available. If one of them has been defined, all the rest almost certainly
* have.
*/
#ifndef STDIN_FILENO
# define STDIN_FILENO 0
# define STDOUT_FILENO 1
# define STDERR_FILENO 2
#endif
/*
* Used for iterating through arrays. Returns the number of elements in the
* array (useful for a < upper bound in a for loop).
*/
#define ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0]))
/*
* The source and build versions of the tests directory. This is used to set
* the C_TAP_SOURCE and C_TAP_BUILD environment variables (and the SOURCE and
* BUILD environment variables set for backward compatibility) and find test
* programs, if set. Normally, this should be set as part of the build
* process to the test subdirectories of $(abs_top_srcdir) and
* $(abs_top_builddir) respectively.
*/
#ifndef C_TAP_SOURCE
# define C_TAP_SOURCE NULL
#endif
#ifndef C_TAP_BUILD
# define C_TAP_BUILD NULL
#endif
/* Test status codes. */
enum test_status {
TEST_FAIL,
TEST_PASS,
TEST_SKIP,
TEST_INVALID
};
/* Really, just a boolean, but this is more self-documenting. */
enum test_verbose {
CONCISE = 0,
VERBOSE = 1
};
/* Indicates the state of our plan. */
enum plan_status {
PLAN_INIT, /* Nothing seen yet. */
PLAN_FIRST, /* Plan seen before any tests. */
PLAN_PENDING, /* Test seen and no plan yet. */
PLAN_FINAL /* Plan seen after some tests. */
};
/* Error exit statuses for test processes. */
#define CHILDERR_DUP 100 /* Couldn't redirect stderr or stdout. */
#define CHILDERR_EXEC 101 /* Couldn't exec child process. */
#define CHILDERR_STDIN 102 /* Couldn't open stdin file. */
#define CHILDERR_STDERR 103 /* Couldn't open stderr file. */
/* Structure to hold data for a set of tests. */
struct testset {
char *file; /* The file name of the test. */
char **command; /* The argv vector to run the command. */
enum plan_status plan; /* The status of our plan. */
unsigned long count; /* Expected count of tests. */
unsigned long current; /* The last seen test number. */
unsigned int length; /* The length of the last status message. */
unsigned long passed; /* Count of passing tests. */
unsigned long failed; /* Count of failing lists. */
unsigned long skipped; /* Count of skipped tests (passed). */
unsigned long allocated; /* The size of the results table. */
enum test_status *results; /* Table of results by test number. */
unsigned int aborted; /* Whether the set was aborted. */
unsigned int reported; /* Whether the results were reported. */
int status; /* The exit status of the test. */
unsigned int all_skipped; /* Whether all tests were skipped. */
char *reason; /* Why all tests were skipped. */
};
/* Structure to hold a linked list of test sets. */
struct testlist {
struct testset *ts;
struct testlist *next;
};
/*
* Usage message. Should be used as a printf format with four arguments: the
* path to runtests, given three times, and the usage_description. This is
* split into variables to satisfy the pedantic ISO C90 limit on strings.
*/
static const char usage_message[] = "\
Usage: %s [-hv] [-b <build-dir>] [-s <source-dir>] <test> ...\n\
%s [-hv] [-b <build-dir>] [-s <source-dir>] -l <test-list>\n\
%s -o [-h] [-b <build-dir>] [-s <source-dir>] <test>\n\
\n\
Options:\n\
-b <build-dir> Set the build directory to <build-dir>\n\
%s";
static const char usage_extra[] = "\
-l <list> Take the list of tests to run from <test-list>\n\
-o Run a single test rather than a list of tests\n\
-s <source-dir> Set the source directory to <source-dir>\n\
-v Show the full output of each test\n\
\n\
runtests normally runs each test listed on the command line. With the -l\n\
option, it instead runs every test listed in a file. With the -o option,\n\
it instead runs a single test and shows its complete output.\n";
/*
* Header used for test output. %s is replaced by the file name of the list
* of tests.
*/
static const char banner[] = "\n\
Running all tests listed in %s. If any tests fail, run the failing\n\
test program with runtests -o to see more details.\n\n";
/* Header for reports of failed tests. */
static const char header[] = "\n\
Failed Set Fail/Total (%) Skip Stat Failing Tests\n\
-------------------------- -------------- ---- ---- ------------------------";
/* Include the file name and line number in malloc failures. */
#define xcalloc(n, type) \
((type *) x_calloc((n), sizeof(type), __FILE__, __LINE__))
#define xmalloc(size) ((char *) x_malloc((size), __FILE__, __LINE__))
#define xstrdup(p) x_strdup((p), __FILE__, __LINE__)
#define xstrndup(p, size) x_strndup((p), (size), __FILE__, __LINE__)
#define xreallocarray(p, n, type) \
((type *) x_reallocarray((p), (n), sizeof(type), __FILE__, __LINE__))
/*
* __attribute__ is available in gcc 2.5 and later, but only with gcc 2.7
* could you use the __format__ form of the attributes, which is what we use
* (to avoid confusion with other macros).
*/
#ifndef __attribute__
# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 7)
# define __attribute__(spec) /* empty */
# endif
#endif
/*
* We use __alloc_size__, but it was only available in fairly recent versions
* of GCC. Suppress warnings about the unknown attribute if GCC is too old.
* We know that we're GCC at this point, so we can use the GCC variadic macro
* extension, which will still work with versions of GCC too old to have C99
* variadic macro support.
*/
#if !defined(__attribute__) && !defined(__alloc_size__)
# if defined(__GNUC__) && !defined(__clang__)
# if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 3)
# define __alloc_size__(spec, args...) /* empty */
# endif
# endif
#endif
/*
* Suppress the argument to __malloc__ in Clang (not supported in at least
* version 13) and GCC versions prior to 11.
*/
#if !defined(__attribute__) && !defined(__malloc__)
# if defined(__clang__) || __GNUC__ < 11
# define __malloc__(dalloc) __malloc__
# endif
#endif
/*
* LLVM and Clang pretend to be GCC but don't support all of the __attribute__
* settings that GCC does. For them, suppress warnings about unknown
* attributes on declarations. This unfortunately will affect the entire
* compilation context, but there's no push and pop available.
*/
#if !defined(__attribute__) && (defined(__llvm__) || defined(__clang__))
# pragma GCC diagnostic ignored "-Wattributes"
#endif
/* Declare internal functions that benefit from compiler attributes. */
static void die(const char *, ...)
__attribute__((__nonnull__, __noreturn__, __format__(printf, 1, 2)));
static void sysdie(const char *, ...)
__attribute__((__nonnull__, __noreturn__, __format__(printf, 1, 2)));
static void *x_calloc(size_t, size_t, const char *, int)
__attribute__((__alloc_size__(1, 2), __malloc__(free), __nonnull__));
static void *x_malloc(size_t, const char *, int)
__attribute__((__alloc_size__(1), __malloc__(free), __nonnull__));
static void *x_reallocarray(void *, size_t, size_t, const char *, int)
__attribute__((__alloc_size__(2, 3), __malloc__(free), __nonnull__(4)));
static char *x_strdup(const char *, const char *, int)
__attribute__((__malloc__(free), __nonnull__));
static char *x_strndup(const char *, size_t, const char *, int)
__attribute__((__malloc__(free), __nonnull__));
/*
* Report a fatal error and exit.
*/
static void
die(const char *format, ...)
{
va_list args;
fflush(stdout);
fprintf(stderr, "runtests: ");
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
fprintf(stderr, "\n");
exit(1);
}
/*
* Report a fatal error, including the results of strerror, and exit.
*/
static void
sysdie(const char *format, ...)
{
int oerrno;
va_list args;
oerrno = errno;
fflush(stdout);
fprintf(stderr, "runtests: ");
va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
fprintf(stderr, ": %s\n", strerror(oerrno));
exit(1);
}
/*
* Allocate zeroed memory, reporting a fatal error and exiting on failure.
*/
static void *
x_calloc(size_t n, size_t size, const char *file, int line)
{
void *p;
n = (n > 0) ? n : 1;
size = (size > 0) ? size : 1;
p = calloc(n, size);
if (p == NULL)
sysdie("failed to calloc %lu bytes at %s line %d",
(unsigned long) size, file, line);
return p;
}
/*
* Allocate memory, reporting a fatal error and exiting on failure.
*/
static void *
x_malloc(size_t size, const char *file, int line)
{
void *p;
p = malloc(size);
if (p == NULL)
sysdie("failed to malloc %lu bytes at %s line %d",
(unsigned long) size, file, line);
return p;
}
/*
* Reallocate memory, reporting a fatal error and exiting on failure.
*
* We should technically use SIZE_MAX here for the overflow check, but
* SIZE_MAX is C99 and we're only assuming C89 + SUSv3, which does not
* guarantee that it exists. They do guarantee that UINT_MAX exists, and we
* can assume that UINT_MAX <= SIZE_MAX. And we should not be allocating
* anything anywhere near that large.
*
* (In theory, C89 and C99 permit size_t to be smaller than unsigned int, but
* I disbelieve in the existence of such systems and they will have to cope
* without overflow checks.)
*/
static void *
x_reallocarray(void *p, size_t n, size_t size, const char *file, int line)
{
n = (n > 0) ? n : 1;
size = (size > 0) ? size : 1;
if (UINT_MAX / n <= size)
sysdie("realloc too large at %s line %d", file, line);
p = realloc(p, n * size);
if (p == NULL)
sysdie("failed to realloc %lu bytes at %s line %d",
(unsigned long) (n * size), file, line);
return p;
}
/*
* Copy a string, reporting a fatal error and exiting on failure.
*/
static char *
x_strdup(const char *s, const char *file, int line)
{
char *p;
size_t len;
len = strlen(s) + 1;
p = (char *) malloc(len);
if (p == NULL)
sysdie("failed to strdup %lu bytes at %s line %d", (unsigned long) len,
file, line);
memcpy(p, s, len);
return p;
}
/*
* Copy the first n characters of a string, reporting a fatal error and
* existing on failure.
*
* Avoid using the system strndup function since it may not exist (on Mac OS
* X, for example), and there's no need to introduce another portability
* requirement.
*/
char *
x_strndup(const char *s, size_t size, const char *file, int line)
{
const char *p;
size_t len;
char *copy;
/* Don't assume that the source string is nul-terminated. */
for (p = s; (size_t) (p - s) < size && *p != '\0'; p++)
;
len = (size_t) (p - s);
copy = (char *) malloc(len + 1);
if (copy == NULL)
sysdie("failed to strndup %lu bytes at %s line %d",
(unsigned long) len, file, line);
memcpy(copy, s, len);
copy[len] = '\0';
return copy;
}
/*
* Form a new string by concatenating multiple strings. The arguments must be
* terminated by (const char *) 0.
*
* This function only exists because we can't assume asprintf. We can't
* simulate asprintf with snprintf because we're only assuming SUSv3, which
* does not require that snprintf with a NULL buffer return the required
* length. When those constraints are relaxed, this should be ripped out and
* replaced with asprintf or a more trivial replacement with snprintf.
*/
static char *
concat(const char *first, ...)
{
va_list args;
char *result;
const char *string;
size_t offset;
size_t length = 0;
/*
* Find the total memory required. Ensure we don't overflow length. We
* aren't guaranteed to have SIZE_MAX, so use UINT_MAX as an acceptable
* substitute (see the x_nrealloc comments).
*/
va_start(args, first);
for (string = first; string != NULL; string = va_arg(args, const char *)) {
if (length >= UINT_MAX - strlen(string)) {
errno = EINVAL;
sysdie("strings too long in concat");
}
length += strlen(string);
}
va_end(args);
length++;
/* Create the string. */
result = xmalloc(length);
va_start(args, first);
offset = 0;
for (string = first; string != NULL; string = va_arg(args, const char *)) {
memcpy(result + offset, string, strlen(string));
offset += strlen(string);
}
va_end(args);
result[offset] = '\0';
return result;
}
/*
* Given a struct timeval, return the number of seconds it represents as a
* double. Use difftime() to convert a time_t to a double.
*/
static double
tv_seconds(const struct timeval *tv)
{
return difftime(tv->tv_sec, 0) + (double) tv->tv_usec * 1e-6;
}
/*
* Given two struct timevals, return the difference in seconds.
*/
static double
tv_diff(const struct timeval *tv1, const struct timeval *tv0)
{
return tv_seconds(tv1) - tv_seconds(tv0);
}
/*
* Given two struct timevals, return the sum in seconds as a double.
*/
static double
tv_sum(const struct timeval *tv1, const struct timeval *tv2)
{
return tv_seconds(tv1) + tv_seconds(tv2);
}
/*
* Given a pointer to a string, skip any leading whitespace and return a
* pointer to the first non-whitespace character.
*/
static const char *
skip_whitespace(const char *p)
{
while (isspace((unsigned char) (*p)))
p++;
return p;
}
/*
* Given a pointer to a string, skip any non-whitespace characters and return
* a pointer to the first whitespace character, or to the end of the string.
*/
static const char *
skip_non_whitespace(const char *p)
{
while (*p != '\0' && !isspace((unsigned char) (*p)))
p++;
return p;
}
/*
* Start a program, connecting its stdout to a pipe on our end and its stderr
* to /dev/null, and storing the file descriptor to read from in the two
* argument. Returns the PID of the new process. Errors are fatal.
*/
static pid_t
test_start(char *const *command, int *fd)
{
int fds[2], infd, errfd;
pid_t child;
/* Create a pipe used to capture the output from the test program. */
if (pipe(fds) == -1) {
puts("ABORTED");
fflush(stdout);
sysdie("can't create pipe");
}
/* Fork a child process, massage the file descriptors, and exec. */
child = fork();
switch (child) {
case -1:
puts("ABORTED");
fflush(stdout);
sysdie("can't fork");
/* In the child. Set up our standard output. */
case 0:
close(fds[0]);
close(STDOUT_FILENO);
if (dup2(fds[1], STDOUT_FILENO) < 0)
_exit(CHILDERR_DUP);
close(fds[1]);
/* Point standard input at /dev/null. */
close(STDIN_FILENO);
infd = open("/dev/null", O_RDONLY);
if (infd < 0)
_exit(CHILDERR_STDIN);
if (infd != STDIN_FILENO) {
if (dup2(infd, STDIN_FILENO) < 0)
_exit(CHILDERR_DUP);
close(infd);
}
/* Point standard error at /dev/null. */
close(STDERR_FILENO);
errfd = open("/dev/null", O_WRONLY);
if (errfd < 0)
_exit(CHILDERR_STDERR);
if (errfd != STDERR_FILENO) {
if (dup2(errfd, STDERR_FILENO) < 0)
_exit(CHILDERR_DUP);
close(errfd);
}
/* Now, exec our process. */
if (execv(command[0], command) == -1)
_exit(CHILDERR_EXEC);
break;
/* In parent. Close the extra file descriptor. */
default:
close(fds[1]);
break;
}
*fd = fds[0];
return child;
}
/*
* Back up over the output saying what test we were executing.
*/
static void
test_backspace(struct testset *ts)
{
unsigned int i;
if (!isatty(STDOUT_FILENO))
return;
for (i = 0; i < ts->length; i++)
putchar('\b');
for (i = 0; i < ts->length; i++)
putchar(' ');
for (i = 0; i < ts->length; i++)
putchar('\b');
ts->length = 0;
}
/*
* Allocate or resize the array of test results to be large enough to contain
* the test number in.
*/
static void
resize_results(struct testset *ts, unsigned long n)
{
unsigned long i;
size_t s;
/* If there's already enough space, return quickly. */
if (n <= ts->allocated)
return;
/*
* If no space has been allocated, do the initial allocation. Otherwise,
* resize. Start with 32 test cases and then add 1024 with each resize to
* try to reduce the number of reallocations.
*/
if (ts->allocated == 0) {
s = (n > 32) ? n : 32;
ts->results = xcalloc(s, enum test_status);
} else {
s = (n > ts->allocated + 1024) ? n : ts->allocated + 1024;
ts->results = xreallocarray(ts->results, s, enum test_status);
}
/* Set the results for the newly-allocated test array. */
for (i = ts->allocated; i < s; i++)
ts->results[i] = TEST_INVALID;
ts->allocated = s;
}
/*
* Report an invalid test number and set the appropriate flags. Pulled into a
* separate function since we do this in several places.
*/
static void
invalid_test_number(struct testset *ts, long n, enum test_verbose verbose)
{
if (!verbose)
test_backspace(ts);
printf("ABORTED (invalid test number %ld)\n", n);
ts->aborted = 1;
ts->reported = 1;
}
/*
* Read the plan line of test output, which should contain the range of test
* numbers. We may initialize the testset structure here if we haven't yet
* seen a test. Return true if initialization succeeded and the test should
* continue, false otherwise.
*/
static int
test_plan(const char *line, struct testset *ts, enum test_verbose verbose)
{
long n;
/*
* Accept a plan without the leading 1.. for compatibility with older
* versions of runtests. This will only be allowed if we've not yet seen
* a test result.
*/
line = skip_whitespace(line);
if (strncmp(line, "1..", 3) == 0)
line += 3;
/*
* Get the count and check it for validity.
*
* If we have something of the form "1..0 # skip foo", the whole file was
* skipped; record that. If we do skip the whole file, zero out all of
* our statistics, since they're no longer relevant.
*
* strtol is called with a second argument to advance the line pointer
* past the count to make it simpler to detect the # skip case.
*/
n = strtol(line, (char **) &line, 10);
if (n == 0) {
line = skip_whitespace(line);
if (*line == '#') {
line = skip_whitespace(line + 1);
if (strncasecmp(line, "skip", 4) == 0) {
line = skip_whitespace(line + 4);
if (*line != '\0') {
ts->reason = xstrdup(line);
ts->reason[strlen(ts->reason) - 1] = '\0';
}
ts->all_skipped = 1;
ts->aborted = 1;
ts->count = 0;
ts->passed = 0;
ts->skipped = 0;
ts->failed = 0;
return 0;
}
}
}
if (n <= 0) {
puts("ABORTED (invalid test count)");
ts->aborted = 1;
ts->reported = 1;
return 0;
}
/*
* If we are doing lazy planning, check the plan against the largest test
* number that we saw and fail now if we saw a check outside the plan
* range.
*/
if (ts->plan == PLAN_PENDING && (unsigned long) n < ts->count) {
invalid_test_number(ts, (long) ts->count, verbose);
return 0;
}
/*
* Otherwise, allocated or resize the results if needed and update count,
* and then record that we've seen a plan.
*/
resize_results(ts, (unsigned long) n);
ts->count = (unsigned long) n;
if (ts->plan == PLAN_INIT)
ts->plan = PLAN_FIRST;
else if (ts->plan == PLAN_PENDING)
ts->plan = PLAN_FINAL;
return 1;
}
/*
* Given a single line of output from a test, parse it and return the success
* status of that test. Anything printed to stdout not matching the form
* /^(not )?ok \d+/ is ignored. Sets ts->current to the test number that just
* reported status.
*/
static void
test_checkline(const char *line, struct testset *ts, enum test_verbose verbose)
{
enum test_status status = TEST_PASS;
const char *bail;
char *end;
long number;
unsigned long current;
int outlen;
/* Before anything, check for a test abort. */
bail = strstr(line, "Bail out!");
if (bail != NULL) {
bail = skip_whitespace(bail + strlen("Bail out!"));
if (*bail != '\0') {
size_t length;
length = strlen(bail);
if (bail[length - 1] == '\n')
length--;
if (!verbose)
test_backspace(ts);
printf("ABORTED (%.*s)\n", (int) length, bail);
ts->reported = 1;
}
ts->aborted = 1;
return;
}
/*
* If the given line isn't newline-terminated, it was too big for an
* fgets(), which means ignore it.
*/
if (line[strlen(line) - 1] != '\n')
return;
/* If the line begins with a hash mark, ignore it. */
if (line[0] == '#')
return;
/* If we haven't yet seen a plan, look for one. */
if (ts->plan == PLAN_INIT && isdigit((unsigned char) (*line))) {
if (!test_plan(line, ts, verbose))
return;
} else if (strncmp(line, "1..", 3) == 0) {
if (ts->plan == PLAN_PENDING) {
if (!test_plan(line, ts, verbose))
return;
} else {
if (!verbose)
test_backspace(ts);
puts("ABORTED (multiple plans)");
ts->aborted = 1;
ts->reported = 1;
return;
}
}
/* Parse the line, ignoring something we can't parse. */
if (strncmp(line, "not ", 4) == 0) {
status = TEST_FAIL;
line += 4;
}
if (strncmp(line, "ok", 2) != 0)
return;
line = skip_whitespace(line + 2);
errno = 0;
number = strtol(line, &end, 10);
if (errno != 0 || end == line)
current = ts->current + 1;
else if (number <= 0) {
invalid_test_number(ts, number, verbose);
return;
} else
current = (unsigned long) number;
if (current > ts->count && ts->plan == PLAN_FIRST) {
invalid_test_number(ts, (long) current, verbose);
return;
}
/* We have a valid test result. Tweak the results array if needed. */
if (ts->plan == PLAN_INIT || ts->plan == PLAN_PENDING) {
ts->plan = PLAN_PENDING;
resize_results(ts, current);
if (current > ts->count)
ts->count = current;
}
/*
* Handle directives. We should probably do something more interesting
* with unexpected passes of todo tests.
*/
while (isdigit((unsigned char) (*line)))
line++;
line = skip_whitespace(line);
if (*line == '#') {
line = skip_whitespace(line + 1);
if (strncasecmp(line, "skip", 4) == 0)
status = TEST_SKIP;
if (strncasecmp(line, "todo", 4) == 0)
status = (status == TEST_FAIL) ? TEST_SKIP : TEST_FAIL;
}
/* Make sure that the test number is in range and not a duplicate. */
if (ts->results[current - 1] != TEST_INVALID) {
if (!verbose)
test_backspace(ts);
printf("ABORTED (duplicate test number %lu)\n", current);
ts->aborted = 1;
ts->reported = 1;
return;
}
/* Good results. Increment our various counters. */
switch (status) {
case TEST_PASS:
ts->passed++;
break;
case TEST_FAIL:
ts->failed++;
break;
case TEST_SKIP:
ts->skipped++;
break;
case TEST_INVALID:
break;
}
ts->current = current;
ts->results[current - 1] = status;
if (!verbose && isatty(STDOUT_FILENO)) {
test_backspace(ts);
if (ts->plan == PLAN_PENDING)
outlen = printf("%lu/?", current);
else
outlen = printf("%lu/%lu", current, ts->count);
ts->length = (outlen >= 0) ? (unsigned int) outlen : 0;
fflush(stdout);
}
}
/*
* Print out a range of test numbers, returning the number of characters it
* took up. Takes the first number, the last number, the number of characters
* already printed on the line, and the limit of number of characters the line
* can hold. Add a comma and a space before the range if chars indicates that
* something has already been printed on the line, and print ... instead if
* chars plus the space needed would go over the limit (use a limit of 0 to
* disable this).
*/
static unsigned int
test_print_range(unsigned long first, unsigned long last, unsigned long chars,
unsigned int limit)
{
unsigned int needed = 0;
unsigned long n;
for (n = first; n > 0; n /= 10)
needed++;
if (last > first) {
for (n = last; n > 0; n /= 10)
needed++;
needed++;
}
if (chars > 0)
needed += 2;
if (limit > 0 && chars + needed > limit) {
needed = 0;
if (chars <= limit) {
if (chars > 0) {
printf(", ");
needed += 2;
}
printf("...");
needed += 3;
}
} else {
if (chars > 0)
printf(", ");
if (last > first)
printf("%lu-", first);
printf("%lu", last);
}
return needed;
}
/*
* Summarize a single test set. The second argument is 0 if the set exited
* cleanly, a positive integer representing the exit status if it exited
* with a non-zero status, and a negative integer representing the signal
* that terminated it if it was killed by a signal.
*/
static void
test_summarize(struct testset *ts, int status)
{
unsigned long i;
unsigned long missing = 0;