ProcFS.cpp 57 KB

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