ProcFS.cpp 55 KB

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