summaryrefslogtreecommitdiff
path: root/Kernel/FileDescriptor.cpp
blob: 78e23f26024de21de720f44b8a30307d41c783e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
#include "FileDescriptor.h"
#include <Kernel/FileSystem/FileSystem.h>
#include <Kernel/Devices/CharacterDevice.h>
#include <LibC/errno_numbers.h>
#include "UnixTypes.h"
#include <AK/BufferStream.h>
#include "FIFO.h"
#include <Kernel/TTY/TTY.h>
#include <Kernel/TTY/MasterPTY.h>
#include <Kernel/Socket.h>
#include <Kernel/Process.h>
#include <Kernel/Devices/BlockDevice.h>
#include <Kernel/MemoryManager.h>

Retained<FileDescriptor> FileDescriptor::create(RetainPtr<Inode>&& inode)
{
    return adopt(*new FileDescriptor(move(inode)));
}

Retained<FileDescriptor> FileDescriptor::create(RetainPtr<Device>&& device)
{
    return adopt(*new FileDescriptor(move(device)));
}

Retained<FileDescriptor> FileDescriptor::create(RetainPtr<Socket>&& socket, SocketRole role)
{
    return adopt(*new FileDescriptor(move(socket), role));
}

Retained<FileDescriptor> FileDescriptor::create_pipe_writer(FIFO& fifo)
{
    return adopt(*new FileDescriptor(fifo, FIFO::Writer));
}

Retained<FileDescriptor> FileDescriptor::create_pipe_reader(FIFO& fifo)
{
    return adopt(*new FileDescriptor(fifo, FIFO::Reader));
}

FileDescriptor::FileDescriptor(RetainPtr<Inode>&& inode)
    : m_inode(move(inode))
{
}

FileDescriptor::FileDescriptor(RetainPtr<Device>&& device)
    : m_device(move(device))
{
}

FileDescriptor::FileDescriptor(RetainPtr<Socket>&& socket, SocketRole role)
    : m_socket(move(socket))
{
    set_socket_role(role);
}

FileDescriptor::~FileDescriptor()
{
    if (m_socket) {
        m_socket->detach_fd(m_socket_role);
        m_socket = nullptr;
    }
    if (m_device) {
        m_device->close();
        m_device = nullptr;
    }
    if (m_fifo) {
        m_fifo->close(fifo_direction());
        m_fifo = nullptr;
    }
    m_inode = nullptr;
}

void FileDescriptor::set_socket_role(SocketRole role)
{
    if (role == m_socket_role)
        return;

    ASSERT(m_socket);
    auto old_socket_role = m_socket_role;
    m_socket_role = role;
    m_socket->attach_fd(role);
    if (old_socket_role != SocketRole::None)
        m_socket->detach_fd(old_socket_role);
}

Retained<FileDescriptor> FileDescriptor::clone()
{
    RetainPtr<FileDescriptor> descriptor;
    if (is_fifo()) {
        descriptor = fifo_direction() == FIFO::Reader
            ? FileDescriptor::create_pipe_reader(*m_fifo)
            : FileDescriptor::create_pipe_writer(*m_fifo);
    } else {
        if (m_device) {
            descriptor = FileDescriptor::create(m_device.copy_ref());
            descriptor->m_inode = m_inode.copy_ref();
        } else if (m_socket) {
            descriptor = FileDescriptor::create(m_socket.copy_ref(), m_socket_role);
            descriptor->m_inode = m_inode.copy_ref();
        } else {
            descriptor = FileDescriptor::create(m_inode.copy_ref());
        }
    }
    ASSERT(descriptor);
    descriptor->m_current_offset = m_current_offset;
    descriptor->m_is_blocking = m_is_blocking;
    descriptor->m_file_flags = m_file_flags;
    return *descriptor;
}

bool addition_would_overflow(off_t a, off_t b)
{
    ASSERT(a > 0);
    uint64_t ua = a;
    return (ua + b) > OFF_T_MAX;
}

