Coverage Report

Created: 2025-08-28 06:26

/src/serenity/Userland/Libraries/LibIPC/File.h
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright (c) 2020, Sergey Bugaev <bugaevc@serenityos.org>
3
 * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
4
 *
5
 * SPDX-License-Identifier: BSD-2-Clause
6
 */
7
8
#pragma once
9
10
#include <AK/Noncopyable.h>
11
#include <AK/StdLibExtras.h>
12
#include <LibCore/File.h>
13
#include <LibCore/System.h>
14
15
namespace IPC {
16
17
class File {
18
    AK_MAKE_NONCOPYABLE(File);
19
20
public:
21
0
    File() = default;
22
23
    static File adopt_file(NonnullOwnPtr<Core::File> file)
24
0
    {
25
0
        return File(file->leak_fd(Badge<File> {}));
26
0
    }
27
28
    static File adopt_fd(int fd)
29
0
    {
30
0
        return File(fd);
31
0
    }
32
33
    static ErrorOr<File> clone_fd(int fd)
34
0
    {
35
0
        int new_fd = TRY(Core::System::dup(fd));
36
0
        return File(new_fd);
37
0
    }
Unexecuted instantiation: IPC::File::clone_fd(int)
Unexecuted instantiation: IPC::File::clone_fd(int)
38
39
    File(File&& other)
40
0
        : m_fd(exchange(other.m_fd, -1))
41
0
    {
42
0
    }
43
44
    File& operator=(File&& other)
45
0
    {
46
0
        if (this != &other) {
47
0
            m_fd = exchange(other.m_fd, -1);
48
0
        }
49
0
        return *this;
50
0
    }
51
52
    ~File()
53
0
    {
54
0
        if (m_fd != -1)
55
0
            (void)Core::System::close(m_fd);
56
0
    }
57
58
0
    int fd() const { return m_fd; }
59
60
    // NOTE: This is 'const' since generated IPC messages expose all parameters by const reference.
61
    [[nodiscard]] int take_fd() const
62
0
    {
63
0
        return exchange(m_fd, -1);
64
0
    }
65
66
    // FIXME: IPC::Files transferred over the wire are always set O_CLOEXEC during decoding.
67
    //        Perhaps we should add an option to IPC::File to allow the receiver to decide whether to
68
    //        make it O_CLOEXEC or not. Or an attribute in the .ipc file?
69
    ErrorOr<void> clear_close_on_exec()
70
0
    {
71
0
        auto fd_flags = TRY(Core::System::fcntl(m_fd, F_GETFD));
72
0
        fd_flags &= ~FD_CLOEXEC;
73
0
        TRY(Core::System::fcntl(m_fd, F_SETFD, fd_flags));
74
0
        return {};
75
0
    }
76
77
private:
78
    explicit File(int fd)
79
0
        : m_fd(fd)
80
0
    {
81
0
    }
82
83
    mutable int m_fd { -1 };
84
};
85
86
}