summaryrefslogtreecommitdiff
path: root/fs/fs_struct.cc
blob: 090819f094f46412430478065e0e12a5760cd4dd (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
/* SPDX-License-Identifier: GPL-2.0-or-later */
/* Copyright (C) 2026 Richard Qin */

/*
 * fs_struct.cc — Per-task filesystem context (cwd, root)
 */

#include <lume/fs_struct.h>
#include <lume/slab.h>

/* ================================================================== */
/*  alloc_fs_struct                                                   */
/* ================================================================== */

fs_struct* alloc_fs_struct()
{
    auto* fs = new fs_struct{};
    if (!fs) return nullptr;

    fs->count.store(1);
    fs->umask = 022;
    fs->root = {nullptr, nullptr};
    fs->pwd  = {nullptr, nullptr};

    return fs;
}

/* ================================================================== */
/*  put_fs_struct                                                     */
/* ================================================================== */

void put_fs_struct(fs_struct* fs)
{
    if (!fs) return;

    int old = fs->count.fetch_sub(1);
    if (old > 1) return;

    path_put(&fs->root);
    path_put(&fs->pwd);
    delete fs;
}

/* ================================================================== */
/*  copy_fs_struct — for fork without CLONE_FS                        */
/* ================================================================== */

fs_struct* copy_fs_struct(const fs_struct* old_fs)
{
    auto* fs = alloc_fs_struct();
    if (!fs) return nullptr;

    fs->umask = old_fs->umask;

    fs->root = old_fs->root;
    path_get(&fs->root);

    fs->pwd = old_fs->pwd;
    path_get(&fs->pwd);

    return fs;
}

/* ================================================================== */
/*  set_fs_root / set_fs_pwd                                          */
/* ================================================================== */

void set_fs_root(fs_struct* fs, const path* p)
{
    path old_root;
    {
        LockGuard guard(fs->lock);
        old_root = fs->root;
        fs->root = *p;
        path_get(p);
    }
    path_put(&old_root);
}

void set_fs_pwd(fs_struct* fs, const path* p)
{
    path old_pwd;
    {
        LockGuard guard(fs->lock);
        old_pwd = fs->pwd;
        fs->pwd = *p;
        path_get(p);
    }
    path_put(&old_pwd);
}