KResult FileDescriptor::fstat(stat& buffer)
{
    ASSERT(!is_fifo());
    if (!m_inode && !m_device)
        return KResult(-EBADF);

    auto metadata = this->metadata();
    if (!metadata.is_valid())
        return KResult(-EIO);

    buffer.st_rdev = encoded_device(metadata.major_device, metadata.minor_device);
    buffer.st_ino = metadata.inode.index();
    buffer.st_mode = metadata.mode;
    buffer.st_nlink = metadata.link_count;
    buffer.st_uid = metadata.uid;
    buffer.st_gid = metadata.gid;
    buffer.st_dev = 0; // FIXME
    buffer.st_size = metadata.size;
    buffer.st_blksize = metadata.block_size;
    buffer.st_blocks = metadata.block_count;
    buffer.st_atime = metadata.atime;
    buffer.st_mtime = metadata.mtime;
    buffer.st_ctime = metadata.ctime;
    return KSuccess;
}

KResult FileDescriptor::fchmod(mode_t mode)
{
    if (!m_inode)
        return KResult(-EBADF);
    return VFS::the().chmod(*m_inode, mode);
}

off_t FileDescriptor::seek(off_t offset, int whence)
{
    ASSERT(!is_fifo());
    if (!m_inode && !m_device)
        return -EBADF;

    // FIXME: The file type should be cached on the vnode.
    //        It's silly that we have to do a full metadata lookup here.
    auto metadata = this->metadata();
    if (!metadata.is_valid())
        return -EIO;

    if (metadata.is_socket() || metadata.is_fifo())
        return -ESPIPE;

    off_t newOffset;

    switch (whence) {
    case SEEK_SET:
        newOffset = offset;
        break;
    case SEEK_CUR:
        newOffset = m_current_offset + offset;
        if (newOffset < 0)
            return -EINVAL;
        break;
    case SEEK_END:
        ASSERT(metadata.size); // FIXME: What do I do?
        newOffset = metadata.size;
        break;
    default:
        return -EINVAL;
    }

    m_current_offset = newOffset;
    return m_current_offset;
}

ssize_t FileDescriptor::read(Process& process, byte* buffer, ssize_t count)
{
    if (is_fifo()) {
        ASSERT(fifo_direction() == FIFO::Reader);
        return m_fifo->read(buffer, count);
    }
    if (m_device) {
        // FIXME: What should happen to m_currentOffset?
        return m_device->read(process, buffer, count);
    }
    if (m_socket)
        return m_socket->read(m_socket_role, buffer, count);
    ASSERT(inode());
    ssize_t nread = inode()->read_bytes(m_current_offset, count, buffer, this);
    m_current_offset += nread;
    return nread;
}

ssize_t FileDescriptor::write(Process& process, const byte* data, ssize_t size)
{
    if (is_fifo()) {
        ASSERT(fifo_direction() == FIFO::Writer);
        return m_fifo->write(data, size);
    }
    if (m_device) {
        // FIXME: What should happen to m_currentOffset?
        return m_device->write(process, data, size);
    }
    if (m_socket)
        return m_socket->write(m_socket_role, data, size);
    ASSERT(m_inode);
    ssize_t nwritten = m_inode->write_bytes(m_current_offset, size, data, this);
    m_current_offset += nwritten;
    return nwritten;
}

bool FileDescriptor::can_write(Process& process)
{
    if (is_fifo()) {
        ASSERT(fifo_direction() == FIFO::Writer);
        return m_fifo->can_write();
    }
    if (m_device)
        return m_device->can_write(process);
    if (m_socket)
        return m_socket->can_write(m_socket_role);
    return true;
}

bool FileDescriptor::can_read(Process& process)
{
    if (is_fifo()) {
        ASSERT(fifo_direction() == FIFO::Reader);
        return m_fifo->can_read();
    }
    if (m_device)
        return m_device->can_read(process);
    if (m_socket)
        return m_socket->can_read(m_socket_role);
    return true;
}

ByteBuffer FileDescriptor::read_entire_file(Process& process)
{
    ASSERT(!is_fifo());

    if (m_device) {
        auto buffer = ByteBuffer::create_uninitialized(1024);
        ssize_t nread = m_device->read(process, buffer.pointer(), buffer.size());
        ASSERT(nread >= 0);
        buffer.trim(nread);
        return buffer;
    }

    ASSERT(m_inode);
    return m_inode->read_entire(this);
}

bool FileDescriptor::is_directory() const
{
    ASSERT(!is_fifo());
    return metadata().is_directory();
}

