Line data Source code
1 : /* Test of getcwd() function.
2 : Copyright (C) 2009-2020 Free Software Foundation, Inc.
3 :
4 : This program is free software: you can redistribute it and/or modify
5 : it under the terms of the GNU General Public License as published by
6 : the Free Software Foundation; either version 3 of the License, or
7 : (at your option) any later version.
8 :
9 : This program is distributed in the hope that it will be useful,
10 : but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : GNU General Public License for more details.
13 :
14 : You should have received a copy of the GNU General Public License
15 : along with this program. If not, see <https://www.gnu.org/licenses/>. */
16 :
17 : #include <config.h>
18 :
19 : #include <unistd.h>
20 :
21 : #include "signature.h"
22 : SIGNATURE_CHECK (getcwd, char *, (char *, size_t));
23 :
24 : #include <errno.h>
25 : #include <stdio.h>
26 : #include <stdlib.h>
27 : #include <string.h>
28 :
29 : #include "macros.h"
30 :
31 : int
32 1 : main (int argc, char **argv)
33 : {
34 : char *pwd1;
35 : char *pwd2;
36 : /* If the user provides an argument, attempt to chdir there first. */
37 1 : if (1 < argc)
38 : {
39 0 : if (chdir (argv[1]) == 0)
40 0 : printf ("changed to directory %s\n", argv[1]);
41 : }
42 :
43 1 : pwd1 = getcwd (NULL, 0);
44 1 : ASSERT (pwd1 && *pwd1);
45 1 : if (1 < argc)
46 0 : printf ("cwd=%s\n", pwd1);
47 :
48 : /* Make sure the result is usable. */
49 1 : ASSERT (chdir (pwd1) == 0);
50 1 : ASSERT (chdir (".//./.") == 0);
51 :
52 : /* Make sure that result is normalized. */
53 1 : pwd2 = getcwd (NULL, 0);
54 1 : ASSERT (pwd2);
55 1 : ASSERT (strcmp (pwd1, pwd2) == 0);
56 1 : free (pwd2);
57 : {
58 1 : size_t len = strlen (pwd1);
59 1 : ssize_t i = len - 10;
60 1 : if (i < 1)
61 0 : i = 1;
62 1 : pwd2 = getcwd (NULL, len + 1);
63 1 : ASSERT (pwd2);
64 1 : free (pwd2);
65 1 : pwd2 = malloc (len + 2);
66 12 : for ( ; i <= len; i++)
67 : {
68 : char *tmp;
69 11 : errno = 0;
70 11 : ASSERT (getcwd (pwd2, i) == NULL);
71 11 : ASSERT (errno == ERANGE);
72 : /* Allow either glibc or BSD behavior, since POSIX allows both. */
73 11 : errno = 0;
74 11 : tmp = getcwd (NULL, i);
75 11 : if (tmp)
76 : {
77 0 : ASSERT (strcmp (pwd1, tmp) == 0);
78 0 : free (tmp);
79 : }
80 : else
81 : {
82 11 : ASSERT (errno == ERANGE);
83 : }
84 : }
85 1 : ASSERT (getcwd (pwd2, len + 1) == pwd2);
86 1 : pwd2[len] = '/';
87 1 : pwd2[len + 1] = '\0';
88 : }
89 1 : ASSERT (strstr (pwd2, "/./") == NULL);
90 1 : ASSERT (strstr (pwd2, "/../") == NULL);
91 1 : ASSERT (strstr (pwd2 + 1 + (pwd2[1] == '/'), "//") == NULL);
92 :
93 : /* Validate a POSIX requirement on size. */
94 1 : errno = 0;
95 1 : ASSERT (getcwd(pwd2, 0) == NULL);
96 1 : ASSERT (errno == EINVAL);
97 :
98 1 : free (pwd1);
99 1 : free (pwd2);
100 :
101 1 : return 0;
102 : }
|