xref: /openbsd-src/regress/lib/libc/basename/basename_test.c (revision 49a6e16f2c2c8e509184b1f777366d1a6f337e1c)
13bafd96cSray /*
23bafd96cSray  * Copyright (c) 2007 Bret S. Lambert <blambert@gsipt.net>
33bafd96cSray  *
43bafd96cSray  * Public domain.
53bafd96cSray  */
63bafd96cSray 
73bafd96cSray #include <libgen.h>
83bafd96cSray #include <stdio.h>
93bafd96cSray #include <string.h>
103bafd96cSray #include <limits.h>
113bafd96cSray #include <errno.h>
123bafd96cSray 
133bafd96cSray int
main(void)143bafd96cSray main(void)
153bafd96cSray {
16*49a6e16fSderaadt 	char path[2 * PATH_MAX];
173bafd96cSray 	const char *dir = "junk/";
183bafd96cSray 	const char *fname = "file.name.ext";
193bafd96cSray 	char *str;
203bafd96cSray 	int i;
213bafd96cSray 
223bafd96cSray 	/* Test normal functioning */
233bafd96cSray 	strlcpy(path, "/", sizeof(path));
243bafd96cSray 	strlcat(path, dir, sizeof(path));
253bafd96cSray 	strlcat(path, fname, sizeof(path));
263bafd96cSray 	str = basename(path);
273bafd96cSray 	if (strcmp(str, fname) != 0)
283bafd96cSray 		goto fail;
293bafd96cSray 
303bafd96cSray 	/*
313bafd96cSray 	 * There are four states that require special handling:
323bafd96cSray 	 *
333bafd96cSray 	 * 1) path is NULL
343bafd96cSray 	 * 2) path is the empty string
353bafd96cSray 	 * 3) path is composed entirely of slashes
36*49a6e16fSderaadt 	 * 4) the resulting name is larger than PATH_MAX
373bafd96cSray 	 *
383bafd96cSray 	 * The first two cases require that a pointer
393bafd96cSray 	 * to the string "." be returned.
403bafd96cSray 	 *
413bafd96cSray 	 * The third case requires that a pointer
423bafd96cSray 	 * to the string "/" be returned.
433bafd96cSray 	 *
443bafd96cSray 	 * The final case requires that NULL be returned
453bafd96cSray 	 * and errno * be set to ENAMETOOLONG.
463bafd96cSray 	 */
473bafd96cSray 	/* Case 1 */
483bafd96cSray 	str = basename(NULL);
493bafd96cSray 	if (strcmp(str, ".") != 0)
503bafd96cSray 		goto fail;
513bafd96cSray 
523bafd96cSray 	/* Case 2 */
533bafd96cSray 	strlcpy(path, "", sizeof(path));
543bafd96cSray 	str = basename(path);
553bafd96cSray 	if (strcmp(str, ".") != 0)
563bafd96cSray 		goto fail;
573bafd96cSray 
583bafd96cSray 	/* Case 3 */
59*49a6e16fSderaadt 	for (i = 0; i < PATH_MAX - 1; i++)
603bafd96cSray 		strlcat(path, "/", sizeof(path));	/* path cleared above */
613bafd96cSray 	str = basename(path);
623bafd96cSray 	if (strcmp(str, "/") != 0)
633bafd96cSray 		goto fail;
643bafd96cSray 
653bafd96cSray 	/* Case 4 */
663bafd96cSray 	strlcpy(path, "/", sizeof(path));
673bafd96cSray 	strlcat(path, dir, sizeof(path));
68*49a6e16fSderaadt 	for (i = 0; i <= PATH_MAX; i += sizeof(fname))
693bafd96cSray 		strlcat(path, fname, sizeof(path));
703bafd96cSray 	str = basename(path);
713bafd96cSray 	if (str != NULL || errno != ENAMETOOLONG)
723bafd96cSray 		goto fail;
733bafd96cSray 
743bafd96cSray 	return (0);
753bafd96cSray fail:
763bafd96cSray 	return (1);
773bafd96cSray }
78