ssize_t FileDescriptor::get_dir_entries(byte* buffer, ssize_t size)
{
    auto metadata = this->metadata();
    if (!metadata.is_valid())
        return -EIO;
    if (!metadata.is_directory())
        return -ENOTDIR;

    int size_to_allocate = max(PAGE_SIZE, metadata.size);

    auto temp_buffer = ByteBuffer::create_uninitialized(size_to_allocate);
    BufferStream stream(temp_buffer);
    VFS::the().traverse_directory_inode(*m_inode, [&stream] (auto& entry) {
        stream << (dword)entry.inode.index();
        stream << (byte)entry.file_type;
        stream << (dword)entry.name_length;
        stream << entry.name;
        return true;
    });
    stream.snip();

    if (size < temp_buffer.size())
        return -1;

    memcpy(buffer, temp_buffer.pointer(), temp_buffer.size());
    return stream.offset();
}

bool FileDescriptor::is_tty() const
{
    return m_device && m_device->is_tty();
}

const TTY* FileDescriptor::tty() const
{
    if (!is_tty())
        return nullptr;
    return static_cast<const TTY*>(m_device.ptr());
}

TTY* FileDescriptor::tty()
{
    if (!is_tty())
        return nullptr;
    return static_cast<TTY*>(m_device.ptr());
}

bool FileDescriptor::is_master_pty() const
{
    if (m_device)
        return m_device->is_master_pty();
    return false;
}

const MasterPTY* FileDescriptor::master_pty() const
{
    if (!is_master_pty())
        return nullptr;
    return static_cast<const MasterPTY*>(m_device.ptr());
}

MasterPTY* FileDescriptor::master_pty()
{
    if (!is_master_pty())
        return nullptr;
    return static_cast<MasterPTY*>(m_device.ptr());
}

int FileDescriptor::close()
{
    return 0;
}

const char* to_string(SocketRole role)
{
    switch (role) {
    case SocketRole::Listener:
        return "Listener";
    case SocketRole::Accepted:
        return "Accepted";
    case SocketRole::Connected:
        return "Connected";
    default:
        return "None";
    }
}

KResultOr<String> FileDescriptor::absolute_path()
{
    Stopwatch sw("absolute_path");
    if (is_tty())
        return tty()->tty_name();
    if (is_fifo())
        return String::format("fifo:%x", m_fifo.ptr());
    if (is_device())
        return String::format("device:%u,%u (%s)", m_device->major(), m_device->minor(), m_device->class_name());
    if (is_socket())
        return String::format("socket:%x (role: %s)", m_socket.ptr(), to_string(m_socket_role));
    ASSERT(m_inode);
    return VFS::the().absolute_path(*m_inode);
}

FileDescriptor::FileDescriptor(FIFO& fifo, FIFO::Direction direction)
    : m_is_blocking(true)
    , m_fifo(fifo)
    , m_fifo_direction(direction)
{
    m_fifo->open(direction);
}

InodeMetadata FileDescriptor::metadata() const
{
    if (m_inode)
        return m_inode->metadata();
    return { };
}

bool FileDescriptor::supports_mmap() const
{
    if (m_inode)
        return true;
    if (m_device)
        return m_device->is_block_device();
    return false;
}

Region* FileDescriptor::mmap(Process& process, LinearAddress laddr, size_t offset, size_t size, int prot)
{
    ASSERT(supports_mmap());

    if (is_block_device())
        return static_cast<BlockDevice&>(*m_device).mmap(process, laddr, offset, size);

    ASSERT(m_inode);
    // FIXME: If PROT_EXEC, check that the underlying file system isn't mounted noexec.
    String region_name;
#if 0
    // FIXME: I would like to do this, but it would instantiate all the damn inodes.
    region_name = absolute_path();
#else
    region_name = "Memory-mapped file";
#endif
    InterruptDisabler disabler;
    // FIXME: Implement mapping at a client-specified address. Most of the support is already in plcae.
    ASSERT(laddr.as_ptr() == nullptr);
    auto* region = process.allocate_file_backed_region(LinearAddress(), size, inode(), move(region_name), prot & PROT_READ, prot & PROT_WRITE);
    region->page_in();
    return region;
}

bool FileDescriptor::is_block_device() const
{
    return m_device && m_device->is_block_device();
}

bool FileDescriptor::is_character_device() const
{
    return m_device && m_device->is_character_device();
}

CharacterDevice* FileDescriptor::character_device()
{
    return is_character_device() ? static_cast<CharacterDevice*>(device()) : nullptr;
}

const CharacterDevice* FileDescriptor::character_device() const
{
    return is_character_device() ? static_cast<const CharacterDevice*>(device()) : nullptr;
}