aboutsummaryrefslogtreecommitdiff
path: root/src/core/hle/service/fs/file.cpp
blob: 702e2018eb12c97a841d145509df4ee70afcb866 (plain) (blame)
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
// Copyright 2018 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.

#include <boost/serialization/unique_ptr.hpp>
#include "common/archives.h"
#include "common/logging/log.h"
#include "core/core.h"
#include "core/file_sys/errors.h"
#include "core/file_sys/file_backend.h"
#include "core/hle/ipc_helpers.h"
#include "core/hle/kernel/client_port.h"
#include "core/hle/kernel/client_session.h"
#include "core/hle/kernel/event.h"
#include "core/hle/kernel/server_session.h"
#include "core/hle/service/fs/file.h"

SERIALIZE_EXPORT_IMPL(Service::FS::File)
SERIALIZE_EXPORT_IMPL(Service::FS::FileSessionSlot)

namespace Service::FS {

template <class Archive>
void File::serialize(Archive& ar, const unsigned int) {
    ar& boost::serialization::base_object<Kernel::SessionRequestHandler>(*this);
    ar& path;
    ar& backend;
}

File::File() : File(Core::Global<Kernel::KernelSystem>()) {}

File::File(Kernel::KernelSystem& kernel, std::unique_ptr<FileSys::FileBackend>&& backend,
           const FileSys::Path& path)
    : File(kernel) {
    this->backend = std::move(backend);
    this->path = path;
}

File::File(Kernel::KernelSystem& kernel)
    : ServiceFramework("", 1), path(""), backend(nullptr), kernel(kernel) {
    static const FunctionInfo functions[] = {
        {0x0801, &File::OpenSubFile, "OpenSubFile"},
        {0x0802, &File::Read, "Read"},
        {0x0803, &File::Write, "Write"},
        {0x0804, &File::GetSize, "GetSize"},
        {0x0805, &File::SetSize, "SetSize"},
        {0x0808, &File::Close, "Close"},
        {0x0809, &File::Flush, "Flush"},
        {0x080A, &File::SetPriority, "SetPriority"},
        {0x080B, &File::GetPriority, "GetPriority"},
        {0x080C, &File::OpenLinkFile, "OpenLinkFile"},
    };
    RegisterHandlers(functions);
}

void File::Read(Kernel::HLERequestContext& ctx) {
    IPC::RequestParser rp(ctx);
    u64 offset = rp.Pop<u64>();
    u32 length = rp.Pop<u32>();
    LOG_TRACE(Service_FS, "Read {}: offset=0x{:x} length=0x{:08X}", GetName(), offset, length);

    const FileSessionSlot* file = GetSessionData(ctx.Session());

    if (file->subfile && length > file->size) {
        LOG_WARNING(Service_FS, "Trying to read beyond the subfile size, truncating");
        length = static_cast<u32>(file->size);
    }

    // This file session might have a specific offset from where to start reading, apply it.
    offset += file->offset;

    if (offset + length > backend->GetSize()) {
        LOG_ERROR(Service_FS,
                  "Reading from out of bounds offset=0x{:x} length=0x{:08X} file_size=0x{:x}",
                  offset, length, backend->GetSize());
    }

    // Conventional reading if the backend does not support cache.
    if (!backend->AllowsCachedReads()) {
        auto& buffer = rp.PopMappedBuffer();
        IPC::RequestBuilder rb = rp.MakeBuilder(2, 2);
        std::unique_ptr<u8*> data = std::make_unique<u8*>(static_cast<u8*>(operator new(length)));
        const auto read = backend->Read(offset, length, *data);
        if (read.Failed()) {
            rb.Push(read.Code());
            rb.Push<u32>(0);
        } else {
            buffer.Write(*data, 0, *read);
            rb.Push(ResultSuccess);
            rb.Push<u32>(static_cast<u32>(*read));
        }
        rb.PushMappedBuffer(buffer);

        std::chrono::nanoseconds read_timeout_ns{backend->GetReadDelayNs(length)};
        ctx.SleepClientThread("file::read", read_timeout_ns, nullptr);
        return;
    }

    struct AsyncData {
        // Input
        u32 length;
        u64 offset;
        std::chrono::steady_clock::time_point pre_timer;
        bool cache_ready;

        // Output
        Result ret{0};
        Kernel::MappedBuffer* buffer;
        std::unique_ptr<u8*> data;
        std::size_t read_size;
    };

    auto async_data = std::make_shared<AsyncData>();
    async_data->buffer = &rp.PopMappedBuffer();
    async_data->length = length;
    async_data->offset = offset;
    async_data->cache_ready = backend->CacheReady(offset, length);
    if (!async_data->cache_ready) {
        async_data->pre_timer = std::chrono::steady_clock::now();
    }

    // LOG_DEBUG(Service_FS, "cache={}, offset={}, length={}", cache_ready, offset, length);
    ctx.RunAsync(
        [this, async_data](Kernel::HLERequestContext& ctx) {
            async_data->data =
                std::make_unique<u8*>(static_cast<u8*>(operator new(async_data->length)));
            const auto read =
                backend->Read(async_data->offset, async_data->length, *async_data->data);
            if (read.Failed()) {
                async_data->ret = read.Code();
                async_data->read_size = 0;
            } else {
                async_data->ret = ResultSuccess;
                async_data->read_size = *read;
            }

            const auto read_delay = static_cast<s64>(backend->GetReadDelayNs(async_data->length));
            if (!async_data->cache_ready) {
                const auto time_took = std::chrono::duration_cast<std::chrono::nanoseconds>(
                                           std::chrono::steady_clock::now() - async_data->pre_timer)
                                           .count();
                /*
                if (time_took > read_delay) {
                    LOG_DEBUG(Service_FS, "Took longer! length={}, time_took={}, read_delay={}",
                              async_data->length, time_took, read_delay);
                }
                */
                return static_cast<s64>((read_delay > time_took) ? (read_delay - time_took) : 0);
            } else {
                return static_cast<s64>(read_delay);
            }
        },
        [async_data](Kernel::HLERequestContext& ctx) {
            IPC::RequestBuilder rb(ctx, 0x0802, 2, 2);
            if (async_data->ret.IsError()) {
                rb.Push(async_data->ret);
                rb.Push<u32>(0);
            } else {
                async_data->buffer->Write(*async_data->data, 0, async_data->read_size);
                rb.Push(ResultSuccess);
                rb.Push<u32>(static_cast<u32>(async_data->read_size));
            }
            rb.PushMappedBuffer(*async_data->buffer);
        },
        !async_data->cache_ready);
}

void File::Write(Kernel::HLERequestContext& ctx) {
    IPC::RequestParser rp(ctx);
    u64 offset = rp.Pop<u64>();
    u32 length = rp.Pop<u32>();
    u32 flush = rp.Pop<u32>();
    auto& buffer = rp.PopMappedBuffer();
    LOG_TRACE(Service_FS, "Write {}: offset=0x{:x} length={}, flush=0x{:x}", GetName(), offset,
              length, flush);

    IPC::RequestBuilder rb = rp.MakeBuilder(2, 2);

    FileSessionSlot* file = GetSessionData(ctx.Session());

    // Subfiles can not be written to
    if (file->subfile) {
        rb.Push(FileSys::ResultUnsupportedOpenFlags);
        rb.Push<u32>(0);
        rb.PushMappedBuffer(buffer);
        return;
    }

    std::vector<u8> data(length);
    buffer.Read(data.data(), 0, data.size());
    ResultVal<std::size_t> written = backend->Write(offset, data.size(), flush != 0, data.data());

    // Update file size
    file->size = backend->GetSize();

    if (written.Failed()) {
        rb.Push(written.Code());
        rb.Push<u32>(0);
    } else {
        rb.Push(ResultSuccess);
        rb.Push<u32>(static_cast<u32>(*written));
    }
    rb.PushMappedBuffer(buffer);
}

void File::GetSize(Kernel::HLERequestContext& ctx) {
    IPC::RequestParser rp(ctx);

    const FileSessionSlot* file = GetSessionData(ctx.Session());

    IPC::RequestBuilder rb = rp.MakeBuilder(3, 0);
    rb.Push(ResultSuccess);
    rb.Push<u64>(file->size);
}

void File::SetSize(Kernel::HLERequestContext& ctx) {
    IPC::RequestParser rp(ctx);
    u64 size = rp.Pop<u64>();

    FileSessionSlot* file = GetSessionData(ctx.Session());

    IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);

