1 /*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <gtest/gtest.h>
18
19 #include <errno.h>
20 #include <limits.h>
21 #include <unistd.h>
22
23 #include <android-base/test_utils.h>
24
25 #include "utils.h"
26
TEST(getcwd,auto_full)27 TEST(getcwd, auto_full) {
28 // If we let the library do all the work, everything's fine.
29 errno = 0;
30 char* cwd = getcwd(nullptr, 0);
31 ASSERT_TRUE(cwd != nullptr);
32 ASSERT_ERRNO(0);
33 ASSERT_GE(strlen(cwd), 1U);
34 free(cwd);
35 }
36
TEST(getcwd,auto_reasonable)37 TEST(getcwd, auto_reasonable) {
38 // If we ask the library to allocate a reasonable buffer, everything's fine.
39 errno = 0;
40 char* cwd = getcwd(nullptr, PATH_MAX);
41 ASSERT_TRUE(cwd != nullptr);
42 ASSERT_ERRNO(0);
43 ASSERT_GE(strlen(cwd), 1U);
44 free(cwd);
45 }
46
TEST(getcwd,auto_too_small)47 TEST(getcwd, auto_too_small) {
48 // If we ask the library to allocate a too-small buffer, ERANGE.
49 errno = 0;
50 char* cwd = getcwd(nullptr, 1);
51 ASSERT_TRUE(cwd == nullptr);
52 ASSERT_ERRNO(ERANGE);
53 }
54
TEST(getcwd,auto_too_large)55 TEST(getcwd, auto_too_large) {
56 SKIP_WITH_HWASAN << "allocation size too large";
57 // If we ask the library to allocate an unreasonably large buffer, ERANGE.
58 errno = 0;
59 char* cwd = getcwd(nullptr, static_cast<size_t>(-1));
60 ASSERT_TRUE(cwd == nullptr);
61 ASSERT_ERRNO(ENOMEM);
62 }
63
TEST(getcwd,manual_too_small)64 TEST(getcwd, manual_too_small) {
65 // If we allocate a too-small buffer, ERANGE.
66 char tiny_buf[1];
67 errno = 0;
68 char* cwd = getcwd(tiny_buf, sizeof(tiny_buf));
69 ASSERT_TRUE(cwd == nullptr);
70 ASSERT_ERRNO(ERANGE);
71 }
72
TEST(getcwd,manual_zero)73 TEST(getcwd, manual_zero) {
74 // If we allocate a zero-length buffer, EINVAL.
75 char tiny_buf[1];
76 errno = 0;
77 char* cwd = getcwd(tiny_buf, 0);
78 ASSERT_TRUE(cwd == nullptr);
79 ASSERT_ERRNO(EINVAL);
80 }
81
TEST(getcwd,manual_path_max)82 TEST(getcwd, manual_path_max) {
83 char* buf = new char[PATH_MAX];
84 errno = 0;
85 char* cwd = getcwd(buf, PATH_MAX);
86 ASSERT_TRUE(cwd == buf);
87 ASSERT_ERRNO(0);
88 ASSERT_GE(strlen(cwd), 1U);
89 delete[] cwd;
90 }
91