Ver código fonte

feat(vfs): impl. vfs_open to open file and dirs

greatbridf 3 anos atrás
pai
commit
89a69a47e9
3 arquivos alterados com 52 adições e 21 exclusões
  1. 3 0
      include/kernel/vfs.h
  2. 46 21
      src/kernel/vfs.cpp
  3. 3 0
      src/kernel_main.c

+ 3 - 0
include/kernel/vfs.h

@@ -65,6 +65,9 @@ int vfs_mkfile(struct inode* dir, const char* filename);
 int vfs_rmfile(struct inode* dir, const char* filename);
 int vfs_mkdir(struct inode* dir, const char* dirname);
 
+// @return pointer to the inode if found, nullptr if not
+struct inode* vfs_open(const char* path);
+
 #ifdef __cplusplus
 }
 #endif

+ 46 - 21
src/kernel/vfs.cpp

@@ -281,6 +281,49 @@ int vfs_mkdir(struct inode* dir, const char* dirname)
         return 0;
     }
 }
+
+struct inode* vfs_open(const char* path)
+{
+    struct inode* cur = fs_root;
+    size_t n = 0;
+    char buf[128] {};
+    switch (*(path++)) {
+    // absolute path
+    case '/':
+        while (true) {
+            if (path[n] == 0x00) {
+                strncpy(buf, path, n);
+                buf[n] = 0x00;
+                cur = vfs_findinode(cur, buf);
+                return cur;
+            }
+            if (path[n] == '/') {
+                strncpy(buf, path, n);
+                buf[n] = 0x00;
+                cur = vfs_findinode(cur, buf);
+                if (path[n + 1] == 0x00) {
+                    return cur;
+                } else {
+                    path += (n + 1);
+                    n = 0;
+                    continue;
+                }
+            }
+            ++n;
+        }
+        break;
+    // empty string
+    case 0x00:
+        return nullptr;
+        break;
+    // relative path
+    default:
+        return nullptr;
+        break;
+    }
+    return nullptr;
+}
+
 struct inode* fs_root;
 static tmpfs* rootfs;
 
@@ -293,25 +336,7 @@ void init_vfs(void)
     vfs_mkdir(fs_root, "root");
     vfs_mkfile(fs_root, "init");
 
-    tty_print(console, "/:\n");
-    struct dirent ent { };
-    int i = 0;
-    char buf[256];
-    while (vfs_readdir(fs_root, &ent, i) == GB_OK) {
-        snprintf(buf, 256, "%s: inode(%d)\n", ent.name, ent.ino);
-        tty_print(console, buf);
-        ++i;
-    }
-
-    auto* dev = vfs_findinode(fs_root, "dev");
-    vfs_mkfile(dev, "console");
-    auto* file_console = vfs_findinode(dev, "console");
-
-    tty_print(console, "/dev:\n");
-    i = 0;
-    while (vfs_readdir(dev, &ent, i) == GB_OK) {
-        snprintf(buf, 256, "%s: inode(%d)\n", ent.name, ent.ino);
-        tty_print(console, buf);
-        ++i;
-    }
+    auto* init = vfs_open("/init");
+    const char* str = "#/bin/sh\nexec /bin/sh\n";
+    vfs_write(init, str, 0, strlen(str));
 }

+ 3 - 0
src/kernel_main.c

@@ -185,6 +185,9 @@ void kernel_main(void)
 
     init_vfs();
 
+    struct inode* init = vfs_open("/init");
+    vfs_read(init, buf, 128, 1, 10);
+
     printkf("No work to do, halting...\n");
 
     while (1) {