1// Copyright 2017 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include <errno.h>
6#include <fcntl.h>
7#include <sys/stat.h>
8
9#include <unittest/unittest.h>
10
11static bool stat_empty_test() {
12    BEGIN_TEST;
13
14    struct stat s;
15    int rc = stat("", &s);
16    int err = errno;
17    ASSERT_EQ(rc, -1);
18    ASSERT_EQ(err, ENOENT);
19
20    END_TEST;
21}
22
23static bool lstat_empty_test() {
24    BEGIN_TEST;
25
26    struct stat s;
27    int rc = lstat("", &s);
28    int err = errno;
29    ASSERT_EQ(rc, -1);
30    ASSERT_EQ(err, ENOENT);
31
32    END_TEST;
33}
34
35static bool open_empty_test() {
36    BEGIN_TEST;
37
38    const int oflags[] = {
39        O_EXEC,
40        O_RDONLY,
41        O_RDWR,
42        O_SEARCH,
43        O_WRONLY,
44    };
45
46    const int additional_oflags[] = {
47        0,
48        O_APPEND,
49        O_CLOEXEC,
50        O_APPEND | O_CLOEXEC,
51        O_TRUNC,
52        O_APPEND | O_TRUNC,
53        O_CLOEXEC | O_TRUNC,
54        O_APPEND | O_CLOEXEC | O_TRUNC,
55    };
56
57    const mode_t modes[] = {
58        0777,
59        0644,
60        0600,
61        0000,
62    };
63
64    const int fds[] = {
65        0,
66        1,
67        2,
68        AT_FDCWD,
69    };
70
71    for (int oflag : oflags) {
72        for (int additional_oflag : additional_oflags) {
73            int flags = oflag | additional_oflag;
74            int rc = open("", flags);
75            int err = errno;
76            ASSERT_EQ(rc, -1);
77            ASSERT_EQ(err, ENOENT);
78
79            for (int fd : fds) {
80                int rc = openat(fd, "", flags);
81                int err = errno;
82                ASSERT_EQ(rc, -1);
83                ASSERT_EQ(err, ENOENT);
84            }
85
86            for (mode_t mode : modes) {
87                rc = open("", flags | O_CREAT, mode);
88                err = errno;
89                ASSERT_EQ(rc, -1);
90                ASSERT_EQ(err, ENOENT);
91
92                for (int fd : fds) {
93                    int rc = openat(fd, "", flags | O_CREAT, mode);
94                    int err = errno;
95                    ASSERT_EQ(rc, -1);
96                    ASSERT_EQ(err, ENOENT);
97                }
98            }
99        }
100    }
101
102    END_TEST;
103}
104
105BEGIN_TEST_CASE(posixio_test)
106RUN_TEST(stat_empty_test)
107RUN_TEST(lstat_empty_test)
108RUN_TEST(open_empty_test)
109END_TEST_CASE(posixio_test)
110
111int main(int argc, char** argv) {
112    bool success = unittest_run_all_tests(argc, argv);
113    return success ? 0 : -1;
114}
115