]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libc/gen/basename_compat.c
zfs: merge openzfs/zfs@66b81b349
[FreeBSD/FreeBSD.git] / lib / libc / gen / basename_compat.c
1 /*      $OpenBSD: basename.c,v 1.14 2005/08/08 08:05:33 espie Exp $     */
2
3 /*
4  * Copyright (c) 1997, 2004 Todd C. Miller <Todd.Miller@courtesan.com>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18
19 #include <sys/cdefs.h>
20 #include <errno.h>
21 #include <libgen.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/param.h>
25
26 char * __freebsd11_basename_r(const char *path, char *bname);
27 char * __freebsd11_basename(char *path);
28
29 char *
30 __freebsd11_basename_r(const char *path, char *bname)
31 {
32         const char *endp, *startp;
33         size_t len;
34
35         /* Empty or NULL string gets treated as "." */
36         if (path == NULL || *path == '\0') {
37                 bname[0] = '.';
38                 bname[1] = '\0';
39                 return (bname);
40         }
41
42         /* Strip any trailing slashes */
43         endp = path + strlen(path) - 1;
44         while (endp > path && *endp == '/')
45                 endp--;
46
47         /* All slashes becomes "/" */
48         if (endp == path && *endp == '/') {
49                 bname[0] = '/';
50                 bname[1] = '\0';
51                 return (bname);
52         }
53
54         /* Find the start of the base */
55         startp = endp;
56         while (startp > path && *(startp - 1) != '/')
57                 startp--;
58
59         len = endp - startp + 1;
60         if (len >= MAXPATHLEN) {
61                 errno = ENAMETOOLONG;
62                 return (NULL);
63         }
64         memcpy(bname, startp, len);
65         bname[len] = '\0';
66         return (bname);
67 }
68
69 char *
70 __freebsd11_basename(char *path)
71 {
72         static char *bname = NULL;
73
74         if (bname == NULL) {
75                 bname = (char *)malloc(MAXPATHLEN);
76                 if (bname == NULL)
77                         return (NULL);
78         }
79         return (__freebsd11_basename_r(path, bname));
80 }
81
82 __sym_compat(basename_r, __freebsd11_basename_r, FBSD_1.2);
83 __sym_compat(basename, __freebsd11_basename, FBSD_1.0);