ProcFS.cpp 55 KB

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