ProcFS.cpp 38 KB

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