ProcFS.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108
  1. #include "ProcFS.h"
  2. #include "Console.h"
  3. #include "KSyms.h"
  4. #include "Process.h"
  5. #include "Scheduler.h"
  6. #include "StdLib.h"
  7. #include <AK/JsonArray.h>
  8. #include <AK/JsonObject.h>
  9. #include <AK/JsonValue.h>
  10. #include <AK/StringBuilder.h>
  11. #include <Kernel/Arch/i386/CPU.h>
  12. #include <Kernel/FileSystem/Custody.h>
  13. #include <Kernel/FileSystem/FileDescription.h>
  14. #include <Kernel/FileSystem/VirtualFileSystem.h>
  15. #include <Kernel/KParams.h>
  16. #include <Kernel/Net/NetworkAdapter.h>
  17. #include <Kernel/PCI.h>
  18. #include <Kernel/VM/MemoryManager.h>
  19. #include <Kernel/kmalloc.h>
  20. #include <LibC/errno_numbers.h>
  21. enum ProcParentDirectory {
  22. PDI_AbstractRoot = 0,
  23. PDI_Root,
  24. PDI_Root_sys,
  25. PDI_PID,
  26. PDI_PID_fd,
  27. };
  28. enum ProcFileType {
  29. FI_Invalid = 0,
  30. FI_Root = 1, // directory
  31. __FI_Root_Start,
  32. FI_Root_mm,
  33. FI_Root_mounts,
  34. FI_Root_df,
  35. FI_Root_kmalloc,
  36. FI_Root_all,
  37. FI_Root_memstat,
  38. FI_Root_cpuinfo,
  39. FI_Root_inodes,
  40. FI_Root_dmesg,
  41. FI_Root_pci,
  42. FI_Root_uptime,
  43. FI_Root_cmdline,
  44. FI_Root_netadapters,
  45. FI_Root_self, // symlink
  46. FI_Root_sys, // directory
  47. __FI_Root_End,
  48. FI_PID,
  49. __FI_PID_Start,
  50. FI_PID_vm,
  51. FI_PID_vmo,
  52. FI_PID_stack,
  53. FI_PID_regs,
  54. FI_PID_fds,
  55. FI_PID_exe, // symlink
  56. FI_PID_cwd, // symlink
  57. FI_PID_fd, // directory
  58. __FI_PID_End,
  59. FI_MaxStaticFileIndex,
  60. };
  61. static inline pid_t to_pid(const InodeIdentifier& identifier)
  62. {
  63. #ifdef PROCFS_DEBUG
  64. dbgprintf("to_pid, index=%08x -> %u\n", identifier.index(), identifier.index() >> 16);
  65. #endif
  66. return identifier.index() >> 16u;
  67. }
  68. static inline ProcParentDirectory to_proc_parent_directory(const InodeIdentifier& identifier)
  69. {
  70. return (ProcParentDirectory)((identifier.index() >> 12) & 0xf);
  71. }
  72. static inline int to_fd(const InodeIdentifier& identifier)
  73. {
  74. ASSERT(to_proc_parent_directory(identifier) == PDI_PID_fd);
  75. return (identifier.index() & 0xff) - FI_MaxStaticFileIndex;
  76. }
  77. static inline int to_sys_index(const InodeIdentifier& identifier)
  78. {
  79. ASSERT(to_proc_parent_directory(identifier) == PDI_Root_sys);
  80. return identifier.index() & 0xff;
  81. }
  82. static inline InodeIdentifier to_identifier(unsigned fsid, ProcParentDirectory parent, pid_t pid, ProcFileType proc_file_type)
  83. {
  84. return { fsid, ((unsigned)parent << 12u) | ((unsigned)pid << 16u) | (unsigned)proc_file_type };
  85. }
  86. static inline InodeIdentifier to_identifier_with_fd(unsigned fsid, pid_t pid, int fd)
  87. {
  88. return { fsid, (PDI_PID_fd << 12u) | ((unsigned)pid << 16u) | (FI_MaxStaticFileIndex + fd) };
  89. }
  90. static inline InodeIdentifier sys_var_to_identifier(unsigned fsid, unsigned index)
  91. {
  92. ASSERT(index < 256);
  93. return { fsid, (PDI_Root_sys << 12u) | index };
  94. }
  95. static inline InodeIdentifier to_parent_id(const InodeIdentifier& identifier)
  96. {
  97. switch (to_proc_parent_directory(identifier)) {
  98. case PDI_AbstractRoot:
  99. case PDI_Root:
  100. return { identifier.fsid(), FI_Root };
  101. case PDI_Root_sys:
  102. return { identifier.fsid(), FI_Root_sys };
  103. case PDI_PID:
  104. return to_identifier(identifier.fsid(), PDI_Root, to_pid(identifier), FI_PID);
  105. case PDI_PID_fd:
  106. return to_identifier(identifier.fsid(), PDI_PID, to_pid(identifier), FI_PID_fd);
  107. }
  108. ASSERT_NOT_REACHED();
  109. }
  110. #if 0
  111. static inline u8 to_unused_metadata(const InodeIdentifier& identifier)
  112. {
  113. return (identifier.index() >> 8) & 0xf;
  114. }
  115. #endif
  116. static inline ProcFileType to_proc_file_type(const InodeIdentifier& identifier)
  117. {
  118. return (ProcFileType)(identifier.index() & 0xff);
  119. }
  120. static inline bool is_process_related_file(const InodeIdentifier& identifier)
  121. {
  122. if (to_proc_file_type(identifier) == FI_PID)
  123. return true;
  124. auto proc_parent_directory = to_proc_parent_directory(identifier);
  125. switch (proc_parent_directory) {
  126. case PDI_PID:
  127. case PDI_PID_fd:
  128. return true;
  129. default:
  130. return false;
  131. }
  132. }
  133. static inline bool is_directory(const InodeIdentifier& identifier)
  134. {
  135. auto proc_file_type = to_proc_file_type(identifier);
  136. switch (proc_file_type) {
  137. case FI_Root:
  138. case FI_Root_sys:
  139. case FI_PID:
  140. case FI_PID_fd:
  141. return true;
  142. default:
  143. return false;
  144. }
  145. }
  146. static inline bool is_persistent_inode(const InodeIdentifier& identifier)
  147. {
  148. return to_proc_parent_directory(identifier) == PDI_Root_sys;
  149. }
  150. static ProcFS* s_the;
  151. ProcFS& ProcFS::the()
  152. {
  153. ASSERT(s_the);
  154. return *s_the;
  155. }
  156. NonnullRefPtr<ProcFS> ProcFS::create()
  157. {
  158. return adopt(*new ProcFS);
  159. }
  160. ProcFS::~ProcFS()
  161. {
  162. }
  163. ByteBuffer procfs$pid_fds(InodeIdentifier identifier)
  164. {
  165. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  166. if (!handle)
  167. return {};
  168. auto& process = handle->process();
  169. if (process.number_of_open_file_descriptors() == 0)
  170. return {};
  171. StringBuilder builder;
  172. for (int i = 0; i < process.max_open_file_descriptors(); ++i) {
  173. auto* description = process.file_description(i);
  174. if (!description)
  175. continue;
  176. builder.appendf("%-3u %s\n", i, description->absolute_path().characters());
  177. }
  178. return builder.to_byte_buffer();
  179. }
  180. ByteBuffer procfs$pid_fd_entry(InodeIdentifier identifier)
  181. {
  182. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  183. if (!handle)
  184. return {};
  185. auto& process = handle->process();
  186. int fd = to_fd(identifier);
  187. auto* description = process.file_description(fd);
  188. if (!description)
  189. return {};
  190. return description->absolute_path().to_byte_buffer();
  191. }
  192. ByteBuffer procfs$pid_vm(InodeIdentifier identifier)
  193. {
  194. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  195. if (!handle)
  196. return {};
  197. auto& process = handle->process();
  198. JsonArray array;
  199. for (auto& region : process.regions()) {
  200. JsonObject region_object;
  201. region_object.set("readable", region.is_readable());
  202. region_object.set("writable", region.is_writable());
  203. region_object.set("address", region.vaddr().get());
  204. region_object.set("size", region.size());
  205. region_object.set("amount_resident", region.amount_resident());
  206. region_object.set("name", region.name());
  207. array.append(move(region_object));
  208. }
  209. return array.serialized().to_byte_buffer();
  210. }
  211. ByteBuffer procfs$pci(InodeIdentifier)
  212. {
  213. StringBuilder builder;
  214. PCI::enumerate_all([&builder](PCI::Address address, PCI::ID id) {
  215. builder.appendf("%b:%b.%b %w:%w\n", address.bus(), address.slot(), address.function(), id.vendor_id, id.device_id);
  216. });
  217. return builder.to_byte_buffer();
  218. }
  219. ByteBuffer procfs$uptime(InodeIdentifier)
  220. {
  221. StringBuilder builder;
  222. builder.appendf("%u\n", (u32)(g_uptime / 1000));
  223. return builder.to_byte_buffer();
  224. }
  225. ByteBuffer procfs$cmdline(InodeIdentifier)
  226. {
  227. StringBuilder builder;
  228. builder.appendf("%s\n", KParams::the().cmdline().characters());
  229. return builder.to_byte_buffer();
  230. }
  231. ByteBuffer procfs$netadapters(InodeIdentifier)
  232. {
  233. StringBuilder builder;
  234. NetworkAdapter::for_each([&builder](auto& adapter) {
  235. builder.appendf("%s,%s,%s,%s\n",
  236. adapter.name().characters(),
  237. adapter.class_name(),
  238. adapter.mac_address().to_string().characters(),
  239. adapter.ipv4_address().to_string().characters());
  240. });
  241. return builder.to_byte_buffer();
  242. }
  243. ByteBuffer procfs$pid_vmo(InodeIdentifier identifier)
  244. {
  245. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  246. if (!handle)
  247. return {};
  248. auto& process = handle->process();
  249. StringBuilder builder;
  250. builder.appendf("BEGIN END SIZE NAME\n");
  251. for (auto& region : process.regions()) {
  252. builder.appendf("%x -- %x %x %s\n",
  253. region.vaddr().get(),
  254. region.vaddr().offset(region.size() - 1).get(),
  255. region.size(),
  256. region.name().characters());
  257. builder.appendf("VMO: %s \"%s\" @ %x(%u)\n",
  258. region.vmo().is_anonymous() ? "anonymous" : "file-backed",
  259. region.vmo().name().characters(),
  260. &region.vmo(),
  261. region.vmo().ref_count());
  262. for (int i = 0; i < region.vmo().page_count(); ++i) {
  263. auto& physical_page = region.vmo().physical_pages()[i];
  264. builder.appendf("P%x%s(%u) ",
  265. physical_page ? physical_page->paddr().get() : 0,
  266. region.should_cow(i) ? "!" : "",
  267. physical_page ? physical_page->ref_count() : 0);
  268. }
  269. builder.appendf("\n");
  270. }
  271. return builder.to_byte_buffer();
  272. }
  273. ByteBuffer procfs$pid_stack(InodeIdentifier identifier)
  274. {
  275. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  276. if (!handle)
  277. return {};
  278. auto& process = handle->process();
  279. return process.backtrace(*handle).to_byte_buffer();
  280. }
  281. ByteBuffer procfs$pid_regs(InodeIdentifier identifier)
  282. {
  283. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  284. if (!handle)
  285. return {};
  286. auto& process = handle->process();
  287. StringBuilder builder;
  288. process.for_each_thread([&](Thread& thread) {
  289. builder.appendf("Thread %d:\n", thread.tid());
  290. auto& tss = thread.tss();
  291. builder.appendf("eax: %x\n", tss.eax);
  292. builder.appendf("ebx: %x\n", tss.ebx);
  293. builder.appendf("ecx: %x\n", tss.ecx);
  294. builder.appendf("edx: %x\n", tss.edx);
  295. builder.appendf("esi: %x\n", tss.esi);
  296. builder.appendf("edi: %x\n", tss.edi);
  297. builder.appendf("ebp: %x\n", tss.ebp);
  298. builder.appendf("cr3: %x\n", tss.cr3);
  299. builder.appendf("flg: %x\n", tss.eflags);
  300. builder.appendf("sp: %w:%x\n", tss.ss, tss.esp);
  301. builder.appendf("pc: %w:%x\n", tss.cs, tss.eip);
  302. return IterationDecision::Continue;
  303. });
  304. return builder.to_byte_buffer();
  305. }
  306. ByteBuffer procfs$pid_exe(InodeIdentifier identifier)
  307. {
  308. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  309. if (!handle)
  310. return {};
  311. auto& process = handle->process();
  312. auto* custody = process.executable();
  313. ASSERT(custody);
  314. return custody->absolute_path().to_byte_buffer();
  315. }
  316. ByteBuffer procfs$pid_cwd(InodeIdentifier identifier)
  317. {
  318. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  319. if (!handle)
  320. return {};
  321. return handle->process().current_directory().absolute_path().to_byte_buffer();
  322. }
  323. ByteBuffer procfs$self(InodeIdentifier)
  324. {
  325. char buffer[16];
  326. ksprintf(buffer, "%u", current->pid());
  327. return ByteBuffer::copy((const u8*)buffer, strlen(buffer));
  328. }
  329. ByteBuffer procfs$mm(InodeIdentifier)
  330. {
  331. // FIXME: Implement
  332. InterruptDisabler disabler;
  333. StringBuilder builder;
  334. for (auto* vmo : MM.m_vmos) {
  335. builder.appendf("VMO: %p %s(%u): p:%4u %s\n",
  336. vmo,
  337. vmo->is_anonymous() ? "anon" : "file",
  338. vmo->ref_count(),
  339. vmo->page_count(),
  340. vmo->name().characters());
  341. }
  342. builder.appendf("VMO count: %u\n", MM.m_vmos.size());
  343. builder.appendf("Free physical pages: %u\n", MM.user_physical_pages() - MM.user_physical_pages_used());
  344. builder.appendf("Free supervisor physical pages: %u\n", MM.super_physical_pages() - MM.super_physical_pages_used());
  345. return builder.to_byte_buffer();
  346. }
  347. ByteBuffer procfs$dmesg(InodeIdentifier)
  348. {
  349. InterruptDisabler disabler;
  350. StringBuilder builder;
  351. for (char ch : Console::the().logbuffer())
  352. builder.append(ch);
  353. return builder.to_byte_buffer();
  354. }
  355. ByteBuffer procfs$mounts(InodeIdentifier)
  356. {
  357. // FIXME: This is obviously racy against the VFS mounts changing.
  358. StringBuilder builder;
  359. VFS::the().for_each_mount([&builder](auto& mount) {
  360. auto& fs = mount.guest_fs();
  361. builder.appendf("%s @ ", fs.class_name());
  362. if (!mount.host().is_valid())
  363. builder.appendf("/");
  364. else {
  365. builder.appendf("%u:%u", mount.host().fsid(), mount.host().index());
  366. builder.append(' ');
  367. builder.append(mount.absolute_path());
  368. }
  369. builder.append('\n');
  370. });
  371. return builder.to_byte_buffer();
  372. }
  373. ByteBuffer procfs$df(InodeIdentifier)
  374. {
  375. // FIXME: This is obviously racy against the VFS mounts changing.
  376. JsonArray json;
  377. VFS::the().for_each_mount([&json](auto& mount) {
  378. auto& fs = mount.guest_fs();
  379. JsonObject fs_object;
  380. fs_object.set("class_name", fs.class_name());
  381. fs_object.set("total_block_count", fs.total_block_count());
  382. fs_object.set("free_block_count", fs.free_block_count());
  383. fs_object.set("total_inode_count", fs.total_inode_count());
  384. fs_object.set("free_inode_count", fs.free_inode_count());
  385. fs_object.set("mount_point", mount.absolute_path());
  386. json.append(fs_object);
  387. });
  388. return json.serialized().to_byte_buffer();
  389. }
  390. ByteBuffer procfs$cpuinfo(InodeIdentifier)
  391. {
  392. StringBuilder builder;
  393. {
  394. CPUID cpuid(0);
  395. builder.appendf("cpuid: ");
  396. auto emit_u32 = [&](u32 value) {
  397. builder.appendf("%c%c%c%c",
  398. value & 0xff,
  399. (value >> 8) & 0xff,
  400. (value >> 16) & 0xff,
  401. (value >> 24) & 0xff);
  402. };
  403. emit_u32(cpuid.ebx());
  404. emit_u32(cpuid.edx());
  405. emit_u32(cpuid.ecx());
  406. builder.appendf("\n");
  407. }
  408. {
  409. CPUID cpuid(1);
  410. u32 stepping = cpuid.eax() & 0xf;
  411. u32 model = (cpuid.eax() >> 4) & 0xf;
  412. u32 family = (cpuid.eax() >> 8) & 0xf;
  413. u32 type = (cpuid.eax() >> 12) & 0x3;
  414. u32 extended_model = (cpuid.eax() >> 16) & 0xf;
  415. u32 extended_family = (cpuid.eax() >> 20) & 0xff;
  416. u32 display_model;
  417. u32 display_family;
  418. if (family == 15) {
  419. display_family = family + extended_family;
  420. display_model = model + (extended_model << 4);
  421. } else if (family == 6) {
  422. display_family = family;
  423. display_model = model + (extended_model << 4);
  424. } else {
  425. display_family = family;
  426. display_model = model;
  427. }
  428. builder.appendf("family: %u\n", display_family);
  429. builder.appendf("model: %u\n", display_model);
  430. builder.appendf("stepping: %u\n", stepping);
  431. builder.appendf("type: %u\n", type);
  432. }
  433. {
  434. // FIXME: Check first that this is supported by calling CPUID with eax=0x80000000
  435. // and verifying that the returned eax>=0x80000004.
  436. char buffer[48];
  437. u32* bufptr = reinterpret_cast<u32*>(buffer);
  438. auto copy_brand_string_part_to_buffer = [&](u32 i) {
  439. CPUID cpuid(0x80000002 + i);
  440. *bufptr++ = cpuid.eax();
  441. *bufptr++ = cpuid.ebx();
  442. *bufptr++ = cpuid.ecx();
  443. *bufptr++ = cpuid.edx();
  444. };
  445. copy_brand_string_part_to_buffer(0);
  446. copy_brand_string_part_to_buffer(1);
  447. copy_brand_string_part_to_buffer(2);
  448. builder.appendf("brandstr: \"%s\"\n", buffer);
  449. }
  450. return builder.to_byte_buffer();
  451. }
  452. ByteBuffer procfs$kmalloc(InodeIdentifier)
  453. {
  454. StringBuilder builder;
  455. builder.appendf(
  456. "eternal: %u\n"
  457. "allocated: %u\n"
  458. "free: %u\n",
  459. kmalloc_sum_eternal,
  460. sum_alloc,
  461. sum_free);
  462. return builder.to_byte_buffer();
  463. }
  464. ByteBuffer procfs$memstat(InodeIdentifier)
  465. {
  466. InterruptDisabler disabler;
  467. JsonObject json;
  468. json.set("kmalloc_allocated", sum_alloc);
  469. json.set("kmalloc_available", sum_free);
  470. json.set("kmalloc_eternal_allocated", kmalloc_sum_eternal);
  471. json.set("user_physical_allocated", MM.user_physical_pages_used());
  472. json.set("user_physical_available", MM.user_physical_pages());
  473. json.set("super_physical_allocated", MM.super_physical_pages_used());
  474. json.set("super_physical_available", MM.super_physical_pages());
  475. json.set("kmalloc_call_count", g_kmalloc_call_count);
  476. json.set("kfree_call_count", g_kfree_call_count);
  477. return json.serialized().to_byte_buffer();
  478. }
  479. ByteBuffer procfs$all(InodeIdentifier)
  480. {
  481. InterruptDisabler disabler;
  482. auto processes = Process::all_processes();
  483. JsonArray array;
  484. // Keep this in sync with CProcessStatistics.
  485. auto build_process = [&](const Process& process) {
  486. JsonObject process_object;
  487. process_object.set("pid", process.pid());
  488. process_object.set("times_scheduled", process.main_thread().times_scheduled());
  489. process_object.set("pgid", process.tty() ? process.tty()->pgid() : 0);
  490. process_object.set("pgp", process.pgid());
  491. process_object.set("sid", process.sid());
  492. process_object.set("uid", process.uid());
  493. process_object.set("gid", process.gid());
  494. process_object.set("state", process.main_thread().state_string());
  495. process_object.set("ppid", process.ppid());
  496. process_object.set("nfds", process.number_of_open_file_descriptors());
  497. process_object.set("name", process.name());
  498. process_object.set("tty", process.tty() ? process.tty()->tty_name() : "notty");
  499. process_object.set("amount_virtual", process.amount_virtual());
  500. process_object.set("amount_resident", process.amount_resident());
  501. process_object.set("amount_shared", process.amount_shared());
  502. process_object.set("ticks", process.main_thread().ticks());
  503. process_object.set("priority", to_string(process.priority()));
  504. process_object.set("syscall_count", process.syscall_count());
  505. process_object.set("icon_id", process.icon_id());
  506. array.append(process_object);
  507. };
  508. build_process(*Scheduler::colonel());
  509. for (auto* process : processes)
  510. build_process(*process);
  511. return array.serialized().to_byte_buffer();
  512. }
  513. ByteBuffer procfs$inodes(InodeIdentifier)
  514. {
  515. extern HashTable<Inode*>& all_inodes();
  516. StringBuilder builder;
  517. for (auto it : all_inodes()) {
  518. RefPtr<Inode> inode = *it;
  519. builder.appendf("Inode{K%x} %02u:%08u (%u)\n", inode.ptr(), inode->fsid(), inode->index(), inode->ref_count());
  520. }
  521. return builder.to_byte_buffer();
  522. }
  523. struct SysVariableData final : public ProcFSInodeCustomData {
  524. virtual ~SysVariableData() override {}
  525. enum Type {
  526. Invalid,
  527. Boolean,
  528. String,
  529. };
  530. Type type { Invalid };
  531. Function<void()> notify_callback;
  532. void* address;
  533. };
  534. static ByteBuffer read_sys_bool(InodeIdentifier inode_id)
  535. {
  536. auto inode_ptr = ProcFS::the().get_inode(inode_id);
  537. if (!inode_ptr)
  538. return {};
  539. auto& inode = static_cast<ProcFSInode&>(*inode_ptr);
  540. ASSERT(inode.custom_data());
  541. auto buffer = ByteBuffer::create_uninitialized(2);
  542. auto& custom_data = *static_cast<const SysVariableData*>(inode.custom_data());
  543. ASSERT(custom_data.type == SysVariableData::Boolean);
  544. ASSERT(custom_data.address);
  545. auto* lockable_bool = reinterpret_cast<Lockable<bool>*>(custom_data.address);
  546. {
  547. LOCKER(lockable_bool->lock());
  548. buffer[0] = lockable_bool->resource() ? '1' : '0';
  549. }
  550. buffer[1] = '\n';
  551. return buffer;
  552. }
  553. static ssize_t write_sys_bool(InodeIdentifier inode_id, const ByteBuffer& data)
  554. {
  555. auto inode_ptr = ProcFS::the().get_inode(inode_id);
  556. if (!inode_ptr)
  557. return {};
  558. auto& inode = static_cast<ProcFSInode&>(*inode_ptr);
  559. ASSERT(inode.custom_data());
  560. if (data.is_empty() || !(data[0] == '0' || data[0] == '1'))
  561. return data.size();
  562. auto& custom_data = *static_cast<const SysVariableData*>(inode.custom_data());
  563. auto* lockable_bool = reinterpret_cast<Lockable<bool>*>(custom_data.address);
  564. {
  565. LOCKER(lockable_bool->lock());
  566. lockable_bool->resource() = data[0] == '1';
  567. }
  568. if (custom_data.notify_callback)
  569. custom_data.notify_callback();
  570. return data.size();
  571. }
  572. static ByteBuffer read_sys_string(InodeIdentifier inode_id)
  573. {
  574. auto inode_ptr = ProcFS::the().get_inode(inode_id);
  575. if (!inode_ptr)
  576. return {};
  577. auto& inode = static_cast<ProcFSInode&>(*inode_ptr);
  578. ASSERT(inode.custom_data());
  579. auto buffer = ByteBuffer::create_uninitialized(2);
  580. auto& custom_data = *static_cast<const SysVariableData*>(inode.custom_data());
  581. ASSERT(custom_data.type == SysVariableData::String);
  582. ASSERT(custom_data.address);
  583. auto* lockable_string = reinterpret_cast<Lockable<String>*>(custom_data.address);
  584. LOCKER(lockable_string->lock());
  585. return lockable_string->resource().to_byte_buffer();
  586. }
  587. static ssize_t write_sys_string(InodeIdentifier inode_id, const ByteBuffer& data)
  588. {
  589. auto inode_ptr = ProcFS::the().get_inode(inode_id);
  590. if (!inode_ptr)
  591. return {};
  592. auto& inode = static_cast<ProcFSInode&>(*inode_ptr);
  593. ASSERT(inode.custom_data());
  594. auto& custom_data = *static_cast<const SysVariableData*>(inode.custom_data());
  595. ASSERT(custom_data.address);
  596. {
  597. auto* lockable_string = reinterpret_cast<Lockable<String>*>(custom_data.address);
  598. LOCKER(lockable_string->lock());
  599. lockable_string->resource() = String((const char*)data.pointer(), data.size());
  600. }
  601. if (custom_data.notify_callback)
  602. custom_data.notify_callback();
  603. return data.size();
  604. }
  605. void ProcFS::add_sys_bool(String&& name, Lockable<bool>& var, Function<void()>&& notify_callback)
  606. {
  607. InterruptDisabler disabler;
  608. int index = m_sys_entries.size();
  609. auto inode = adopt(*new ProcFSInode(*this, sys_var_to_identifier(fsid(), index).index()));
  610. auto data = make<SysVariableData>();
  611. data->type = SysVariableData::Boolean;
  612. data->notify_callback = move(notify_callback);
  613. data->address = &var;
  614. inode->set_custom_data(move(data));
  615. m_sys_entries.append({ strdup(name.characters()), 0, read_sys_bool, write_sys_bool, move(inode) });
  616. }
  617. void ProcFS::add_sys_string(String&& name, Lockable<String>& var, Function<void()>&& notify_callback)
  618. {
  619. InterruptDisabler disabler;
  620. int index = m_sys_entries.size();
  621. auto inode = adopt(*new ProcFSInode(*this, sys_var_to_identifier(fsid(), index).index()));
  622. auto data = make<SysVariableData>();
  623. data->type = SysVariableData::String;
  624. data->notify_callback = move(notify_callback);
  625. data->address = &var;
  626. inode->set_custom_data(move(data));
  627. m_sys_entries.append({ strdup(name.characters()), 0, read_sys_string, write_sys_string, move(inode) });
  628. }
  629. bool ProcFS::initialize()
  630. {
  631. return true;
  632. }
  633. const char* ProcFS::class_name() const
  634. {
  635. return "ProcFS";
  636. }
  637. RefPtr<Inode> ProcFS::create_inode(InodeIdentifier, const String&, mode_t, off_t, dev_t, int&)
  638. {
  639. kprintf("FIXME: Implement ProcFS::create_inode()?\n");
  640. return {};
  641. }
  642. RefPtr<Inode> ProcFS::create_directory(InodeIdentifier, const String&, mode_t, int& error)
  643. {
  644. error = -EROFS;
  645. return nullptr;
  646. }
  647. InodeIdentifier ProcFS::root_inode() const
  648. {
  649. return { fsid(), FI_Root };
  650. }
  651. RefPtr<Inode> ProcFS::get_inode(InodeIdentifier inode_id) const
  652. {
  653. #ifdef PROCFS_DEBUG
  654. dbgprintf("ProcFS::get_inode(%u)\n", inode_id.index());
  655. #endif
  656. if (inode_id == root_inode())
  657. return m_root_inode;
  658. if (to_proc_parent_directory(inode_id) == ProcParentDirectory::PDI_Root_sys) {
  659. auto sys_index = to_sys_index(inode_id);
  660. if (sys_index < m_sys_entries.size())
  661. return m_sys_entries[sys_index].inode;
  662. }
  663. LOCKER(m_inodes_lock);
  664. auto it = m_inodes.find(inode_id.index());
  665. if (it == m_inodes.end()) {
  666. auto inode = adopt(*new ProcFSInode(const_cast<ProcFS&>(*this), inode_id.index()));
  667. m_inodes.set(inode_id.index(), inode.ptr());
  668. return inode;
  669. }
  670. return (*it).value;
  671. }
  672. ProcFSInode::ProcFSInode(ProcFS& fs, unsigned index)
  673. : Inode(fs, index)
  674. {
  675. }
  676. ProcFSInode::~ProcFSInode()
  677. {
  678. LOCKER(fs().m_inodes_lock);
  679. fs().m_inodes.remove(index());
  680. }
  681. InodeMetadata ProcFSInode::metadata() const
  682. {
  683. #ifdef PROCFS_DEBUG
  684. dbgprintf("ProcFSInode::metadata(%u)\n", index());
  685. #endif
  686. InodeMetadata metadata;
  687. metadata.inode = identifier();
  688. metadata.ctime = mepoch;
  689. metadata.atime = mepoch;
  690. metadata.mtime = mepoch;
  691. auto proc_parent_directory = to_proc_parent_directory(identifier());
  692. auto pid = to_pid(identifier());
  693. auto proc_file_type = to_proc_file_type(identifier());
  694. #ifdef PROCFS_DEBUG
  695. dbgprintf(" -> pid: %d, fi: %u, pdi: %u\n", pid, proc_file_type, proc_parent_directory);
  696. #endif
  697. if (is_process_related_file(identifier())) {
  698. auto handle = ProcessInspectionHandle::from_pid(pid);
  699. metadata.uid = handle->process().sys$getuid();
  700. metadata.gid = handle->process().sys$getgid();
  701. }
  702. if (proc_parent_directory == PDI_PID_fd) {
  703. metadata.mode = 00120777;
  704. return metadata;
  705. }
  706. if (proc_parent_directory == PDI_Root_sys) {
  707. metadata.mode = 00100644;
  708. return metadata;
  709. }
  710. switch (proc_file_type) {
  711. case FI_Root_self:
  712. case FI_PID_cwd:
  713. case FI_PID_exe:
  714. metadata.mode = 0120777;
  715. break;
  716. case FI_Root:
  717. case FI_Root_sys:
  718. case FI_PID:
  719. case FI_PID_fd:
  720. metadata.mode = 040777;
  721. break;
  722. default:
  723. metadata.mode = 0100644;
  724. break;
  725. }
  726. #ifdef PROCFS_DEBUG
  727. dbgprintf("Returning mode %o\n", metadata.mode);
  728. #endif
  729. return metadata;
  730. }
  731. ssize_t ProcFSInode::read_bytes(off_t offset, ssize_t count, u8* buffer, FileDescription* description) const
  732. {
  733. #ifdef PROCFS_DEBUG
  734. dbgprintf("ProcFS: read_bytes %u\n", index());
  735. #endif
  736. ASSERT(offset >= 0);
  737. ASSERT(buffer);
  738. auto* directory_entry = fs().get_directory_entry(identifier());
  739. Function<ByteBuffer(InodeIdentifier)> callback_tmp;
  740. Function<ByteBuffer(InodeIdentifier)>* read_callback { nullptr };
  741. if (directory_entry) {
  742. read_callback = &directory_entry->read_callback;
  743. } else {
  744. if (to_proc_parent_directory(identifier()) == PDI_PID_fd) {
  745. callback_tmp = procfs$pid_fd_entry;
  746. read_callback = &callback_tmp;
  747. }
  748. }
  749. ASSERT(read_callback);
  750. ByteBuffer generated_data;
  751. if (!description) {
  752. generated_data = (*read_callback)(identifier());
  753. } else {
  754. if (!description->generator_cache())
  755. description->generator_cache() = (*read_callback)(identifier());
  756. generated_data = description->generator_cache();
  757. }
  758. auto& data = generated_data;
  759. ssize_t nread = min(static_cast<off_t>(data.size() - offset), static_cast<off_t>(count));
  760. memcpy(buffer, data.pointer() + offset, nread);
  761. if (nread == 0 && description && description->generator_cache())
  762. description->generator_cache().clear();
  763. return nread;
  764. }
  765. InodeIdentifier ProcFS::ProcFSDirectoryEntry::identifier(unsigned fsid) const
  766. {
  767. return to_identifier(fsid, PDI_Root, 0, (ProcFileType)proc_file_type);
  768. }
  769. bool ProcFSInode::traverse_as_directory(Function<bool(const FS::DirectoryEntry&)> callback) const
  770. {
  771. #ifdef PROCFS_DEBUG
  772. dbgprintf("ProcFS: traverse_as_directory %u\n", index());
  773. #endif
  774. if (!::is_directory(identifier()))
  775. return false;
  776. auto pid = to_pid(identifier());
  777. auto proc_file_type = to_proc_file_type(identifier());
  778. auto parent_id = to_parent_id(identifier());
  779. callback({ ".", 1, identifier(), 2 });
  780. callback({ "..", 2, parent_id, 2 });
  781. switch (proc_file_type) {
  782. case FI_Root:
  783. for (auto& entry : fs().m_entries) {
  784. // FIXME: strlen() here is sad.
  785. if (!entry.name)
  786. continue;
  787. if (entry.proc_file_type > __FI_Root_Start && entry.proc_file_type < __FI_Root_End)
  788. callback({ entry.name, (int)strlen(entry.name), to_identifier(fsid(), PDI_Root, 0, (ProcFileType)entry.proc_file_type), 0 });
  789. }
  790. for (auto pid_child : Process::all_pids()) {
  791. char name[16];
  792. int name_length = ksprintf(name, "%u", pid_child);
  793. callback({ name, name_length, to_identifier(fsid(), PDI_Root, pid_child, FI_PID), 0 });
  794. }
  795. break;
  796. case FI_Root_sys:
  797. for (int i = 0; i < fs().m_sys_entries.size(); ++i) {
  798. auto& entry = fs().m_sys_entries[i];
  799. callback({ entry.name, (int)strlen(entry.name), sys_var_to_identifier(fsid(), i), 0 });
  800. }
  801. break;
  802. case FI_PID: {
  803. auto handle = ProcessInspectionHandle::from_pid(pid);
  804. if (!handle)
  805. return false;
  806. auto& process = handle->process();
  807. for (auto& entry : fs().m_entries) {
  808. if (entry.proc_file_type > __FI_PID_Start && entry.proc_file_type < __FI_PID_End) {
  809. if (entry.proc_file_type == FI_PID_exe && !process.executable())
  810. continue;
  811. // FIXME: strlen() here is sad.
  812. callback({ entry.name, (int)strlen(entry.name), to_identifier(fsid(), PDI_PID, pid, (ProcFileType)entry.proc_file_type), 0 });
  813. }
  814. }
  815. } break;
  816. case FI_PID_fd: {
  817. auto handle = ProcessInspectionHandle::from_pid(pid);
  818. if (!handle)
  819. return false;
  820. auto& process = handle->process();
  821. for (int i = 0; i < process.max_open_file_descriptors(); ++i) {
  822. auto* description = process.file_description(i);
  823. if (!description)
  824. continue;
  825. char name[16];
  826. int name_length = ksprintf(name, "%u", i);
  827. callback({ name, name_length, to_identifier_with_fd(fsid(), pid, i), 0 });
  828. }
  829. } break;
  830. default:
  831. return true;
  832. }
  833. return true;
  834. }
  835. InodeIdentifier ProcFSInode::lookup(StringView name)
  836. {
  837. ASSERT(is_directory());
  838. if (name == ".")
  839. return identifier();
  840. if (name == "..")
  841. return to_parent_id(identifier());
  842. auto proc_file_type = to_proc_file_type(identifier());
  843. if (proc_file_type == FI_Root) {
  844. for (auto& entry : fs().m_entries) {
  845. if (entry.name == nullptr)
  846. continue;
  847. if (entry.proc_file_type > __FI_Root_Start && entry.proc_file_type < __FI_Root_End) {
  848. if (name == entry.name) {
  849. return to_identifier(fsid(), PDI_Root, 0, (ProcFileType)entry.proc_file_type);
  850. }
  851. }
  852. }
  853. bool ok;
  854. unsigned name_as_number = name.to_uint(ok);
  855. if (ok) {
  856. bool process_exists = false;
  857. {
  858. InterruptDisabler disabler;
  859. process_exists = Process::from_pid(name_as_number);
  860. }
  861. if (process_exists)
  862. return to_identifier(fsid(), PDI_Root, name_as_number, FI_PID);
  863. }
  864. return {};
  865. }
  866. if (proc_file_type == FI_Root_sys) {
  867. for (int i = 0; i < fs().m_sys_entries.size(); ++i) {
  868. auto& entry = fs().m_sys_entries[i];
  869. if (name == entry.name)
  870. return sys_var_to_identifier(fsid(), i);
  871. }
  872. return {};
  873. }
  874. if (proc_file_type == FI_PID) {
  875. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier()));
  876. if (!handle)
  877. return {};
  878. auto& process = handle->process();
  879. for (auto& entry : fs().m_entries) {
  880. if (entry.proc_file_type > __FI_PID_Start && entry.proc_file_type < __FI_PID_End) {
  881. if (entry.proc_file_type == FI_PID_exe && !process.executable())
  882. continue;
  883. if (entry.name == nullptr)
  884. continue;
  885. if (name == entry.name) {
  886. return to_identifier(fsid(), PDI_PID, to_pid(identifier()), (ProcFileType)entry.proc_file_type);
  887. }
  888. }
  889. }
  890. return {};
  891. }
  892. if (proc_file_type == FI_PID_fd) {
  893. bool ok;
  894. unsigned name_as_number = name.to_uint(ok);
  895. if (ok) {
  896. bool fd_exists = false;
  897. {
  898. InterruptDisabler disabler;
  899. if (auto* process = Process::from_pid(to_pid(identifier())))
  900. fd_exists = process->file_description(name_as_number);
  901. }
  902. if (fd_exists)
  903. return to_identifier_with_fd(fsid(), to_pid(identifier()), name_as_number);
  904. }
  905. }
  906. return {};
  907. }
  908. void ProcFSInode::flush_metadata()
  909. {
  910. }
  911. ssize_t ProcFSInode::write_bytes(off_t offset, ssize_t size, const u8* buffer, FileDescription*)
  912. {
  913. auto* directory_entry = fs().get_directory_entry(identifier());
  914. if (!directory_entry || !directory_entry->write_callback)
  915. return -EPERM;
  916. ASSERT(is_persistent_inode(identifier()));
  917. // FIXME: Being able to write into ProcFS at a non-zero offset seems like something we should maybe support..
  918. ASSERT(offset == 0);
  919. bool success = directory_entry->write_callback(identifier(), ByteBuffer::wrap(buffer, size));
  920. ASSERT(success);
  921. return 0;
  922. }
  923. KResult ProcFSInode::add_child(InodeIdentifier child_id, const StringView& name, mode_t)
  924. {
  925. (void)child_id;
  926. (void)name;
  927. return KResult(-EPERM);
  928. }
  929. KResult ProcFSInode::remove_child(const StringView& name)
  930. {
  931. (void)name;
  932. return KResult(-EPERM);
  933. }
  934. ProcFSInodeCustomData::~ProcFSInodeCustomData()
  935. {
  936. }
  937. size_t ProcFSInode::directory_entry_count() const
  938. {
  939. ASSERT(is_directory());
  940. size_t count = 0;
  941. traverse_as_directory([&count](const FS::DirectoryEntry&) {
  942. ++count;
  943. return true;
  944. });
  945. return count;
  946. }
  947. KResult ProcFSInode::chmod(mode_t)
  948. {
  949. return KResult(-EPERM);
  950. }
  951. ProcFS::ProcFS()
  952. {
  953. s_the = this;
  954. m_root_inode = adopt(*new ProcFSInode(*this, 1));
  955. m_entries.resize(FI_MaxStaticFileIndex);
  956. m_entries[FI_Root_mm] = { "mm", FI_Root_mm, procfs$mm };
  957. m_entries[FI_Root_mounts] = { "mounts", FI_Root_mounts, procfs$mounts };
  958. m_entries[FI_Root_df] = { "df", FI_Root_df, procfs$df };
  959. m_entries[FI_Root_kmalloc] = { "kmalloc", FI_Root_kmalloc, procfs$kmalloc };
  960. m_entries[FI_Root_all] = { "all", FI_Root_all, procfs$all };
  961. m_entries[FI_Root_memstat] = { "memstat", FI_Root_memstat, procfs$memstat };
  962. m_entries[FI_Root_cpuinfo] = { "cpuinfo", FI_Root_cpuinfo, procfs$cpuinfo };
  963. m_entries[FI_Root_inodes] = { "inodes", FI_Root_inodes, procfs$inodes };
  964. m_entries[FI_Root_dmesg] = { "dmesg", FI_Root_dmesg, procfs$dmesg };
  965. m_entries[FI_Root_self] = { "self", FI_Root_self, procfs$self };
  966. m_entries[FI_Root_pci] = { "pci", FI_Root_pci, procfs$pci };
  967. m_entries[FI_Root_uptime] = { "uptime", FI_Root_uptime, procfs$uptime };
  968. m_entries[FI_Root_cmdline] = { "cmdline", FI_Root_cmdline, procfs$cmdline };
  969. m_entries[FI_Root_netadapters] = { "netadapters", FI_Root_netadapters, procfs$netadapters };
  970. m_entries[FI_Root_sys] = { "sys", FI_Root_sys };
  971. m_entries[FI_PID_vm] = { "vm", FI_PID_vm, procfs$pid_vm };
  972. m_entries[FI_PID_vmo] = { "vmo", FI_PID_vmo, procfs$pid_vmo };
  973. m_entries[FI_PID_stack] = { "stack", FI_PID_stack, procfs$pid_stack };
  974. m_entries[FI_PID_regs] = { "regs", FI_PID_regs, procfs$pid_regs };
  975. m_entries[FI_PID_fds] = { "fds", FI_PID_fds, procfs$pid_fds };
  976. m_entries[FI_PID_exe] = { "exe", FI_PID_exe, procfs$pid_exe };
  977. m_entries[FI_PID_cwd] = { "cwd", FI_PID_cwd, procfs$pid_cwd };
  978. m_entries[FI_PID_fd] = { "fd", FI_PID_fd };
  979. m_kmalloc_stack_helper.resource() = g_dump_kmalloc_stacks;
  980. add_sys_bool("kmalloc_stacks", m_kmalloc_stack_helper, [this] {
  981. g_dump_kmalloc_stacks = m_kmalloc_stack_helper.resource();
  982. });
  983. }
  984. ProcFS::ProcFSDirectoryEntry* ProcFS::get_directory_entry(InodeIdentifier identifier) const
  985. {
  986. if (to_proc_parent_directory(identifier) == PDI_Root_sys) {
  987. auto sys_index = to_sys_index(identifier);
  988. if (sys_index < m_sys_entries.size())
  989. return const_cast<ProcFSDirectoryEntry*>(&m_sys_entries[sys_index]);
  990. return nullptr;
  991. }
  992. auto proc_file_type = to_proc_file_type(identifier);
  993. if (proc_file_type != FI_Invalid && proc_file_type < FI_MaxStaticFileIndex)
  994. return const_cast<ProcFSDirectoryEntry*>(&m_entries[proc_file_type]);
  995. return nullptr;
  996. }
  997. KResult ProcFSInode::chown(uid_t, gid_t)
  998. {
  999. return KResult(-EPERM);
  1000. }