xref: /openbsd-src/regress/lib/libc/dirname/dirname_test.c (revision 46035553bfdd96e63c94e32da0210227ec2e3cf1)
1 /*
2  * Copyright (c) 2007 Bret S. Lambert <blambert@gsipt.net>
3  *
4  * Public domain.
5  */
6 
7 #include <sys/param.h>
8 
9 #include <libgen.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include <limits.h>
13 #include <errno.h>
14 #include <err.h>
15 
16 int
17 main(void)
18 {
19 	char path[2 * MAXPATHLEN];
20 	char dname[128];
21 	const char *dir = "junk";
22 	const char *fname = "/file.name.ext";
23 	char *str;
24 	int i;
25 
26 	/* Test normal functioning */
27 	strlcpy(path, "/", sizeof(path));
28 	strlcpy(dname, "/", sizeof(dname));
29 	strlcat(path, dir, sizeof(path));
30 	strlcat(dname, dir, sizeof(dname));
31 	strlcat(path, fname, sizeof(path));
32 	str = dirname(path);
33 	if (strcmp(str, dname) != 0)
34 		errx(1, "0: dirname(%s) = %s != %s", path, str, dname);
35 
36 	/*
37 	 * There are four states that require special handling:
38 	 *
39 	 * 1) path is NULL
40 	 * 2) path is the empty string
41 	 * 3) path is composed entirely of slashes
42 	 * 4) the resulting name is larger than MAXPATHLEN
43 	 *
44 	 * The first two cases require that a pointer
45 	 * to the string "." be returned.
46 	 *
47 	 * The third case requires that a pointer
48 	 * to the string "/" be returned.
49 	 *
50 	 * The final case requires that NULL be returned
51 	 * and errno * be set to ENAMETOOLONG.
52 	 */
53 	/* Case 1 */
54 	str = dirname(NULL);
55 	if (strcmp(str, ".") != 0)
56 		errx(1, "1: dirname(NULL) = %s != .", str);
57 
58 	/* Case 2 */
59 	strlcpy(path, "", sizeof(path));
60 	str = dirname(path);
61 	if (strcmp(str, ".") != 0)
62 		errx(1, "2: dirname(%s) = %s != .", path, str);
63 
64 	/* Case 3 */
65 	for (i = 0; i < MAXPATHLEN - 1; i++)
66 		strlcat(path, "/", sizeof(path));	/* path cleared above */
67 	str = dirname(path);
68 	if (strcmp(str, "/") != 0)
69 		errx(1, "3: dirname(%s) = %s != /", path, str);
70 
71 	/* Case 4 */
72 	strlcpy(path, "/", sizeof(path));		/* reset path */
73 	for (i = 0; i <= MAXPATHLEN; i += strlen(dir))
74 		strlcat(path, dir, sizeof(path));
75 	strlcat(path, fname, sizeof(path));
76 	str = dirname(path);
77 	if (str != NULL)
78 		errx(1, "4: dirname(%s) = %s != NULL", path, str);
79 	if (errno != ENAMETOOLONG)
80 		errx(1, "4: dirname(%s) sets errno to %d", path, errno);
81 
82 	return (0);
83 }
84