    // SetSize can not be called on subfiles.
    if (file->subfile) {
        rb.Push(FileSys::ResultUnsupportedOpenFlags);
        return;
    }

    file->size = size;
    backend->SetSize(size);
    rb.Push(ResultSuccess);
}

void File::Close(Kernel::HLERequestContext& ctx) {
    IPC::RequestParser rp(ctx);

    // TODO(Subv): Only close the backend if this client is the only one left.
    if (connected_sessions.size() > 1)
        LOG_WARNING(Service_FS, "Closing File backend but {} clients still connected",
                    connected_sessions.size());

    backend->Close();
    IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
    rb.Push(ResultSuccess);
}

void File::Flush(Kernel::HLERequestContext& ctx) {
    IPC::RequestParser rp(ctx);

    IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);

    const FileSessionSlot* file = GetSessionData(ctx.Session());

    // Subfiles can not be flushed.
    if (file->subfile) {
        rb.Push(FileSys::ResultUnsupportedOpenFlags);
        return;
    }

    backend->Flush();
    rb.Push(ResultSuccess);
}

void File::SetPriority(Kernel::HLERequestContext& ctx) {
    IPC::RequestParser rp(ctx);

    FileSessionSlot* file = GetSessionData(ctx.Session());
    file->priority = rp.Pop<u32>();

    IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
    rb.Push(ResultSuccess);
}

