ProcFS.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402
  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/JsonArraySerializer.h>
  8. #include <AK/JsonObject.h>
  9. #include <AK/JsonObjectSerializer.h>
  10. #include <AK/JsonValue.h>
  11. #include <Kernel/Arch/i386/CPU.h>
  12. #include <Kernel/FileSystem/Custody.h>
  13. #include <Kernel/FileSystem/DiskBackedFileSystem.h>
  14. #include <Kernel/FileSystem/FileDescription.h>
  15. #include <Kernel/FileSystem/VirtualFileSystem.h>
  16. #include <Kernel/Heap/kmalloc.h>
  17. #include <Kernel/KBufferBuilder.h>
  18. #include <Kernel/KParams.h>
  19. #include <Kernel/Module.h>
  20. #include <Kernel/Net/LocalSocket.h>
  21. #include <Kernel/Net/NetworkAdapter.h>
  22. #include <Kernel/Net/Routing.h>
  23. #include <Kernel/Net/TCPSocket.h>
  24. #include <Kernel/Net/UDPSocket.h>
  25. #include <Kernel/PCI.h>
  26. #include <Kernel/Profiling.h>
  27. #include <Kernel/VM/MemoryManager.h>
  28. #include <Kernel/VM/PurgeableVMObject.h>
  29. #include <LibC/errno_numbers.h>
  30. enum ProcParentDirectory {
  31. PDI_AbstractRoot = 0,
  32. PDI_Root,
  33. PDI_Root_sys,
  34. PDI_Root_net,
  35. PDI_PID,
  36. PDI_PID_fd,
  37. };
  38. enum ProcFileType {
  39. FI_Invalid = 0,
  40. FI_Root = 1, // directory
  41. __FI_Root_Start,
  42. FI_Root_mm,
  43. FI_Root_mounts,
  44. FI_Root_df,
  45. FI_Root_all,
  46. FI_Root_memstat,
  47. FI_Root_cpuinfo,
  48. FI_Root_inodes,
  49. FI_Root_dmesg,
  50. FI_Root_pci,
  51. FI_Root_devices,
  52. FI_Root_uptime,
  53. FI_Root_cmdline,
  54. FI_Root_modules,
  55. FI_Root_profile,
  56. FI_Root_self, // symlink
  57. FI_Root_sys, // directory
  58. FI_Root_net, // directory
  59. __FI_Root_End,
  60. FI_Root_sys_variable,
  61. FI_Root_net_adapters,
  62. FI_Root_net_arp,
  63. FI_Root_net_tcp,
  64. FI_Root_net_udp,
  65. FI_Root_net_local,
  66. FI_PID,
  67. __FI_PID_Start,
  68. FI_PID_vm,
  69. FI_PID_vmobjects,
  70. FI_PID_stack,
  71. FI_PID_regs,
  72. FI_PID_fds,
  73. FI_PID_exe, // symlink
  74. FI_PID_cwd, // symlink
  75. FI_PID_fd, // directory
  76. __FI_PID_End,
  77. FI_MaxStaticFileIndex,
  78. };
  79. static inline pid_t to_pid(const InodeIdentifier& identifier)
  80. {
  81. #ifdef PROCFS_DEBUG
  82. dbgprintf("to_pid, index=%08x -> %u\n", identifier.index(), identifier.index() >> 16);
  83. #endif
  84. return identifier.index() >> 16u;
  85. }
  86. static inline ProcParentDirectory to_proc_parent_directory(const InodeIdentifier& identifier)
  87. {
  88. return (ProcParentDirectory)((identifier.index() >> 12) & 0xf);
  89. }
  90. static inline ProcFileType to_proc_file_type(const InodeIdentifier& identifier)
  91. {
  92. return (ProcFileType)(identifier.index() & 0xff);
  93. }
  94. static inline int to_fd(const InodeIdentifier& identifier)
  95. {
  96. ASSERT(to_proc_parent_directory(identifier) == PDI_PID_fd);
  97. return (identifier.index() & 0xff) - FI_MaxStaticFileIndex;
  98. }
  99. static inline int to_sys_index(const InodeIdentifier& identifier)
  100. {
  101. ASSERT(to_proc_parent_directory(identifier) == PDI_Root_sys);
  102. ASSERT(to_proc_file_type(identifier) == FI_Root_sys_variable);
  103. return identifier.index() >> 16u;
  104. }
  105. static inline InodeIdentifier to_identifier(unsigned fsid, ProcParentDirectory parent, pid_t pid, ProcFileType proc_file_type)
  106. {
  107. return { fsid, ((unsigned)parent << 12u) | ((unsigned)pid << 16u) | (unsigned)proc_file_type };
  108. }
  109. static inline InodeIdentifier to_identifier_with_fd(unsigned fsid, pid_t pid, int fd)
  110. {
  111. return { fsid, (PDI_PID_fd << 12u) | ((unsigned)pid << 16u) | (FI_MaxStaticFileIndex + fd) };
  112. }
  113. static inline InodeIdentifier sys_var_to_identifier(unsigned fsid, unsigned index)
  114. {
  115. ASSERT(index < 256);
  116. return { fsid, (PDI_Root_sys << 12u) | (index << 16u) | FI_Root_sys_variable };
  117. }
  118. static inline InodeIdentifier to_parent_id(const InodeIdentifier& identifier)
  119. {
  120. switch (to_proc_parent_directory(identifier)) {
  121. case PDI_AbstractRoot:
  122. case PDI_Root:
  123. return { identifier.fsid(), FI_Root };
  124. case PDI_Root_sys:
  125. return { identifier.fsid(), FI_Root_sys };
  126. case PDI_Root_net:
  127. return { identifier.fsid(), FI_Root_net };
  128. case PDI_PID:
  129. return to_identifier(identifier.fsid(), PDI_Root, to_pid(identifier), FI_PID);
  130. case PDI_PID_fd:
  131. return to_identifier(identifier.fsid(), PDI_PID, to_pid(identifier), FI_PID_fd);
  132. }
  133. ASSERT_NOT_REACHED();
  134. }
  135. #if 0
  136. static inline u8 to_unused_metadata(const InodeIdentifier& identifier)
  137. {
  138. return (identifier.index() >> 8) & 0xf;
  139. }
  140. #endif
  141. static inline bool is_process_related_file(const InodeIdentifier& identifier)
  142. {
  143. if (to_proc_file_type(identifier) == FI_PID)
  144. return true;
  145. auto proc_parent_directory = to_proc_parent_directory(identifier);
  146. switch (proc_parent_directory) {
  147. case PDI_PID:
  148. case PDI_PID_fd:
  149. return true;
  150. default:
  151. return false;
  152. }
  153. }
  154. static inline bool is_directory(const InodeIdentifier& identifier)
  155. {
  156. auto proc_file_type = to_proc_file_type(identifier);
  157. switch (proc_file_type) {
  158. case FI_Root:
  159. case FI_Root_sys:
  160. case FI_Root_net:
  161. case FI_PID:
  162. case FI_PID_fd:
  163. return true;
  164. default:
  165. return false;
  166. }
  167. }
  168. static inline bool is_persistent_inode(const InodeIdentifier& identifier)
  169. {
  170. return to_proc_parent_directory(identifier) == PDI_Root_sys;
  171. }
  172. NonnullRefPtr<ProcFS> ProcFS::create()
  173. {
  174. return adopt(*new ProcFS);
  175. }
  176. ProcFS::~ProcFS()
  177. {
  178. }
  179. Optional<KBuffer> procfs$pid_fds(InodeIdentifier identifier)
  180. {
  181. KBufferBuilder builder;
  182. JsonArraySerializer array { builder };
  183. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  184. if (!handle) {
  185. array.finish();
  186. return builder.build();
  187. }
  188. auto& process = handle->process();
  189. if (process.number_of_open_file_descriptors() == 0) {
  190. array.finish();
  191. return builder.build();
  192. }
  193. for (int i = 0; i < process.max_open_file_descriptors(); ++i) {
  194. auto* description = process.file_description(i);
  195. if (!description)
  196. continue;
  197. bool cloexec = process.fd_flags(i) & FD_CLOEXEC;
  198. auto description_object = array.add_object();
  199. description_object.add("fd", i);
  200. description_object.add("absolute_path", description->absolute_path());
  201. description_object.add("seekable", description->file().is_seekable());
  202. description_object.add("class", description->file().class_name());
  203. description_object.add("offset", description->offset());
  204. description_object.add("cloexec", cloexec);
  205. description_object.add("blocking", description->is_blocking());
  206. description_object.add("can_read", description->can_read());
  207. description_object.add("can_write", description->can_write());
  208. }
  209. array.finish();
  210. return builder.build();
  211. }
  212. Optional<KBuffer> procfs$pid_fd_entry(InodeIdentifier identifier)
  213. {
  214. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  215. if (!handle)
  216. return {};
  217. auto& process = handle->process();
  218. int fd = to_fd(identifier);
  219. auto* description = process.file_description(fd);
  220. if (!description)
  221. return {};
  222. return description->absolute_path().to_byte_buffer();
  223. }
  224. Optional<KBuffer> procfs$pid_vm(InodeIdentifier identifier)
  225. {
  226. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  227. if (!handle)
  228. return {};
  229. auto& process = handle->process();
  230. KBufferBuilder builder;
  231. JsonArraySerializer array { builder };
  232. for (auto& region : process.regions()) {
  233. auto region_object = array.add_object();
  234. region_object.add("readable", region.is_readable());
  235. region_object.add("writable", region.is_writable());
  236. region_object.add("executable", region.is_executable());
  237. region_object.add("stack", region.is_stack());
  238. region_object.add("shared", region.is_shared());
  239. region_object.add("user_accessible", region.is_user_accessible());
  240. region_object.add("purgeable", region.vmobject().is_purgeable());
  241. if (region.vmobject().is_purgeable()) {
  242. region_object.add("volatile", static_cast<const PurgeableVMObject&>(region.vmobject()).is_volatile());
  243. }
  244. region_object.add("purgeable", region.vmobject().is_purgeable());
  245. region_object.add("address", region.vaddr().get());
  246. region_object.add("size", (u32)region.size());
  247. region_object.add("amount_resident", (u32)region.amount_resident());
  248. region_object.add("amount_dirty", (u32)region.amount_dirty());
  249. region_object.add("cow_pages", region.cow_pages());
  250. region_object.add("name", region.name());
  251. }
  252. array.finish();
  253. return builder.build();
  254. }
  255. Optional<KBuffer> procfs$pci(InodeIdentifier)
  256. {
  257. KBufferBuilder builder;
  258. JsonArraySerializer array { builder };
  259. PCI::enumerate_all([&array](PCI::Address address, PCI::ID id) {
  260. auto obj = array.add_object();
  261. obj.add("bus", address.bus());
  262. obj.add("slot", address.slot());
  263. obj.add("function", address.function());
  264. obj.add("vendor_id", id.vendor_id);
  265. obj.add("device_id", id.device_id);
  266. obj.add("revision_id", PCI::get_revision_id(address));
  267. obj.add("subclass", PCI::get_subclass(address));
  268. obj.add("class", PCI::get_class(address));
  269. obj.add("subsystem_id", PCI::get_subsystem_id(address));
  270. obj.add("subsystem_vendor_id", PCI::get_subsystem_vendor_id(address));
  271. });
  272. array.finish();
  273. return builder.build();
  274. }
  275. Optional<KBuffer> procfs$devices(InodeIdentifier)
  276. {
  277. KBufferBuilder builder;
  278. JsonArraySerializer array { builder };
  279. Device::for_each([&array](auto& device) {
  280. auto obj = array.add_object();
  281. obj.add("major", device.major());
  282. obj.add("minor", device.minor());
  283. obj.add("class_name", device.class_name());
  284. if (device.is_block_device())
  285. obj.add("type", "block");
  286. else if (device.is_character_device())
  287. obj.add("type", "character");
  288. else
  289. ASSERT_NOT_REACHED();
  290. });
  291. array.finish();
  292. return builder.build();
  293. }
  294. Optional<KBuffer> procfs$uptime(InodeIdentifier)
  295. {
  296. KBufferBuilder builder;
  297. builder.appendf("%u\n", (u32)(g_uptime / 1000));
  298. return builder.build();
  299. }
  300. Optional<KBuffer> procfs$cmdline(InodeIdentifier)
  301. {
  302. KBufferBuilder builder;
  303. builder.appendf("%s\n", KParams::the().cmdline().characters());
  304. return builder.build();
  305. }
  306. Optional<KBuffer> procfs$modules(InodeIdentifier)
  307. {
  308. extern HashMap<String, OwnPtr<Module>>* g_modules;
  309. KBufferBuilder builder;
  310. JsonArraySerializer array { builder };
  311. for (auto& it : *g_modules) {
  312. auto obj = array.add_object();
  313. obj.add("name", it.value->name);
  314. obj.add("module_init", (u32)it.value->module_init);
  315. obj.add("module_fini", (u32)it.value->module_fini);
  316. u32 size = 0;
  317. for (auto& section : it.value->sections) {
  318. size += section.capacity();
  319. }
  320. obj.add("size", size);
  321. }
  322. array.finish();
  323. return builder.build();
  324. }
  325. Optional<KBuffer> procfs$profile(InodeIdentifier)
  326. {
  327. InterruptDisabler disabler;
  328. KBufferBuilder builder;
  329. JsonArraySerializer array(builder);
  330. Profiling::for_each_sample([&](auto& sample) {
  331. auto object = array.add_object();
  332. object.add("pid", sample.pid);
  333. object.add("tid", sample.tid);
  334. object.add("timestamp", sample.timestamp);
  335. auto frames_array = object.add_array("frames");
  336. for (size_t i = 0; i < Profiling::max_stack_frame_count; ++i) {
  337. if (sample.frames[i] == 0)
  338. break;
  339. auto frame_object = frames_array.add_object();
  340. frame_object.add("address", JsonValue((u32)sample.frames[i]));
  341. frame_object.add("symbol", sample.symbolicated_frames[i]);
  342. frame_object.add("offset", JsonValue((u32)sample.offsets[i]));
  343. frame_object.finish();
  344. }
  345. frames_array.finish();
  346. });
  347. array.finish();
  348. return builder.build();
  349. }
  350. Optional<KBuffer> procfs$net_adapters(InodeIdentifier)
  351. {
  352. KBufferBuilder builder;
  353. JsonArraySerializer array { builder };
  354. NetworkAdapter::for_each([&array](auto& adapter) {
  355. auto obj = array.add_object();
  356. obj.add("name", adapter.name());
  357. obj.add("class_name", adapter.class_name());
  358. obj.add("mac_address", adapter.mac_address().to_string());
  359. if (!adapter.ipv4_address().is_zero()) {
  360. obj.add("ipv4_address", adapter.ipv4_address().to_string());
  361. obj.add("ipv4_netmask", adapter.ipv4_netmask().to_string());
  362. }
  363. if (!adapter.ipv4_gateway().is_zero())
  364. obj.add("ipv4_gateway", adapter.ipv4_gateway().to_string());
  365. obj.add("packets_in", adapter.packets_in());
  366. obj.add("bytes_in", adapter.bytes_in());
  367. obj.add("packets_out", adapter.packets_out());
  368. obj.add("bytes_out", adapter.bytes_out());
  369. obj.add("link_up", adapter.link_up());
  370. obj.add("mtu", adapter.mtu());
  371. });
  372. array.finish();
  373. return builder.build();
  374. }
  375. Optional<KBuffer> procfs$net_arp(InodeIdentifier)
  376. {
  377. KBufferBuilder builder;
  378. JsonArraySerializer array { builder };
  379. LOCKER(arp_table().lock());
  380. for (auto& it : arp_table().resource()) {
  381. auto obj = array.add_object();
  382. obj.add("mac_address", it.value.to_string());
  383. obj.add("ip_address", it.key.to_string());
  384. }
  385. array.finish();
  386. return builder.build();
  387. }
  388. Optional<KBuffer> procfs$net_tcp(InodeIdentifier)
  389. {
  390. KBufferBuilder builder;
  391. JsonArraySerializer array { builder };
  392. TCPSocket::for_each([&array](auto& socket) {
  393. auto obj = array.add_object();
  394. obj.add("local_address", socket.local_address().to_string());
  395. obj.add("local_port", socket.local_port());
  396. obj.add("peer_address", socket.peer_address().to_string());
  397. obj.add("peer_port", socket.peer_port());
  398. obj.add("state", TCPSocket::to_string(socket.state()));
  399. obj.add("ack_number", socket.ack_number());
  400. obj.add("sequence_number", socket.sequence_number());
  401. obj.add("packets_in", socket.packets_in());
  402. obj.add("bytes_in", socket.bytes_in());
  403. obj.add("packets_out", socket.packets_out());
  404. obj.add("bytes_out", socket.bytes_out());
  405. });
  406. array.finish();
  407. return builder.build();
  408. }
  409. Optional<KBuffer> procfs$net_udp(InodeIdentifier)
  410. {
  411. KBufferBuilder builder;
  412. JsonArraySerializer array { builder };
  413. UDPSocket::for_each([&array](auto& socket) {
  414. auto obj = array.add_object();
  415. obj.add("local_address", socket.local_address().to_string());
  416. obj.add("local_port", socket.local_port());
  417. obj.add("peer_address", socket.peer_address().to_string());
  418. obj.add("peer_port", socket.peer_port());
  419. });
  420. array.finish();
  421. return builder.build();
  422. }
  423. Optional<KBuffer> procfs$net_local(InodeIdentifier)
  424. {
  425. KBufferBuilder builder;
  426. JsonArraySerializer array { builder };
  427. LocalSocket::for_each([&array](auto& socket) {
  428. auto obj = array.add_object();
  429. obj.add("path", String(socket.socket_path()));
  430. obj.add("origin_pid", socket.origin_pid());
  431. obj.add("origin_uid", socket.origin_uid());
  432. obj.add("origin_gid", socket.origin_gid());
  433. obj.add("acceptor_pid", socket.acceptor_pid());
  434. obj.add("acceptor_uid", socket.acceptor_uid());
  435. obj.add("acceptor_gid", socket.acceptor_gid());
  436. });
  437. array.finish();
  438. return builder.build();
  439. }
  440. Optional<KBuffer> procfs$pid_vmobjects(InodeIdentifier identifier)
  441. {
  442. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  443. if (!handle)
  444. return {};
  445. auto& process = handle->process();
  446. KBufferBuilder builder;
  447. builder.appendf("BEGIN END SIZE NAME\n");
  448. for (auto& region : process.regions()) {
  449. builder.appendf("%x -- %x %x %s\n",
  450. region.vaddr().get(),
  451. region.vaddr().offset(region.size() - 1).get(),
  452. region.size(),
  453. region.name().characters());
  454. builder.appendf("VMO: %s @ %x(%u)\n",
  455. region.vmobject().is_anonymous() ? "anonymous" : "file-backed",
  456. &region.vmobject(),
  457. region.vmobject().ref_count());
  458. for (size_t i = 0; i < region.vmobject().page_count(); ++i) {
  459. auto& physical_page = region.vmobject().physical_pages()[i];
  460. builder.appendf("P%x%s(%u) ",
  461. physical_page ? physical_page->paddr().get() : 0,
  462. region.should_cow(i) ? "!" : "",
  463. physical_page ? physical_page->ref_count() : 0);
  464. }
  465. builder.appendf("\n");
  466. }
  467. return builder.build();
  468. }
  469. Optional<KBuffer> procfs$pid_stack(InodeIdentifier identifier)
  470. {
  471. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  472. if (!handle)
  473. return {};
  474. auto& process = handle->process();
  475. return process.backtrace(*handle);
  476. }
  477. Optional<KBuffer> procfs$pid_regs(InodeIdentifier identifier)
  478. {
  479. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  480. if (!handle)
  481. return {};
  482. auto& process = handle->process();
  483. KBufferBuilder builder;
  484. process.for_each_thread([&](Thread& thread) {
  485. builder.appendf("Thread %d:\n", thread.tid());
  486. auto& tss = thread.tss();
  487. builder.appendf("eax: %x\n", tss.eax);
  488. builder.appendf("ebx: %x\n", tss.ebx);
  489. builder.appendf("ecx: %x\n", tss.ecx);
  490. builder.appendf("edx: %x\n", tss.edx);
  491. builder.appendf("esi: %x\n", tss.esi);
  492. builder.appendf("edi: %x\n", tss.edi);
  493. builder.appendf("ebp: %x\n", tss.ebp);
  494. builder.appendf("cr3: %x\n", tss.cr3);
  495. builder.appendf("flg: %x\n", tss.eflags);
  496. builder.appendf("sp: %w:%x\n", tss.ss, tss.esp);
  497. builder.appendf("pc: %w:%x\n", tss.cs, tss.eip);
  498. return IterationDecision::Continue;
  499. });
  500. return builder.build();
  501. }
  502. Optional<KBuffer> procfs$pid_exe(InodeIdentifier identifier)
  503. {
  504. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  505. if (!handle)
  506. return {};
  507. auto& process = handle->process();
  508. auto* custody = process.executable();
  509. ASSERT(custody);
  510. return custody->absolute_path().to_byte_buffer();
  511. }
  512. Optional<KBuffer> procfs$pid_cwd(InodeIdentifier identifier)
  513. {
  514. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  515. if (!handle)
  516. return {};
  517. return handle->process().current_directory().absolute_path().to_byte_buffer();
  518. }
  519. Optional<KBuffer> procfs$self(InodeIdentifier)
  520. {
  521. char buffer[16];
  522. sprintf(buffer, "%u", current->pid());
  523. return KBuffer::copy((const u8*)buffer, strlen(buffer));
  524. }
  525. Optional<KBuffer> procfs$mm(InodeIdentifier)
  526. {
  527. InterruptDisabler disabler;
  528. KBufferBuilder builder;
  529. u32 vmobject_count = 0;
  530. MemoryManager::for_each_vmobject([&](auto& vmobject) {
  531. ++vmobject_count;
  532. builder.appendf("VMObject: %p %s(%u): p:%4u\n",
  533. &vmobject,
  534. vmobject.is_anonymous() ? "anon" : "file",
  535. vmobject.ref_count(),
  536. vmobject.page_count());
  537. return IterationDecision::Continue;
  538. });
  539. builder.appendf("VMO count: %u\n", vmobject_count);
  540. builder.appendf("Free physical pages: %u\n", MM.user_physical_pages() - MM.user_physical_pages_used());
  541. builder.appendf("Free supervisor physical pages: %u\n", MM.super_physical_pages() - MM.super_physical_pages_used());
  542. return builder.build();
  543. }
  544. Optional<KBuffer> procfs$dmesg(InodeIdentifier)
  545. {
  546. InterruptDisabler disabler;
  547. KBufferBuilder builder;
  548. for (char ch : Console::the().logbuffer())
  549. builder.append(ch);
  550. return builder.build();
  551. }
  552. Optional<KBuffer> procfs$mounts(InodeIdentifier)
  553. {
  554. // FIXME: This is obviously racy against the VFS mounts changing.
  555. KBufferBuilder builder;
  556. VFS::the().for_each_mount([&builder](auto& mount) {
  557. auto& fs = mount.guest_fs();
  558. builder.appendf("%s @ ", fs.class_name());
  559. if (!mount.host().is_valid())
  560. builder.appendf("/");
  561. else {
  562. builder.appendf("%u:%u", mount.host().fsid(), mount.host().index());
  563. builder.append(' ');
  564. builder.append(mount.absolute_path());
  565. }
  566. builder.append('\n');
  567. });
  568. return builder.build();
  569. }
  570. Optional<KBuffer> procfs$df(InodeIdentifier)
  571. {
  572. // FIXME: This is obviously racy against the VFS mounts changing.
  573. KBufferBuilder builder;
  574. JsonArraySerializer array { builder };
  575. VFS::the().for_each_mount([&array](auto& mount) {
  576. auto& fs = mount.guest_fs();
  577. auto fs_object = array.add_object();
  578. fs_object.add("class_name", fs.class_name());
  579. fs_object.add("total_block_count", fs.total_block_count());
  580. fs_object.add("free_block_count", fs.free_block_count());
  581. fs_object.add("total_inode_count", fs.total_inode_count());
  582. fs_object.add("free_inode_count", fs.free_inode_count());
  583. fs_object.add("mount_point", mount.absolute_path());
  584. fs_object.add("block_size", fs.block_size());
  585. fs_object.add("readonly", fs.is_readonly());
  586. if (fs.is_disk_backed())
  587. fs_object.add("device", static_cast<const DiskBackedFS&>(fs).device().absolute_path());
  588. else
  589. fs_object.add("device", fs.class_name());
  590. });
  591. array.finish();
  592. return builder.build();
  593. }
  594. Optional<KBuffer> procfs$cpuinfo(InodeIdentifier)
  595. {
  596. KBufferBuilder builder;
  597. {
  598. CPUID cpuid(0);
  599. builder.appendf("cpuid: ");
  600. auto emit_u32 = [&](u32 value) {
  601. builder.appendf("%c%c%c%c",
  602. value & 0xff,
  603. (value >> 8) & 0xff,
  604. (value >> 16) & 0xff,
  605. (value >> 24) & 0xff);
  606. };
  607. emit_u32(cpuid.ebx());
  608. emit_u32(cpuid.edx());
  609. emit_u32(cpuid.ecx());
  610. builder.appendf("\n");
  611. }
  612. {
  613. CPUID cpuid(1);
  614. u32 stepping = cpuid.eax() & 0xf;
  615. u32 model = (cpuid.eax() >> 4) & 0xf;
  616. u32 family = (cpuid.eax() >> 8) & 0xf;
  617. u32 type = (cpuid.eax() >> 12) & 0x3;
  618. u32 extended_model = (cpuid.eax() >> 16) & 0xf;
  619. u32 extended_family = (cpuid.eax() >> 20) & 0xff;
  620. u32 display_model;
  621. u32 display_family;
  622. if (family == 15) {
  623. display_family = family + extended_family;
  624. display_model = model + (extended_model << 4);
  625. } else if (family == 6) {
  626. display_family = family;
  627. display_model = model + (extended_model << 4);
  628. } else {
  629. display_family = family;
  630. display_model = model;
  631. }
  632. builder.appendf("family: %u\n", display_family);
  633. builder.appendf("model: %u\n", display_model);
  634. builder.appendf("stepping: %u\n", stepping);
  635. builder.appendf("type: %u\n", type);
  636. }
  637. {
  638. // FIXME: Check first that this is supported by calling CPUID with eax=0x80000000
  639. // and verifying that the returned eax>=0x80000004.
  640. alignas(u32) char buffer[48];
  641. u32* bufptr = reinterpret_cast<u32*>(buffer);
  642. auto copy_brand_string_part_to_buffer = [&](u32 i) {
  643. CPUID cpuid(0x80000002 + i);
  644. *bufptr++ = cpuid.eax();
  645. *bufptr++ = cpuid.ebx();
  646. *bufptr++ = cpuid.ecx();
  647. *bufptr++ = cpuid.edx();
  648. };
  649. copy_brand_string_part_to_buffer(0);
  650. copy_brand_string_part_to_buffer(1);
  651. copy_brand_string_part_to_buffer(2);
  652. builder.appendf("brandstr: \"%s\"\n", buffer);
  653. }
  654. return builder.build();
  655. }
  656. Optional<KBuffer> procfs$memstat(InodeIdentifier)
  657. {
  658. InterruptDisabler disabler;
  659. KBufferBuilder builder;
  660. JsonObjectSerializer<KBufferBuilder> json { builder };
  661. json.add("kmalloc_allocated", (u32)sum_alloc);
  662. json.add("kmalloc_available", (u32)sum_free);
  663. json.add("kmalloc_eternal_allocated", (u32)kmalloc_sum_eternal);
  664. json.add("user_physical_allocated", MM.user_physical_pages_used());
  665. json.add("user_physical_available", MM.user_physical_pages() - MM.user_physical_pages_used());
  666. json.add("super_physical_allocated", MM.super_physical_pages_used());
  667. json.add("super_physical_available", MM.super_physical_pages() - MM.super_physical_pages_used());
  668. json.add("kmalloc_call_count", g_kmalloc_call_count);
  669. json.add("kfree_call_count", g_kfree_call_count);
  670. slab_alloc_stats([&json](size_t slab_size, size_t num_allocated, size_t num_free) {
  671. auto prefix = String::format("slab_%zu", slab_size);
  672. json.add(String::format("%s_num_allocated", prefix.characters()), (u32)num_allocated);
  673. json.add(String::format("%s_num_free", prefix.characters()), (u32)num_free);
  674. });
  675. json.finish();
  676. return builder.build();
  677. }
  678. Optional<KBuffer> procfs$all(InodeIdentifier)
  679. {
  680. InterruptDisabler disabler;
  681. auto processes = Process::all_processes();
  682. KBufferBuilder builder;
  683. JsonArraySerializer array { builder };
  684. // Keep this in sync with CProcessStatistics.
  685. auto build_process = [&](const Process& process) {
  686. auto process_object = array.add_object();
  687. process_object.add("pid", process.pid());
  688. process_object.add("pgid", process.tty() ? process.tty()->pgid() : 0);
  689. process_object.add("pgp", process.pgid());
  690. process_object.add("sid", process.sid());
  691. process_object.add("uid", process.uid());
  692. process_object.add("gid", process.gid());
  693. process_object.add("ppid", process.ppid());
  694. process_object.add("nfds", process.number_of_open_file_descriptors());
  695. process_object.add("name", process.name());
  696. process_object.add("tty", process.tty() ? process.tty()->tty_name() : "notty");
  697. process_object.add("amount_virtual", (u32)process.amount_virtual());
  698. process_object.add("amount_resident", (u32)process.amount_resident());
  699. process_object.add("amount_dirty_private", (u32)process.amount_dirty_private());
  700. process_object.add("amount_clean_inode", (u32)process.amount_clean_inode());
  701. process_object.add("amount_shared", (u32)process.amount_shared());
  702. process_object.add("amount_purgeable_volatile", (u32)process.amount_purgeable_volatile());
  703. process_object.add("amount_purgeable_nonvolatile", (u32)process.amount_purgeable_nonvolatile());
  704. process_object.add("icon_id", process.icon_id());
  705. auto thread_array = process_object.add_array("threads");
  706. process.for_each_thread([&](const Thread& thread) {
  707. auto thread_object = thread_array.add_object();
  708. thread_object.add("tid", thread.tid());
  709. thread_object.add("name", thread.name());
  710. thread_object.add("times_scheduled", thread.times_scheduled());
  711. thread_object.add("ticks", thread.ticks());
  712. thread_object.add("state", thread.state_string());
  713. thread_object.add("priority", thread.priority());
  714. thread_object.add("effective_priority", thread.effective_priority());
  715. thread_object.add("syscall_count", thread.syscall_count());
  716. thread_object.add("inode_faults", thread.inode_faults());
  717. thread_object.add("zero_faults", thread.zero_faults());
  718. thread_object.add("cow_faults", thread.cow_faults());
  719. thread_object.add("file_read_bytes", thread.file_read_bytes());
  720. thread_object.add("file_write_bytes", thread.file_write_bytes());
  721. thread_object.add("unix_socket_read_bytes", thread.unix_socket_read_bytes());
  722. thread_object.add("unix_socket_write_bytes", thread.unix_socket_write_bytes());
  723. thread_object.add("ipv4_socket_read_bytes", thread.ipv4_socket_read_bytes());
  724. thread_object.add("ipv4_socket_write_bytes", thread.ipv4_socket_write_bytes());
  725. return IterationDecision::Continue;
  726. });
  727. };
  728. build_process(*Scheduler::colonel());
  729. for (auto* process : processes)
  730. build_process(*process);
  731. array.finish();
  732. return builder.build();
  733. }
  734. Optional<KBuffer> procfs$inodes(InodeIdentifier)
  735. {
  736. extern InlineLinkedList<Inode>& all_inodes();
  737. KBufferBuilder builder;
  738. InterruptDisabler disabler;
  739. for (auto& inode : all_inodes()) {
  740. builder.appendf("Inode{K%x} %02u:%08u (%u)\n", &inode, inode.fsid(), inode.index(), inode.ref_count());
  741. }
  742. return builder.build();
  743. }
  744. struct SysVariable {
  745. String name;
  746. enum class Type : u8 {
  747. Invalid,
  748. Boolean,
  749. String,
  750. };
  751. Type type { Type::Invalid };
  752. Function<void()> notify_callback;
  753. void* address { nullptr };
  754. static SysVariable& for_inode(InodeIdentifier);
  755. void notify()
  756. {
  757. if (notify_callback)
  758. notify_callback();
  759. }
  760. };
  761. static Vector<SysVariable, 16>* s_sys_variables;
  762. static inline Vector<SysVariable, 16>& sys_variables()
  763. {
  764. if (s_sys_variables == nullptr) {
  765. s_sys_variables = new Vector<SysVariable, 16>;
  766. s_sys_variables->append({ "", SysVariable::Type::Invalid, nullptr, nullptr });
  767. }
  768. return *s_sys_variables;
  769. }
  770. SysVariable& SysVariable::for_inode(InodeIdentifier id)
  771. {
  772. auto index = to_sys_index(id);
  773. if (index >= sys_variables().size())
  774. return sys_variables()[0];
  775. auto& variable = sys_variables()[index];
  776. ASSERT(variable.address);
  777. return variable;
  778. }
  779. static ByteBuffer read_sys_bool(InodeIdentifier inode_id)
  780. {
  781. auto& variable = SysVariable::for_inode(inode_id);
  782. ASSERT(variable.type == SysVariable::Type::Boolean);
  783. auto buffer = ByteBuffer::create_uninitialized(2);
  784. auto* lockable_bool = reinterpret_cast<Lockable<bool>*>(variable.address);
  785. {
  786. LOCKER(lockable_bool->lock());
  787. buffer[0] = lockable_bool->resource() ? '1' : '0';
  788. }
  789. buffer[1] = '\n';
  790. return buffer;
  791. }
  792. static ssize_t write_sys_bool(InodeIdentifier inode_id, const ByteBuffer& data)
  793. {
  794. auto& variable = SysVariable::for_inode(inode_id);
  795. ASSERT(variable.type == SysVariable::Type::Boolean);
  796. if (data.is_empty() || !(data[0] == '0' || data[0] == '1'))
  797. return data.size();
  798. auto* lockable_bool = reinterpret_cast<Lockable<bool>*>(variable.address);
  799. {
  800. LOCKER(lockable_bool->lock());
  801. lockable_bool->resource() = data[0] == '1';
  802. }
  803. variable.notify();
  804. return data.size();
  805. }
  806. static ByteBuffer read_sys_string(InodeIdentifier inode_id)
  807. {
  808. auto& variable = SysVariable::for_inode(inode_id);
  809. ASSERT(variable.type == SysVariable::Type::String);
  810. auto* lockable_string = reinterpret_cast<Lockable<String>*>(variable.address);
  811. LOCKER(lockable_string->lock());
  812. return lockable_string->resource().to_byte_buffer();
  813. }
  814. static ssize_t write_sys_string(InodeIdentifier inode_id, const ByteBuffer& data)
  815. {
  816. auto& variable = SysVariable::for_inode(inode_id);
  817. ASSERT(variable.type == SysVariable::Type::String);
  818. {
  819. auto* lockable_string = reinterpret_cast<Lockable<String>*>(variable.address);
  820. LOCKER(lockable_string->lock());
  821. lockable_string->resource() = String((const char*)data.data(), data.size());
  822. }
  823. variable.notify();
  824. return data.size();
  825. }
  826. void ProcFS::add_sys_bool(String&& name, Lockable<bool>& var, Function<void()>&& notify_callback)
  827. {
  828. InterruptDisabler disabler;
  829. SysVariable variable;
  830. variable.name = move(name);
  831. variable.type = SysVariable::Type::Boolean;
  832. variable.notify_callback = move(notify_callback);
  833. variable.address = &var;
  834. sys_variables().append(move(variable));
  835. }
  836. void ProcFS::add_sys_string(String&& name, Lockable<String>& var, Function<void()>&& notify_callback)
  837. {
  838. InterruptDisabler disabler;
  839. SysVariable variable;
  840. variable.name = move(name);
  841. variable.type = SysVariable::Type::String;
  842. variable.notify_callback = move(notify_callback);
  843. variable.address = &var;
  844. sys_variables().append(move(variable));
  845. }
  846. bool ProcFS::initialize()
  847. {
  848. static Lockable<bool>* kmalloc_stack_helper;
  849. if (kmalloc_stack_helper == nullptr) {
  850. kmalloc_stack_helper = new Lockable<bool>();
  851. kmalloc_stack_helper->resource() = g_dump_kmalloc_stacks;
  852. ProcFS::add_sys_bool("kmalloc_stacks", *kmalloc_stack_helper, [] {
  853. g_dump_kmalloc_stacks = kmalloc_stack_helper->resource();
  854. });
  855. }
  856. return true;
  857. }
  858. const char* ProcFS::class_name() const
  859. {
  860. return "ProcFS";
  861. }
  862. RefPtr<Inode> ProcFS::create_inode(InodeIdentifier, const String&, mode_t, off_t, dev_t, int&)
  863. {
  864. kprintf("FIXME: Implement ProcFS::create_inode()?\n");
  865. return {};
  866. }
  867. RefPtr<Inode> ProcFS::create_directory(InodeIdentifier, const String&, mode_t, int& error)
  868. {
  869. error = -EROFS;
  870. return nullptr;
  871. }
  872. InodeIdentifier ProcFS::root_inode() const
  873. {
  874. return { fsid(), FI_Root };
  875. }
  876. RefPtr<Inode> ProcFS::get_inode(InodeIdentifier inode_id) const
  877. {
  878. #ifdef PROCFS_DEBUG
  879. dbgprintf("ProcFS::get_inode(%u)\n", inode_id.index());
  880. #endif
  881. if (inode_id == root_inode())
  882. return m_root_inode;
  883. LOCKER(m_inodes_lock);
  884. auto it = m_inodes.find(inode_id.index());
  885. if (it == m_inodes.end()) {
  886. auto inode = adopt(*new ProcFSInode(const_cast<ProcFS&>(*this), inode_id.index()));
  887. m_inodes.set(inode_id.index(), inode.ptr());
  888. return inode;
  889. }
  890. return (*it).value;
  891. }
  892. ProcFSInode::ProcFSInode(ProcFS& fs, unsigned index)
  893. : Inode(fs, index)
  894. {
  895. }
  896. ProcFSInode::~ProcFSInode()
  897. {
  898. LOCKER(fs().m_inodes_lock);
  899. fs().m_inodes.remove(index());
  900. }
  901. InodeMetadata ProcFSInode::metadata() const
  902. {
  903. #ifdef PROCFS_DEBUG
  904. dbgprintf("ProcFSInode::metadata(%u)\n", index());
  905. #endif
  906. InodeMetadata metadata;
  907. metadata.inode = identifier();
  908. metadata.ctime = mepoch;
  909. metadata.atime = mepoch;
  910. metadata.mtime = mepoch;
  911. auto proc_parent_directory = to_proc_parent_directory(identifier());
  912. auto pid = to_pid(identifier());
  913. auto proc_file_type = to_proc_file_type(identifier());
  914. #ifdef PROCFS_DEBUG
  915. dbgprintf(" -> pid: %d, fi: %u, pdi: %u\n", pid, proc_file_type, proc_parent_directory);
  916. #endif
  917. if (is_process_related_file(identifier())) {
  918. auto handle = ProcessInspectionHandle::from_pid(pid);
  919. metadata.uid = handle->process().sys$getuid();
  920. metadata.gid = handle->process().sys$getgid();
  921. }
  922. if (proc_parent_directory == PDI_PID_fd) {
  923. metadata.mode = 00120777;
  924. return metadata;
  925. }
  926. switch (proc_file_type) {
  927. case FI_Root_self:
  928. case FI_PID_cwd:
  929. case FI_PID_exe:
  930. metadata.mode = 0120777;
  931. break;
  932. case FI_Root:
  933. case FI_Root_sys:
  934. case FI_Root_net:
  935. case FI_PID:
  936. case FI_PID_fd:
  937. metadata.mode = 040777;
  938. break;
  939. default:
  940. metadata.mode = 0100644;
  941. break;
  942. }
  943. #ifdef PROCFS_DEBUG
  944. dbgprintf("Returning mode %o\n", metadata.mode);
  945. #endif
  946. return metadata;
  947. }
  948. ssize_t ProcFSInode::read_bytes(off_t offset, ssize_t count, u8* buffer, FileDescription* description) const
  949. {
  950. #ifdef PROCFS_DEBUG
  951. dbgprintf("ProcFS: read_bytes %u\n", index());
  952. #endif
  953. ASSERT(offset >= 0);
  954. ASSERT(buffer);
  955. auto* directory_entry = fs().get_directory_entry(identifier());
  956. Function<Optional<KBuffer>(InodeIdentifier)> callback_tmp;
  957. Function<Optional<KBuffer>(InodeIdentifier)>* read_callback { nullptr };
  958. if (directory_entry)
  959. read_callback = &directory_entry->read_callback;
  960. else
  961. switch (to_proc_parent_directory(identifier())) {
  962. case PDI_PID_fd:
  963. callback_tmp = procfs$pid_fd_entry;
  964. read_callback = &callback_tmp;
  965. break;
  966. case PDI_Root_sys:
  967. switch (SysVariable::for_inode(identifier()).type) {
  968. case SysVariable::Type::Invalid:
  969. ASSERT_NOT_REACHED();
  970. case SysVariable::Type::Boolean:
  971. callback_tmp = read_sys_bool;
  972. break;
  973. case SysVariable::Type::String:
  974. callback_tmp = read_sys_string;
  975. break;
  976. }
  977. read_callback = &callback_tmp;
  978. break;
  979. default:
  980. ASSERT_NOT_REACHED();
  981. }
  982. ASSERT(read_callback);
  983. Optional<KBuffer> generated_data;
  984. if (!description) {
  985. generated_data = (*read_callback)(identifier());
  986. } else {
  987. if (!description->generator_cache())
  988. description->generator_cache() = (*read_callback)(identifier());
  989. generated_data = description->generator_cache();
  990. }
  991. auto& data = generated_data;
  992. ssize_t nread = 0;
  993. if (data.has_value()) {
  994. nread = min(static_cast<off_t>(data.value().size() - offset), static_cast<off_t>(count));
  995. memcpy(buffer, data.value().data() + offset, nread);
  996. if (nread == 0 && description && description->generator_cache())
  997. description->generator_cache().clear();
  998. }
  999. return nread;
  1000. }
  1001. InodeIdentifier ProcFS::ProcFSDirectoryEntry::identifier(unsigned fsid) const
  1002. {
  1003. return to_identifier(fsid, PDI_Root, 0, (ProcFileType)proc_file_type);
  1004. }
  1005. bool ProcFSInode::traverse_as_directory(Function<bool(const FS::DirectoryEntry&)> callback) const
  1006. {
  1007. #ifdef PROCFS_DEBUG
  1008. dbgprintf("ProcFS: traverse_as_directory %u\n", index());
  1009. #endif
  1010. if (!::is_directory(identifier()))
  1011. return false;
  1012. auto pid = to_pid(identifier());
  1013. auto proc_file_type = to_proc_file_type(identifier());
  1014. auto parent_id = to_parent_id(identifier());
  1015. callback({ ".", 1, identifier(), 2 });
  1016. callback({ "..", 2, parent_id, 2 });
  1017. switch (proc_file_type) {
  1018. case FI_Root:
  1019. for (auto& entry : fs().m_entries) {
  1020. // FIXME: strlen() here is sad.
  1021. if (!entry.name)
  1022. continue;
  1023. if (entry.proc_file_type > __FI_Root_Start && entry.proc_file_type < __FI_Root_End)
  1024. callback({ entry.name, strlen(entry.name), to_identifier(fsid(), PDI_Root, 0, (ProcFileType)entry.proc_file_type), 0 });
  1025. }
  1026. for (auto pid_child : Process::all_pids()) {
  1027. char name[16];
  1028. size_t name_length = (size_t)sprintf(name, "%u", pid_child);
  1029. callback({ name, name_length, to_identifier(fsid(), PDI_Root, pid_child, FI_PID), 0 });
  1030. }
  1031. break;
  1032. case FI_Root_sys:
  1033. for (int i = 1; i < sys_variables().size(); ++i) {
  1034. auto& variable = sys_variables()[i];
  1035. callback({ variable.name.characters(), variable.name.length(), sys_var_to_identifier(fsid(), i), 0 });
  1036. }
  1037. break;
  1038. case FI_Root_net:
  1039. callback({ "adapters", 8, to_identifier(fsid(), PDI_Root_net, 0, FI_Root_net_adapters), 0 });
  1040. callback({ "arp", 3, to_identifier(fsid(), PDI_Root_net, 0, FI_Root_net_arp), 0 });
  1041. callback({ "tcp", 3, to_identifier(fsid(), PDI_Root_net, 0, FI_Root_net_tcp), 0 });
  1042. callback({ "udp", 3, to_identifier(fsid(), PDI_Root_net, 0, FI_Root_net_udp), 0 });
  1043. callback({ "local", 5, to_identifier(fsid(), PDI_Root_net, 0, FI_Root_net_local), 0 });
  1044. break;
  1045. case FI_PID: {
  1046. auto handle = ProcessInspectionHandle::from_pid(pid);
  1047. if (!handle)
  1048. return false;
  1049. auto& process = handle->process();
  1050. for (auto& entry : fs().m_entries) {
  1051. if (entry.proc_file_type > __FI_PID_Start && entry.proc_file_type < __FI_PID_End) {
  1052. if (entry.proc_file_type == FI_PID_exe && !process.executable())
  1053. continue;
  1054. // FIXME: strlen() here is sad.
  1055. callback({ entry.name, strlen(entry.name), to_identifier(fsid(), PDI_PID, pid, (ProcFileType)entry.proc_file_type), 0 });
  1056. }
  1057. }
  1058. } break;
  1059. case FI_PID_fd: {
  1060. auto handle = ProcessInspectionHandle::from_pid(pid);
  1061. if (!handle)
  1062. return false;
  1063. auto& process = handle->process();
  1064. for (int i = 0; i < process.max_open_file_descriptors(); ++i) {
  1065. auto* description = process.file_description(i);
  1066. if (!description)
  1067. continue;
  1068. char name[16];
  1069. size_t name_length = (size_t)sprintf(name, "%u", i);
  1070. callback({ name, name_length, to_identifier_with_fd(fsid(), pid, i), 0 });
  1071. }
  1072. } break;
  1073. default:
  1074. return true;
  1075. }
  1076. return true;
  1077. }
  1078. InodeIdentifier ProcFSInode::lookup(StringView name)
  1079. {
  1080. ASSERT(is_directory());
  1081. if (name == ".")
  1082. return identifier();
  1083. if (name == "..")
  1084. return to_parent_id(identifier());
  1085. auto proc_file_type = to_proc_file_type(identifier());
  1086. if (proc_file_type == FI_Root) {
  1087. for (auto& entry : fs().m_entries) {
  1088. if (entry.name == nullptr)
  1089. continue;
  1090. if (entry.proc_file_type > __FI_Root_Start && entry.proc_file_type < __FI_Root_End) {
  1091. if (name == entry.name) {
  1092. return to_identifier(fsid(), PDI_Root, 0, (ProcFileType)entry.proc_file_type);
  1093. }
  1094. }
  1095. }
  1096. bool ok;
  1097. unsigned name_as_number = name.to_uint(ok);
  1098. if (ok) {
  1099. bool process_exists = false;
  1100. {
  1101. InterruptDisabler disabler;
  1102. process_exists = Process::from_pid(name_as_number);
  1103. }
  1104. if (process_exists)
  1105. return to_identifier(fsid(), PDI_Root, name_as_number, FI_PID);
  1106. }
  1107. return {};
  1108. }
  1109. if (proc_file_type == FI_Root_sys) {
  1110. for (int i = 1; i < sys_variables().size(); ++i) {
  1111. auto& variable = sys_variables()[i];
  1112. if (name == variable.name)
  1113. return sys_var_to_identifier(fsid(), i);
  1114. }
  1115. return {};
  1116. }
  1117. if (proc_file_type == FI_Root_net) {
  1118. if (name == "adapters")
  1119. return to_identifier(fsid(), PDI_Root, 0, FI_Root_net_adapters);
  1120. if (name == "arp")
  1121. return to_identifier(fsid(), PDI_Root, 0, FI_Root_net_arp);
  1122. if (name == "tcp")
  1123. return to_identifier(fsid(), PDI_Root, 0, FI_Root_net_tcp);
  1124. if (name == "udp")
  1125. return to_identifier(fsid(), PDI_Root, 0, FI_Root_net_udp);
  1126. if (name == "local")
  1127. return to_identifier(fsid(), PDI_Root, 0, FI_Root_net_local);
  1128. return {};
  1129. }
  1130. if (proc_file_type == FI_PID) {
  1131. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier()));
  1132. if (!handle)
  1133. return {};
  1134. auto& process = handle->process();
  1135. for (auto& entry : fs().m_entries) {
  1136. if (entry.proc_file_type > __FI_PID_Start && entry.proc_file_type < __FI_PID_End) {
  1137. if (entry.proc_file_type == FI_PID_exe && !process.executable())
  1138. continue;
  1139. if (entry.name == nullptr)
  1140. continue;
  1141. if (name == entry.name) {
  1142. return to_identifier(fsid(), PDI_PID, to_pid(identifier()), (ProcFileType)entry.proc_file_type);
  1143. }
  1144. }
  1145. }
  1146. return {};
  1147. }
  1148. if (proc_file_type == FI_PID_fd) {
  1149. bool ok;
  1150. unsigned name_as_number = name.to_uint(ok);
  1151. if (ok) {
  1152. bool fd_exists = false;
  1153. {
  1154. InterruptDisabler disabler;
  1155. if (auto* process = Process::from_pid(to_pid(identifier())))
  1156. fd_exists = process->file_description(name_as_number);
  1157. }
  1158. if (fd_exists)
  1159. return to_identifier_with_fd(fsid(), to_pid(identifier()), name_as_number);
  1160. }
  1161. }
  1162. return {};
  1163. }
  1164. void ProcFSInode::flush_metadata()
  1165. {
  1166. }
  1167. ssize_t ProcFSInode::write_bytes(off_t offset, ssize_t size, const u8* buffer, FileDescription*)
  1168. {
  1169. auto* directory_entry = fs().get_directory_entry(identifier());
  1170. Function<ssize_t(InodeIdentifier, const ByteBuffer&)> callback_tmp;
  1171. Function<ssize_t(InodeIdentifier, const ByteBuffer&)>* write_callback { nullptr };
  1172. if (directory_entry == nullptr) {
  1173. if (to_proc_parent_directory(identifier()) == PDI_Root_sys) {
  1174. switch (SysVariable::for_inode(identifier()).type) {
  1175. case SysVariable::Type::Invalid:
  1176. ASSERT_NOT_REACHED();
  1177. case SysVariable::Type::Boolean:
  1178. callback_tmp = write_sys_bool;
  1179. break;
  1180. case SysVariable::Type::String:
  1181. callback_tmp = write_sys_string;
  1182. break;
  1183. }
  1184. write_callback = &callback_tmp;
  1185. } else
  1186. return -EPERM;
  1187. } else {
  1188. if (!directory_entry->write_callback)
  1189. return -EPERM;
  1190. write_callback = &directory_entry->write_callback;
  1191. }
  1192. ASSERT(is_persistent_inode(identifier()));
  1193. // FIXME: Being able to write into ProcFS at a non-zero offset seems like something we should maybe support..
  1194. ASSERT(offset == 0);
  1195. bool success = (*write_callback)(identifier(), ByteBuffer::wrap(buffer, size));
  1196. ASSERT(success);
  1197. return 0;
  1198. }
  1199. KResult ProcFSInode::add_child(InodeIdentifier child_id, const StringView& name, mode_t)
  1200. {
  1201. (void)child_id;
  1202. (void)name;
  1203. return KResult(-EPERM);
  1204. }
  1205. KResult ProcFSInode::remove_child(const StringView& name)
  1206. {
  1207. (void)name;
  1208. return KResult(-EPERM);
  1209. }
  1210. size_t ProcFSInode::directory_entry_count() const
  1211. {
  1212. ASSERT(is_directory());
  1213. size_t count = 0;
  1214. traverse_as_directory([&count](const FS::DirectoryEntry&) {
  1215. ++count;
  1216. return true;
  1217. });
  1218. return count;
  1219. }
  1220. KResult ProcFSInode::chmod(mode_t)
  1221. {
  1222. return KResult(-EPERM);
  1223. }
  1224. ProcFS::ProcFS()
  1225. {
  1226. m_root_inode = adopt(*new ProcFSInode(*this, 1));
  1227. m_entries.resize(FI_MaxStaticFileIndex);
  1228. m_entries[FI_Root_mm] = { "mm", FI_Root_mm, procfs$mm };
  1229. m_entries[FI_Root_mounts] = { "mounts", FI_Root_mounts, procfs$mounts };
  1230. m_entries[FI_Root_df] = { "df", FI_Root_df, procfs$df };
  1231. m_entries[FI_Root_all] = { "all", FI_Root_all, procfs$all };
  1232. m_entries[FI_Root_memstat] = { "memstat", FI_Root_memstat, procfs$memstat };
  1233. m_entries[FI_Root_cpuinfo] = { "cpuinfo", FI_Root_cpuinfo, procfs$cpuinfo };
  1234. m_entries[FI_Root_inodes] = { "inodes", FI_Root_inodes, procfs$inodes };
  1235. m_entries[FI_Root_dmesg] = { "dmesg", FI_Root_dmesg, procfs$dmesg };
  1236. m_entries[FI_Root_self] = { "self", FI_Root_self, procfs$self };
  1237. m_entries[FI_Root_pci] = { "pci", FI_Root_pci, procfs$pci };
  1238. m_entries[FI_Root_devices] = { "devices", FI_Root_devices, procfs$devices };
  1239. m_entries[FI_Root_uptime] = { "uptime", FI_Root_uptime, procfs$uptime };
  1240. m_entries[FI_Root_cmdline] = { "cmdline", FI_Root_cmdline, procfs$cmdline };
  1241. m_entries[FI_Root_modules] = { "modules", FI_Root_modules, procfs$modules };
  1242. m_entries[FI_Root_profile] = { "profile", FI_Root_profile, procfs$profile };
  1243. m_entries[FI_Root_sys] = { "sys", FI_Root_sys };
  1244. m_entries[FI_Root_net] = { "net", FI_Root_net };
  1245. m_entries[FI_Root_net_adapters] = { "adapters", FI_Root_net_adapters, procfs$net_adapters };
  1246. m_entries[FI_Root_net_arp] = { "arp", FI_Root_net_arp, procfs$net_arp };
  1247. m_entries[FI_Root_net_tcp] = { "tcp", FI_Root_net_tcp, procfs$net_tcp };
  1248. m_entries[FI_Root_net_udp] = { "udp", FI_Root_net_udp, procfs$net_udp };
  1249. m_entries[FI_Root_net_local] = { "local", FI_Root_net_local, procfs$net_local };
  1250. m_entries[FI_PID_vm] = { "vm", FI_PID_vm, procfs$pid_vm };
  1251. m_entries[FI_PID_vmobjects] = { "vmobjects", FI_PID_vmobjects, procfs$pid_vmobjects };
  1252. m_entries[FI_PID_stack] = { "stack", FI_PID_stack, procfs$pid_stack };
  1253. m_entries[FI_PID_regs] = { "regs", FI_PID_regs, procfs$pid_regs };
  1254. m_entries[FI_PID_fds] = { "fds", FI_PID_fds, procfs$pid_fds };
  1255. m_entries[FI_PID_exe] = { "exe", FI_PID_exe, procfs$pid_exe };
  1256. m_entries[FI_PID_cwd] = { "cwd", FI_PID_cwd, procfs$pid_cwd };
  1257. m_entries[FI_PID_fd] = { "fd", FI_PID_fd };
  1258. }
  1259. ProcFS::ProcFSDirectoryEntry* ProcFS::get_directory_entry(InodeIdentifier identifier) const
  1260. {
  1261. auto proc_file_type = to_proc_file_type(identifier);
  1262. if (proc_file_type != FI_Invalid && proc_file_type != FI_Root_sys_variable && proc_file_type < FI_MaxStaticFileIndex)
  1263. return const_cast<ProcFSDirectoryEntry*>(&m_entries[proc_file_type]);
  1264. return nullptr;
  1265. }
  1266. KResult ProcFSInode::chown(uid_t, gid_t)
  1267. {
  1268. return KResult(-EPERM);
  1269. }