VirtualFileSystem.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. #include "VirtualFileSystem.h"
  2. #include "FileHandle.h"
  3. #include "FileSystem.h"
  4. #include <AK/StringBuilder.h>
  5. #include <AK/kmalloc.h>
  6. #include <AK/kstdio.h>
  7. #include <AK/ktime.h>
  8. #include "sys-errno.h"
  9. //#define VFS_DEBUG
  10. static dword encodedDevice(unsigned major, unsigned minor)
  11. {
  12. return (minor & 0xff) | (major << 8) | ((minor & ~0xff) << 12);
  13. }
  14. static VirtualFileSystem* s_the;
  15. VirtualFileSystem& VirtualFileSystem::the()
  16. {
  17. ASSERT(s_the);
  18. return *s_the;
  19. }
  20. static SpinLock* s_vfsLock;
  21. SpinLock& VirtualFileSystem::lock()
  22. {
  23. ASSERT(s_vfsLock);
  24. return *s_vfsLock;
  25. }
  26. void VirtualFileSystem::initializeGlobals()
  27. {
  28. s_the = nullptr;
  29. s_vfsLock = new SpinLock;
  30. FileSystem::initializeGlobals();
  31. }
  32. VirtualFileSystem::VirtualFileSystem()
  33. {
  34. #ifdef VFS_DEBUG
  35. kprintf("[VFS] Constructing VFS\n");
  36. #endif
  37. s_the = this;
  38. m_maxNodeCount = 16;
  39. m_nodes = reinterpret_cast<Node*>(kmalloc(sizeof(Node) * maxNodeCount()));
  40. memset(m_nodes, 0, sizeof(Node) * maxNodeCount());
  41. for (unsigned i = 0; i < m_maxNodeCount; ++i)
  42. m_nodeFreeList.append(&m_nodes[i]);
  43. }
  44. VirtualFileSystem::~VirtualFileSystem()
  45. {
  46. kprintf("[VFS] ~VirtualFileSystem with %u nodes allocated\n", allocatedNodeCount());
  47. // FIXME: m_nodes is never freed. Does it matter though?
  48. }
  49. auto VirtualFileSystem::makeNode(InodeIdentifier inode) -> RetainPtr<Node>
  50. {
  51. auto metadata = inode.metadata();
  52. if (!metadata.isValid())
  53. return nullptr;
  54. CharacterDevice* characterDevice = nullptr;
  55. if (metadata.isCharacterDevice()) {
  56. auto it = m_characterDevices.find(encodedDevice(metadata.majorDevice, metadata.minorDevice));
  57. if (it != m_characterDevices.end()) {
  58. characterDevice = (*it).value;
  59. } else {
  60. kprintf("[VFS] makeNode() no such character device %u,%u\n", metadata.majorDevice, metadata.minorDevice);
  61. return nullptr;
  62. }
  63. }
  64. auto vnode = allocateNode();
  65. ASSERT(vnode);
  66. FileSystem* fileSystem = inode.fileSystem();
  67. fileSystem->retain();
  68. vnode->inode = inode;
  69. vnode->m_cachedMetadata = { };
  70. #ifdef VFS_DEBUG
  71. kprintf("makeNode: inode=%u, size=%u, mode=%o, uid=%u, gid=%u\n", inode.index(), metadata.size, metadata.mode, metadata.uid, metadata.gid);
  72. #endif
  73. m_inode2vnode.set(inode, vnode.ptr());
  74. vnode->m_characterDevice = characterDevice;
  75. return vnode;
  76. }
  77. auto VirtualFileSystem::getOrCreateNode(InodeIdentifier inode) -> RetainPtr<Node>
  78. {
  79. auto it = m_inode2vnode.find(inode);
  80. if (it != m_inode2vnode.end())
  81. return (*it).value;
  82. return makeNode(inode);
  83. }
  84. bool VirtualFileSystem::mount(RetainPtr<FileSystem>&& fileSystem, const String& path)
  85. {
  86. ASSERT(fileSystem);
  87. int error;
  88. auto inode = resolvePath(path, error);
  89. if (!inode.isValid()) {
  90. kprintf("[VFS] mount can't resolve mount point '%s'\n", path.characters());
  91. return false;
  92. }
  93. kprintf("mounting %s{%p} at %s (inode: %u)\n", fileSystem->className(), fileSystem.ptr(), path.characters(), inode.index());
  94. // FIXME: check that this is not already a mount point
  95. auto mount = make<Mount>(inode, move(fileSystem));
  96. m_mounts.append(move(mount));
  97. return true;
  98. }
  99. bool VirtualFileSystem::mountRoot(RetainPtr<FileSystem>&& fileSystem)
  100. {
  101. if (m_rootNode) {
  102. kprintf("[VFS] mountRoot can't mount another root\n");
  103. return false;
  104. }
  105. auto mount = make<Mount>(InodeIdentifier(), move(fileSystem));
  106. auto node = makeNode(mount->guest());
  107. if (!node->inUse()) {
  108. kprintf("[VFS] root inode for / is not in use :(\n");
  109. return false;
  110. }
  111. if (!node->inode.metadata().isDirectory()) {
  112. kprintf("[VFS] root inode for / is not in use :(\n");
  113. return false;
  114. }
  115. m_rootNode = move(node);
  116. kprintf("[VFS] mountRoot mounted %s{%p}\n",
  117. m_rootNode->fileSystem()->className(),
  118. m_rootNode->fileSystem());
  119. m_mounts.append(move(mount));
  120. return true;
  121. }
  122. auto VirtualFileSystem::allocateNode() -> RetainPtr<Node>
  123. {
  124. if (m_nodeFreeList.isEmpty()) {
  125. kprintf("[VFS] allocateNode has no nodes left\n");
  126. return nullptr;
  127. }
  128. auto* node = m_nodeFreeList.takeLast();
  129. ASSERT(node->retainCount == 0);
  130. node->retainCount = 1;
  131. node->m_vfs = this;
  132. return adopt(*node);
  133. }
  134. void VirtualFileSystem::freeNode(Node* node)
  135. {
  136. ASSERT(node);
  137. ASSERT(node->inUse());
  138. m_inode2vnode.remove(node->inode);
  139. node->inode.fileSystem()->release();
  140. node->inode = InodeIdentifier();
  141. node->m_characterDevice = nullptr;
  142. m_nodeFreeList.append(move(node));
  143. }
  144. bool VirtualFileSystem::isDirectory(const String& path, InodeIdentifier base)
  145. {
  146. int error;
  147. auto inode = resolvePath(path, error, base);
  148. if (!inode.isValid())
  149. return false;
  150. return inode.metadata().isDirectory();
  151. }
  152. auto VirtualFileSystem::findMountForHost(InodeIdentifier inode) -> Mount*
  153. {
  154. for (auto& mount : m_mounts) {
  155. if (mount->host() == inode)
  156. return mount.ptr();
  157. }
  158. return nullptr;
  159. }
  160. auto VirtualFileSystem::findMountForGuest(InodeIdentifier inode) -> Mount*
  161. {
  162. for (auto& mount : m_mounts) {
  163. if (mount->guest() == inode)
  164. return mount.ptr();
  165. }
  166. return nullptr;
  167. }
  168. bool VirtualFileSystem::isRoot(InodeIdentifier inode) const
  169. {
  170. return inode == m_rootNode->inode;
  171. }
  172. void VirtualFileSystem::enumerateDirectoryInode(InodeIdentifier directoryInode, Function<bool(const FileSystem::DirectoryEntry&)> callback)
  173. {
  174. if (!directoryInode.isValid())
  175. return;
  176. directoryInode.fileSystem()->enumerateDirectoryInode(directoryInode, [&] (const FileSystem::DirectoryEntry& entry) {
  177. InodeIdentifier resolvedInode;
  178. if (auto mount = findMountForHost(entry.inode))
  179. resolvedInode = mount->guest();
  180. else
  181. resolvedInode = entry.inode;
  182. if (directoryInode.isRootInode() && !isRoot(directoryInode) && entry.name == "..") {
  183. auto mount = findMountForGuest(entry.inode);
  184. ASSERT(mount);
  185. resolvedInode = mount->host();
  186. }
  187. callback({ entry.name, resolvedInode });
  188. return true;
  189. });
  190. }
  191. void VirtualFileSystem::listDirectory(const String& path)
  192. {
  193. int error;
  194. auto directoryInode = resolvePath(path, error);
  195. if (!directoryInode.isValid())
  196. return;
  197. kprintf("[VFS] ls %s -> %s %02u:%08u\n", path.characters(), directoryInode.fileSystem()->className(), directoryInode.fileSystemID(), directoryInode.index());
  198. enumerateDirectoryInode(directoryInode, [&] (const FileSystem::DirectoryEntry& entry) {
  199. const char* nameColorBegin = "";
  200. const char* nameColorEnd = "";
  201. auto metadata = entry.inode.metadata();
  202. ASSERT(metadata.isValid());
  203. if (metadata.isDirectory()) {
  204. nameColorBegin = "\033[34;1m";
  205. nameColorEnd = "\033[0m";
  206. } else if (metadata.isSymbolicLink()) {
  207. nameColorBegin = "\033[36;1m";
  208. nameColorEnd = "\033[0m";
  209. }
  210. if (metadata.isSticky()) {
  211. nameColorBegin = "\033[42;30m";
  212. nameColorEnd = "\033[0m";
  213. }
  214. if (metadata.isCharacterDevice() || metadata.isBlockDevice()) {
  215. nameColorBegin = "\033[33;1m";
  216. nameColorEnd = "\033[0m";
  217. }
  218. kprintf("%02u:%08u ",
  219. metadata.inode.fileSystemID(),
  220. metadata.inode.index());
  221. if (metadata.isDirectory())
  222. kprintf("d");
  223. else if (metadata.isSymbolicLink())
  224. kprintf("l");
  225. else if (metadata.isBlockDevice())
  226. kprintf("b");
  227. else if (metadata.isCharacterDevice())
  228. kprintf("c");
  229. else if (metadata.isSocket())
  230. kprintf("s");
  231. else if (metadata.isFIFO())
  232. kprintf("f");
  233. else if (metadata.isRegularFile())
  234. kprintf("-");
  235. else
  236. kprintf("?");
  237. kprintf("%c%c%c%c%c%c%c%c",
  238. metadata.mode & 00400 ? 'r' : '-',
  239. metadata.mode & 00200 ? 'w' : '-',
  240. metadata.mode & 00100 ? 'x' : '-',
  241. metadata.mode & 00040 ? 'r' : '-',
  242. metadata.mode & 00020 ? 'w' : '-',
  243. metadata.mode & 00010 ? 'x' : '-',
  244. metadata.mode & 00004 ? 'r' : '-',
  245. metadata.mode & 00002 ? 'w' : '-'
  246. );
  247. if (metadata.isSticky())
  248. kprintf("t");
  249. else
  250. kprintf("%c", metadata.mode & 00001 ? 'x' : '-');
  251. if (metadata.isCharacterDevice() || metadata.isBlockDevice()) {
  252. char buf[16];
  253. ksprintf(buf, "%u, %u", metadata.majorDevice, metadata.minorDevice);
  254. kprintf("%12s ", buf);
  255. } else {
  256. kprintf("%12lld ", metadata.size);
  257. }
  258. kprintf("\033[30;1m");
  259. time_t mtime = metadata.mtime;
  260. auto tm = *klocaltime(&mtime);
  261. kprintf("%04u-%02u-%02u %02u:%02u:%02u ",
  262. tm.tm_year + 1900,
  263. tm.tm_mon + 1,
  264. tm.tm_mday,
  265. tm.tm_hour,
  266. tm.tm_min,
  267. tm.tm_sec);
  268. kprintf("\033[0m");
  269. kprintf("%s%s%s",
  270. nameColorBegin,
  271. entry.name.characters(),
  272. nameColorEnd);
  273. if (metadata.isDirectory()) {
  274. kprintf("/");
  275. } else if (metadata.isSymbolicLink()) {
  276. auto symlinkContents = directoryInode.fileSystem()->readEntireInode(metadata.inode);
  277. kprintf(" -> %s", String((const char*)symlinkContents.pointer(), symlinkContents.size()).characters());
  278. }
  279. kprintf("\n");
  280. return true;
  281. });
  282. }
  283. void VirtualFileSystem::listDirectoryRecursively(const String& path)
  284. {
  285. int error;
  286. auto directory = resolvePath(path, error);
  287. if (!directory.isValid())
  288. return;
  289. kprintf("%s\n", path.characters());
  290. enumerateDirectoryInode(directory, [&] (const FileSystem::DirectoryEntry& entry) {
  291. auto metadata = entry.inode.metadata();
  292. if (metadata.isDirectory()) {
  293. if (entry.name != "." && entry.name != "..") {
  294. char buf[4096];
  295. ksprintf(buf, "%s/%s", path.characters(), entry.name.characters());
  296. listDirectoryRecursively(buf);
  297. }
  298. } else {
  299. kprintf("%s/%s\n", path.characters(), entry.name.characters());
  300. }
  301. return true;
  302. });
  303. }
  304. bool VirtualFileSystem::touch(const String& path)
  305. {
  306. Locker locker(VirtualFileSystem::lock());
  307. int error;
  308. auto inode = resolvePath(path, error);
  309. if (!inode.isValid())
  310. return false;
  311. return inode.fileSystem()->setModificationTime(inode, ktime(nullptr));
  312. }
  313. OwnPtr<FileHandle> VirtualFileSystem::open(const String& path, int& error, int options, InodeIdentifier base)
  314. {
  315. Locker locker(VirtualFileSystem::lock());
  316. auto inode = resolvePath(path, error, base, options);
  317. if (!inode.isValid())
  318. return nullptr;
  319. auto vnode = getOrCreateNode(inode);
  320. if (!vnode)
  321. return nullptr;
  322. return make<FileHandle>(move(vnode));
  323. }
  324. OwnPtr<FileHandle> VirtualFileSystem::create(const String& path, InodeIdentifier base)
  325. {
  326. Locker locker(VirtualFileSystem::lock());
  327. // FIXME: Do the real thing, not just this fake thing!
  328. (void) path;
  329. m_rootNode->fileSystem()->createInode(m_rootNode->fileSystem()->rootInode(), "empty", 0100644, 0);
  330. return nullptr;
  331. }
  332. OwnPtr<FileHandle> VirtualFileSystem::mkdir(const String& path, InodeIdentifier base)
  333. {
  334. Locker locker(VirtualFileSystem::lock());
  335. // FIXME: Do the real thing, not just this fake thing!
  336. (void) path;
  337. m_rootNode->fileSystem()->makeDirectory(m_rootNode->fileSystem()->rootInode(), "mydir", 0400755);
  338. return nullptr;
  339. }
  340. InodeIdentifier VirtualFileSystem::resolveSymbolicLink(InodeIdentifier base, InodeIdentifier symlinkInode, int& error)
  341. {
  342. auto symlinkContents = symlinkInode.readEntireFile();
  343. if (!symlinkContents)
  344. return { };
  345. return resolvePath((const char*)symlinkContents.pointer(), error, base);
  346. }
  347. String VirtualFileSystem::absolutePath(InodeIdentifier inode)
  348. {
  349. Locker locker(VirtualFileSystem::lock());
  350. if (!inode.isValid())
  351. return String();
  352. int error;
  353. Vector<InodeIdentifier> lineage;
  354. while (inode != m_rootNode->inode) {
  355. if (auto* mount = findMountForGuest(inode))
  356. lineage.append(mount->host());
  357. else
  358. lineage.append(inode);
  359. if (inode.metadata().isDirectory()) {
  360. inode = resolvePath("..", error, inode);
  361. } else
  362. inode = inode.fileSystem()->findParentOfInode(inode);
  363. ASSERT(inode.isValid());
  364. }
  365. if (lineage.isEmpty())
  366. return "/";
  367. lineage.append(m_rootNode->inode);
  368. StringBuilder builder;
  369. for (size_t i = lineage.size() - 1; i >= 1; --i) {
  370. auto& child = lineage[i - 1];
  371. auto parent = lineage[i];
  372. if (auto* mount = findMountForHost(parent))
  373. parent = mount->guest();
  374. builder.append('/');
  375. builder.append(parent.fileSystem()->nameOfChildInDirectory(parent, child));
  376. }
  377. return builder.build();
  378. }
  379. InodeIdentifier VirtualFileSystem::resolvePath(const String& path, int& error, InodeIdentifier base, int options)
  380. {
  381. if (path.isEmpty())
  382. return { };
  383. auto parts = path.split('/');
  384. InodeIdentifier inode;
  385. if (path[0] == '/')
  386. inode = m_rootNode->inode;
  387. else
  388. inode = base.isValid() ? base : m_rootNode->inode;
  389. for (unsigned i = 0; i < parts.size(); ++i) {
  390. bool wasRootInodeAtHeadOfLoop = inode.isRootInode();
  391. auto& part = parts[i];
  392. auto metadata = inode.metadata();
  393. if (!metadata.isValid()) {
  394. #ifdef VFS_DEBUG
  395. kprintf("invalid metadata\n");
  396. #endif
  397. error = -EIO;
  398. return { };
  399. }
  400. if (!metadata.isDirectory()) {
  401. #ifdef VFS_DEBUG
  402. kprintf("not directory\n");
  403. #endif
  404. error = -EIO;
  405. return { };
  406. }
  407. auto parent = inode;
  408. inode = inode.fileSystem()->childOfDirectoryInodeWithName(inode, part);
  409. if (!inode.isValid()) {
  410. #ifdef VFS_DEBUG
  411. kprintf("bad child\n");
  412. #endif
  413. error = -ENOENT;
  414. return { };
  415. }
  416. #ifdef VFS_DEBUG
  417. kprintf("<%s> %u:%u\n", part.characters(), inode.fileSystemID(), inode.index());
  418. #endif
  419. if (auto mount = findMountForHost(inode)) {
  420. #ifdef VFS_DEBUG
  421. kprintf(" -- is host\n");
  422. #endif
  423. inode = mount->guest();
  424. }
  425. if (wasRootInodeAtHeadOfLoop && inode.isRootInode() && !isRoot(inode) && part == "..") {
  426. #ifdef VFS_DEBUG
  427. kprintf(" -- is guest\n");
  428. #endif
  429. auto mount = findMountForGuest(inode);
  430. inode = mount->host();
  431. inode = inode.fileSystem()->childOfDirectoryInodeWithName(inode, "..");
  432. }
  433. metadata = inode.metadata();
  434. if (metadata.isSymbolicLink()) {
  435. if (i == parts.size() - 1) {
  436. if (options & O_NOFOLLOW) {
  437. error = -ELOOP;
  438. return { };
  439. }
  440. if (options & O_NOFOLLOW_NOERROR)
  441. return inode;
  442. }
  443. char buf[4096] = "";
  444. char* p = buf;
  445. for (unsigned j = 0; j < i; ++j) {
  446. p += ksprintf(p, "/%s", parts[j].characters());
  447. }
  448. inode = resolveSymbolicLink(parent, inode, error);
  449. if (!inode.isValid()) {
  450. kprintf("Symbolic link resolution failed :(\n");
  451. return { };
  452. }
  453. }
  454. }
  455. return inode;
  456. }
  457. void VirtualFileSystem::Node::retain()
  458. {
  459. ++retainCount;
  460. }
  461. void VirtualFileSystem::Node::release()
  462. {
  463. ASSERT(retainCount);
  464. if (--retainCount == 0) {
  465. m_vfs->freeNode(this);
  466. }
  467. }
  468. const InodeMetadata& VirtualFileSystem::Node::metadata() const
  469. {
  470. if (!m_cachedMetadata.isValid())
  471. m_cachedMetadata = inode.metadata();
  472. return m_cachedMetadata;
  473. }
  474. VirtualFileSystem::Mount::Mount(InodeIdentifier host, RetainPtr<FileSystem>&& guestFileSystem)
  475. : m_host(host)
  476. , m_guest(guestFileSystem->rootInode())
  477. , m_fileSystem(move(guestFileSystem))
  478. {
  479. }
  480. void VirtualFileSystem::registerCharacterDevice(unsigned major, unsigned minor, CharacterDevice& device)
  481. {
  482. m_characterDevices.set(encodedDevice(major, minor), &device);
  483. }
  484. void VirtualFileSystem::forEachMount(Function<void(const Mount&)> callback) const
  485. {
  486. for (auto& mount : m_mounts) {
  487. callback(*mount);
  488. }
  489. }