void File::GetPriority(Kernel::HLERequestContext& ctx) {
    IPC::RequestParser rp(ctx);
    const FileSessionSlot* file = GetSessionData(ctx.Session());

    IPC::RequestBuilder rb = rp.MakeBuilder(2, 0);
    rb.Push(ResultSuccess);
    rb.Push(file->priority);
}

void File::OpenLinkFile(Kernel::HLERequestContext& ctx) {
    LOG_WARNING(Service_FS, "(STUBBED) File command OpenLinkFile {}", GetName());
    using Kernel::ClientSession;
    using Kernel::ServerSession;
    IPC::RequestParser rp(ctx);
    IPC::RequestBuilder rb = rp.MakeBuilder(1, 2);
    auto [server, client] = kernel.CreateSessionPair(GetName());
    ClientConnected(server);

    FileSessionSlot* slot = GetSessionData(std::move(server));
    const FileSessionSlot* original_file = GetSessionData(ctx.Session());

    slot->priority = original_file->priority;
    slot->offset = 0;
    slot->size = backend->GetSize();
    slot->subfile = false;

    rb.Push(ResultSuccess);
    rb.PushMoveObjects(client);
}

void File::OpenSubFile(Kernel::HLERequestContext& ctx) {
    IPC::RequestParser rp(ctx);
    s64 offset = rp.PopRaw<s64>();
    s64 size = rp.PopRaw<s64>();

    IPC::RequestBuilder rb = rp.MakeBuilder(1, 2);

    const FileSessionSlot* original_file = GetSessionData(ctx.Session());

    if (original_file->subfile) {
        // OpenSubFile can not be called on a file which is already as subfile
        rb.Push(FileSys::ResultUnsupportedOpenFlags);
        return;
    }

    if (offset < 0 || size < 0) {
        rb.Push(FileSys::ResultWriteBeyondEnd);
        return;
    }

    std::size_t end = offset + size;

    // TODO(Subv): Check for overflow and return ResultWriteBeyondEnd

    if (end > original_file->size) {
        rb.Push(FileSys::ResultWriteBeyondEnd);
        return;
    }

    using Kernel::ClientSession;
    using Kernel::ServerSession;
    auto [server, client] = kernel.CreateSessionPair(GetName());
    ClientConnected(server);

    FileSessionSlot* slot = GetSessionData(std::move(server));
    slot->priority = original_file->priority;
    slot->offset = offset;
    slot->size = size;
    slot->subfile = true;

    rb.Push(ResultSuccess);
    rb.PushMoveObjects(client);
}

std::shared_ptr<Kernel::ClientSession> File::Connect() {
    auto [server, client] = kernel.CreateSessionPair(GetName());
    ClientConnected(server);

    FileSessionSlot* slot = GetSessionData(std::move(server));
    slot->priority = 0;
    slot->offset = 0;
    slot->size = backend->GetSize();
    slot->subfile = false;

    return client;
}

std::size_t File::GetSessionFileOffset(std::shared_ptr<Kernel::ServerSession> session) {
    const FileSessionSlot* slot = GetSessionData(std::move(session));
    ASSERT(slot);
    return slot->offset;
}

std::size_t File::GetSessionFileSize(std::shared_ptr<Kernel::ServerSession> session) {
    const FileSessionSlot* slot = GetSessionData(std::move(session));
    ASSERT(slot);
    return slot->size;
}

} // namespace Service::FS