ProcFS.cpp 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633
  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_regs,
  104. FI_PID_fds,
  105. FI_PID_unveil,
  106. FI_PID_exe, // symlink
  107. FI_PID_cwd, // symlink
  108. FI_PID_root, // symlink
  109. FI_PID_fd, // directory
  110. __FI_PID_End,
  111. FI_MaxStaticFileIndex,
  112. };
  113. static inline pid_t to_pid(const InodeIdentifier& identifier)
  114. {
  115. #ifdef PROCFS_DEBUG
  116. dbg() << "to_pid, index=" << String::format("%08x", identifier.index()) << " -> " << (identifier.index() >> 16);
  117. #endif
  118. return identifier.index() >> 16u;
  119. }
  120. static inline ProcParentDirectory to_proc_parent_directory(const InodeIdentifier& identifier)
  121. {
  122. return (ProcParentDirectory)((identifier.index() >> 12) & 0xf);
  123. }
  124. static inline ProcFileType to_proc_file_type(const InodeIdentifier& identifier)
  125. {
  126. return (ProcFileType)(identifier.index() & 0xff);
  127. }
  128. static inline int to_fd(const InodeIdentifier& identifier)
  129. {
  130. ASSERT(to_proc_parent_directory(identifier) == PDI_PID_fd);
  131. return (identifier.index() & 0xff) - FI_MaxStaticFileIndex;
  132. }
  133. static inline size_t to_sys_index(const InodeIdentifier& identifier)
  134. {
  135. ASSERT(to_proc_parent_directory(identifier) == PDI_Root_sys);
  136. ASSERT(to_proc_file_type(identifier) == FI_Root_sys_variable);
  137. return identifier.index() >> 16u;
  138. }
  139. static inline InodeIdentifier to_identifier(unsigned fsid, ProcParentDirectory parent, pid_t pid, ProcFileType proc_file_type)
  140. {
  141. return { fsid, ((unsigned)parent << 12u) | ((unsigned)pid << 16u) | (unsigned)proc_file_type };
  142. }
  143. static inline InodeIdentifier to_identifier_with_fd(unsigned fsid, pid_t pid, int fd)
  144. {
  145. return { fsid, (PDI_PID_fd << 12u) | ((unsigned)pid << 16u) | (FI_MaxStaticFileIndex + fd) };
  146. }
  147. static inline InodeIdentifier sys_var_to_identifier(unsigned fsid, unsigned index)
  148. {
  149. ASSERT(index < 256);
  150. return { fsid, (PDI_Root_sys << 12u) | (index << 16u) | FI_Root_sys_variable };
  151. }
  152. static inline InodeIdentifier to_parent_id(const InodeIdentifier& identifier)
  153. {
  154. switch (to_proc_parent_directory(identifier)) {
  155. case PDI_AbstractRoot:
  156. case PDI_Root:
  157. return { identifier.fsid(), FI_Root };
  158. case PDI_Root_sys:
  159. return { identifier.fsid(), FI_Root_sys };
  160. case PDI_Root_net:
  161. return { identifier.fsid(), FI_Root_net };
  162. case PDI_PID:
  163. return to_identifier(identifier.fsid(), PDI_Root, to_pid(identifier), FI_PID);
  164. case PDI_PID_fd:
  165. return to_identifier(identifier.fsid(), PDI_PID, to_pid(identifier), FI_PID_fd);
  166. }
  167. ASSERT_NOT_REACHED();
  168. }
  169. #if 0
  170. static inline u8 to_unused_metadata(const InodeIdentifier& identifier)
  171. {
  172. return (identifier.index() >> 8) & 0xf;
  173. }
  174. #endif
  175. static inline bool is_process_related_file(const InodeIdentifier& identifier)
  176. {
  177. if (to_proc_file_type(identifier) == FI_PID)
  178. return true;
  179. auto proc_parent_directory = to_proc_parent_directory(identifier);
  180. switch (proc_parent_directory) {
  181. case PDI_PID:
  182. case PDI_PID_fd:
  183. return true;
  184. default:
  185. return false;
  186. }
  187. }
  188. static inline bool is_directory(const InodeIdentifier& identifier)
  189. {
  190. auto proc_file_type = to_proc_file_type(identifier);
  191. switch (proc_file_type) {
  192. case FI_Root:
  193. case FI_Root_sys:
  194. case FI_Root_net:
  195. case FI_PID:
  196. case FI_PID_fd:
  197. return true;
  198. default:
  199. return false;
  200. }
  201. }
  202. static inline bool is_persistent_inode(const InodeIdentifier& identifier)
  203. {
  204. return to_proc_parent_directory(identifier) == PDI_Root_sys;
  205. }
  206. NonnullRefPtr<ProcFS> ProcFS::create()
  207. {
  208. return adopt(*new ProcFS);
  209. }
  210. ProcFS::~ProcFS()
  211. {
  212. }
  213. Optional<KBuffer> procfs$pid_fds(InodeIdentifier identifier)
  214. {
  215. KBufferBuilder builder;
  216. JsonArraySerializer array { builder };
  217. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  218. if (!handle) {
  219. array.finish();
  220. return builder.build();
  221. }
  222. auto& process = handle->process();
  223. if (process.number_of_open_file_descriptors() == 0) {
  224. array.finish();
  225. return builder.build();
  226. }
  227. for (int i = 0; i < process.max_open_file_descriptors(); ++i) {
  228. auto description = process.file_description(i);
  229. if (!description)
  230. continue;
  231. bool cloexec = process.fd_flags(i) & FD_CLOEXEC;
  232. auto description_object = array.add_object();
  233. description_object.add("fd", i);
  234. description_object.add("absolute_path", description->absolute_path());
  235. description_object.add("seekable", description->file().is_seekable());
  236. description_object.add("class", description->file().class_name());
  237. description_object.add("offset", description->offset());
  238. description_object.add("cloexec", cloexec);
  239. description_object.add("blocking", description->is_blocking());
  240. description_object.add("can_read", description->can_read());
  241. description_object.add("can_write", description->can_write());
  242. }
  243. array.finish();
  244. return builder.build();
  245. }
  246. Optional<KBuffer> procfs$pid_fd_entry(InodeIdentifier identifier)
  247. {
  248. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  249. if (!handle)
  250. return {};
  251. auto& process = handle->process();
  252. int fd = to_fd(identifier);
  253. auto description = process.file_description(fd);
  254. if (!description)
  255. return {};
  256. return description->absolute_path().to_byte_buffer();
  257. }
  258. Optional<KBuffer> procfs$pid_vm(InodeIdentifier identifier)
  259. {
  260. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier));
  261. if (!handle)
  262. return {};
  263. auto& process = handle->process();
  264. KBufferBuilder builder;
  265. JsonArraySerializer array { builder };
  266. for (auto& region : process.regions()) {
  267. if (!region.is_user_accessible() && !Process::current->is_superuser())
  268. continue;
  269. auto region_object = array.add_object();
  270. region_object.add("readable", region.is_readable());
  271. region_object.add("writable", region.is_writable());
  272. region_object.add("executable", region.is_executable());
  273. region_object.add("stack", region.is_stack());
  274. region_object.add("shared", region.is_shared());
  275. region_object.add("user_accessible", region.is_user_accessible());
  276. region_object.add("purgeable", region.vmobject().is_purgeable());
  277. if (region.vmobject().is_purgeable()) {
  278. region_object.add("volatile", static_cast<const PurgeableVMObject&>(region.vmobject()).is_volatile());
  279. }
  280. region_object.add("purgeable", region.vmobject().is_purgeable());
  281. region_object.add("address", region.vaddr().get());
  282. region_object.add("size", region.size());
  283. region_object.add("amount_resident", region.amount_resident());
  284. region_object.add("amount_dirty", region.amount_dirty());
  285. region_object.add("cow_pages", region.cow_pages());
  286. region_object.add("name", region.name());
  287. region_object.add("vmobject", region.vmobject().class_name());
  288. StringBuilder pagemap_builder;
  289. for (size_t i = 0; i < region.page_count(); ++i) {
  290. auto* page = region.physical_page(i);
  291. if (!page)
  292. pagemap_builder.append('N');
  293. else if (page->is_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([&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", (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", it.value->module_init);
  381. obj.add("module_fini", 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(), Lock::Mode::Shared);
  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() == nullptr)
  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", static_cast<u64>(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", "none");
  693. });
  694. array.finish();
  695. return builder.build();
  696. }
  697. Optional<KBuffer> procfs$cpuinfo(InodeIdentifier)
  698. {
  699. KBufferBuilder builder;
  700. bool first = true;
  701. Processor::for_each(
  702. [&](Processor& proc) -> IterationDecision
  703. {
  704. if (first)
  705. first = false;
  706. else
  707. builder.append('\n');
  708. auto& info = proc.info();
  709. builder.appendf("processor: %u\n", proc.id());
  710. builder.appendf("cpuid: %s\n", info.cpuid().characters());
  711. builder.appendf("family: %u\n", info.display_family());
  712. builder.appendf("model: %u\n", info.display_model());
  713. builder.appendf("stepping: %u\n", info.stepping());
  714. builder.appendf("type: %u\n", info.type());
  715. builder.appendf("brandstr: \"%s\"\n", info.brandstr().characters());
  716. return IterationDecision::Continue;
  717. });
  718. return builder.build();
  719. }
  720. Optional<KBuffer> procfs$memstat(InodeIdentifier)
  721. {
  722. InterruptDisabler disabler;
  723. KBufferBuilder builder;
  724. JsonObjectSerializer<KBufferBuilder> json { builder };
  725. json.add("kmalloc_allocated", g_kmalloc_bytes_allocated);
  726. json.add("kmalloc_available", g_kmalloc_bytes_free);
  727. json.add("kmalloc_eternal_allocated", g_kmalloc_bytes_eternal);
  728. json.add("user_physical_allocated", MM.user_physical_pages_used());
  729. json.add("user_physical_available", MM.user_physical_pages() - MM.user_physical_pages_used());
  730. json.add("super_physical_allocated", MM.super_physical_pages_used());
  731. json.add("super_physical_available", MM.super_physical_pages() - MM.super_physical_pages_used());
  732. json.add("kmalloc_call_count", g_kmalloc_call_count);
  733. json.add("kfree_call_count", g_kfree_call_count);
  734. slab_alloc_stats([&json](size_t slab_size, size_t num_allocated, size_t num_free) {
  735. auto prefix = String::format("slab_%zu", slab_size);
  736. json.add(String::format("%s_num_allocated", prefix.characters()), num_allocated);
  737. json.add(String::format("%s_num_free", prefix.characters()), num_free);
  738. });
  739. json.finish();
  740. return builder.build();
  741. }
  742. Optional<KBuffer> procfs$all(InodeIdentifier)
  743. {
  744. InterruptDisabler disabler;
  745. auto processes = Process::all_processes();
  746. KBufferBuilder builder;
  747. JsonArraySerializer array { builder };
  748. // Keep this in sync with CProcessStatistics.
  749. auto build_process = [&](const Process& process) {
  750. auto process_object = array.add_object();
  751. StringBuilder pledge_builder;
  752. #define __ENUMERATE_PLEDGE_PROMISE(promise) \
  753. if (process.has_promised(Pledge::promise)) { \
  754. pledge_builder.append(#promise " "); \
  755. }
  756. ENUMERATE_PLEDGE_PROMISES
  757. #undef __ENUMERATE_PLEDGE_PROMISE
  758. process_object.add("pledge", pledge_builder.to_string());
  759. switch (process.veil_state()) {
  760. case VeilState::None:
  761. process_object.add("veil", "None");
  762. break;
  763. case VeilState::Dropped:
  764. process_object.add("veil", "Dropped");
  765. break;
  766. case VeilState::Locked:
  767. process_object.add("veil", "Locked");
  768. break;
  769. }
  770. process_object.add("pid", process.pid());
  771. process_object.add("pgid", process.tty() ? process.tty()->pgid() : 0);
  772. process_object.add("pgp", process.pgid());
  773. process_object.add("sid", process.sid());
  774. process_object.add("uid", process.uid());
  775. process_object.add("gid", process.gid());
  776. process_object.add("ppid", process.ppid());
  777. process_object.add("nfds", process.number_of_open_file_descriptors());
  778. process_object.add("name", process.name());
  779. process_object.add("tty", process.tty() ? process.tty()->tty_name() : "notty");
  780. process_object.add("amount_virtual", process.amount_virtual());
  781. process_object.add("amount_resident", process.amount_resident());
  782. process_object.add("amount_dirty_private", process.amount_dirty_private());
  783. process_object.add("amount_clean_inode", process.amount_clean_inode());
  784. process_object.add("amount_shared", process.amount_shared());
  785. process_object.add("amount_purgeable_volatile", process.amount_purgeable_volatile());
  786. process_object.add("amount_purgeable_nonvolatile", process.amount_purgeable_nonvolatile());
  787. process_object.add("icon_id", process.icon_id());
  788. auto thread_array = process_object.add_array("threads");
  789. process.for_each_thread([&](const Thread& thread) {
  790. auto thread_object = thread_array.add_object();
  791. thread_object.add("tid", thread.tid());
  792. thread_object.add("name", thread.name());
  793. thread_object.add("times_scheduled", thread.times_scheduled());
  794. thread_object.add("ticks", thread.ticks());
  795. thread_object.add("state", thread.state_string());
  796. thread_object.add("priority", thread.priority());
  797. thread_object.add("effective_priority", thread.effective_priority());
  798. thread_object.add("syscall_count", thread.syscall_count());
  799. thread_object.add("inode_faults", thread.inode_faults());
  800. thread_object.add("zero_faults", thread.zero_faults());
  801. thread_object.add("cow_faults", thread.cow_faults());
  802. thread_object.add("file_read_bytes", thread.file_read_bytes());
  803. thread_object.add("file_write_bytes", thread.file_write_bytes());
  804. thread_object.add("unix_socket_read_bytes", thread.unix_socket_read_bytes());
  805. thread_object.add("unix_socket_write_bytes", thread.unix_socket_write_bytes());
  806. thread_object.add("ipv4_socket_read_bytes", thread.ipv4_socket_read_bytes());
  807. thread_object.add("ipv4_socket_write_bytes", thread.ipv4_socket_write_bytes());
  808. return IterationDecision::Continue;
  809. });
  810. };
  811. build_process(*Scheduler::colonel());
  812. for (auto* process : processes)
  813. build_process(*process);
  814. array.finish();
  815. return builder.build();
  816. }
  817. Optional<KBuffer> procfs$inodes(InodeIdentifier)
  818. {
  819. extern InlineLinkedList<Inode>& all_inodes();
  820. KBufferBuilder builder;
  821. InterruptDisabler disabler;
  822. for (auto& inode : all_inodes()) {
  823. builder.appendf("Inode{K%x} %02u:%08u (%u)\n", &inode, inode.fsid(), inode.index(), inode.ref_count());
  824. }
  825. return builder.build();
  826. }
  827. struct SysVariable {
  828. String name;
  829. enum class Type : u8 {
  830. Invalid,
  831. Boolean,
  832. String,
  833. };
  834. Type type { Type::Invalid };
  835. Function<void()> notify_callback;
  836. void* address { nullptr };
  837. static SysVariable& for_inode(InodeIdentifier);
  838. void notify()
  839. {
  840. if (notify_callback)
  841. notify_callback();
  842. }
  843. };
  844. static Vector<SysVariable, 16>* s_sys_variables;
  845. static inline Vector<SysVariable, 16>& sys_variables()
  846. {
  847. if (s_sys_variables == nullptr) {
  848. s_sys_variables = new Vector<SysVariable, 16>;
  849. s_sys_variables->append({ "", SysVariable::Type::Invalid, nullptr, nullptr });
  850. }
  851. return *s_sys_variables;
  852. }
  853. SysVariable& SysVariable::for_inode(InodeIdentifier id)
  854. {
  855. auto index = to_sys_index(id);
  856. if (index >= sys_variables().size())
  857. return sys_variables()[0];
  858. auto& variable = sys_variables()[index];
  859. ASSERT(variable.address);
  860. return variable;
  861. }
  862. static ByteBuffer read_sys_bool(InodeIdentifier inode_id)
  863. {
  864. auto& variable = SysVariable::for_inode(inode_id);
  865. ASSERT(variable.type == SysVariable::Type::Boolean);
  866. auto buffer = ByteBuffer::create_uninitialized(2);
  867. auto* lockable_bool = reinterpret_cast<Lockable<bool>*>(variable.address);
  868. {
  869. LOCKER(lockable_bool->lock(), Lock::Mode::Shared);
  870. buffer[0] = lockable_bool->resource() ? '1' : '0';
  871. }
  872. buffer[1] = '\n';
  873. return buffer;
  874. }
  875. static ssize_t write_sys_bool(InodeIdentifier inode_id, const ByteBuffer& data)
  876. {
  877. auto& variable = SysVariable::for_inode(inode_id);
  878. ASSERT(variable.type == SysVariable::Type::Boolean);
  879. if (data.is_empty() || !(data[0] == '0' || data[0] == '1'))
  880. return data.size();
  881. auto* lockable_bool = reinterpret_cast<Lockable<bool>*>(variable.address);
  882. {
  883. LOCKER(lockable_bool->lock());
  884. lockable_bool->resource() = data[0] == '1';
  885. }
  886. variable.notify();
  887. return data.size();
  888. }
  889. static ByteBuffer read_sys_string(InodeIdentifier inode_id)
  890. {
  891. auto& variable = SysVariable::for_inode(inode_id);
  892. ASSERT(variable.type == SysVariable::Type::String);
  893. auto* lockable_string = reinterpret_cast<Lockable<String>*>(variable.address);
  894. LOCKER(lockable_string->lock(), Lock::Mode::Shared);
  895. return lockable_string->resource().to_byte_buffer();
  896. }
  897. static ssize_t write_sys_string(InodeIdentifier inode_id, const ByteBuffer& data)
  898. {
  899. auto& variable = SysVariable::for_inode(inode_id);
  900. ASSERT(variable.type == SysVariable::Type::String);
  901. {
  902. auto* lockable_string = reinterpret_cast<Lockable<String>*>(variable.address);
  903. LOCKER(lockable_string->lock());
  904. lockable_string->resource() = String((const char*)data.data(), data.size());
  905. }
  906. variable.notify();
  907. return data.size();
  908. }
  909. void ProcFS::add_sys_bool(String&& name, Lockable<bool>& var, Function<void()>&& notify_callback)
  910. {
  911. InterruptDisabler disabler;
  912. SysVariable variable;
  913. variable.name = move(name);
  914. variable.type = SysVariable::Type::Boolean;
  915. variable.notify_callback = move(notify_callback);
  916. variable.address = &var;
  917. sys_variables().append(move(variable));
  918. }
  919. void ProcFS::add_sys_string(String&& name, Lockable<String>& var, Function<void()>&& notify_callback)
  920. {
  921. InterruptDisabler disabler;
  922. SysVariable variable;
  923. variable.name = move(name);
  924. variable.type = SysVariable::Type::String;
  925. variable.notify_callback = move(notify_callback);
  926. variable.address = &var;
  927. sys_variables().append(move(variable));
  928. }
  929. bool ProcFS::initialize()
  930. {
  931. static Lockable<bool>* kmalloc_stack_helper;
  932. if (kmalloc_stack_helper == nullptr) {
  933. kmalloc_stack_helper = new Lockable<bool>();
  934. kmalloc_stack_helper->resource() = g_dump_kmalloc_stacks;
  935. ProcFS::add_sys_bool("kmalloc_stacks", *kmalloc_stack_helper, [] {
  936. g_dump_kmalloc_stacks = kmalloc_stack_helper->resource();
  937. });
  938. }
  939. return true;
  940. }
  941. const char* ProcFS::class_name() const
  942. {
  943. return "ProcFS";
  944. }
  945. NonnullRefPtr<Inode> ProcFS::root_inode() const
  946. {
  947. return *m_root_inode;
  948. }
  949. RefPtr<Inode> ProcFS::get_inode(InodeIdentifier inode_id) const
  950. {
  951. #ifdef PROCFS_DEBUG
  952. dbg() << "ProcFS::get_inode(" << inode_id.index() << ")";
  953. #endif
  954. if (inode_id == root_inode()->identifier())
  955. return m_root_inode;
  956. LOCKER(m_inodes_lock);
  957. auto it = m_inodes.find(inode_id.index());
  958. if (it == m_inodes.end()) {
  959. auto inode = adopt(*new ProcFSInode(const_cast<ProcFS&>(*this), inode_id.index()));
  960. m_inodes.set(inode_id.index(), inode.ptr());
  961. return inode;
  962. }
  963. return (*it).value;
  964. }
  965. ProcFSInode::ProcFSInode(ProcFS& fs, unsigned index)
  966. : Inode(fs, index)
  967. {
  968. }
  969. ProcFSInode::~ProcFSInode()
  970. {
  971. LOCKER(fs().m_inodes_lock);
  972. fs().m_inodes.remove(index());
  973. }
  974. InodeMetadata ProcFSInode::metadata() const
  975. {
  976. #ifdef PROCFS_DEBUG
  977. dbg() << "ProcFSInode::metadata(" << index() << ")";
  978. #endif
  979. InodeMetadata metadata;
  980. metadata.inode = identifier();
  981. metadata.ctime = mepoch;
  982. metadata.atime = mepoch;
  983. metadata.mtime = mepoch;
  984. auto proc_parent_directory = to_proc_parent_directory(identifier());
  985. auto pid = to_pid(identifier());
  986. auto proc_file_type = to_proc_file_type(identifier());
  987. #ifdef PROCFS_DEBUG
  988. dbg() << " -> pid: " << pid << ", fi: " << proc_file_type << ", pdi: " << proc_parent_directory;
  989. #endif
  990. if (is_process_related_file(identifier())) {
  991. auto handle = ProcessInspectionHandle::from_pid(pid);
  992. metadata.uid = handle->process().sys$getuid();
  993. metadata.gid = handle->process().sys$getgid();
  994. }
  995. if (proc_parent_directory == PDI_PID_fd) {
  996. metadata.mode = S_IFLNK | S_IRUSR | S_IWUSR | S_IXUSR;
  997. return metadata;
  998. }
  999. switch (proc_file_type) {
  1000. case FI_Root_self:
  1001. metadata.mode = S_IFLNK | S_IRUSR | S_IRGRP | S_IROTH;
  1002. break;
  1003. case FI_PID_cwd:
  1004. case FI_PID_exe:
  1005. case FI_PID_root:
  1006. metadata.mode = S_IFLNK | S_IRUSR;
  1007. break;
  1008. case FI_Root:
  1009. case FI_Root_sys:
  1010. case FI_Root_net:
  1011. metadata.mode = S_IFDIR | S_IRUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
  1012. break;
  1013. case FI_PID:
  1014. case FI_PID_fd:
  1015. metadata.mode = S_IFDIR | S_IRUSR | S_IXUSR;
  1016. break;
  1017. default:
  1018. metadata.mode = S_IFREG | S_IRUSR | S_IRGRP | S_IROTH;
  1019. break;
  1020. }
  1021. if (proc_file_type > FI_Invalid && proc_file_type < FI_MaxStaticFileIndex) {
  1022. if (fs().m_entries[proc_file_type].supervisor_only) {
  1023. metadata.uid = 0;
  1024. metadata.gid = 0;
  1025. metadata.mode &= ~077;
  1026. }
  1027. }
  1028. #ifdef PROCFS_DEBUG
  1029. dbg() << "Returning mode " << String::format("%o", metadata.mode);
  1030. #endif
  1031. return metadata;
  1032. }
  1033. ssize_t ProcFSInode::read_bytes(off_t offset, ssize_t count, u8* buffer, FileDescription* description) const
  1034. {
  1035. #ifdef PROCFS_DEBUG
  1036. dbg() << "ProcFS: read_bytes " << index();
  1037. #endif
  1038. ASSERT(offset >= 0);
  1039. ASSERT(buffer);
  1040. auto* directory_entry = fs().get_directory_entry(identifier());
  1041. Function<Optional<KBuffer>(InodeIdentifier)> callback_tmp;
  1042. Function<Optional<KBuffer>(InodeIdentifier)>* read_callback { nullptr };
  1043. if (directory_entry)
  1044. read_callback = &directory_entry->read_callback;
  1045. else
  1046. switch (to_proc_parent_directory(identifier())) {
  1047. case PDI_PID_fd:
  1048. callback_tmp = procfs$pid_fd_entry;
  1049. read_callback = &callback_tmp;
  1050. break;
  1051. case PDI_Root_sys:
  1052. switch (SysVariable::for_inode(identifier()).type) {
  1053. case SysVariable::Type::Invalid:
  1054. ASSERT_NOT_REACHED();
  1055. case SysVariable::Type::Boolean:
  1056. callback_tmp = read_sys_bool;
  1057. break;
  1058. case SysVariable::Type::String:
  1059. callback_tmp = read_sys_string;
  1060. break;
  1061. }
  1062. read_callback = &callback_tmp;
  1063. break;
  1064. default:
  1065. ASSERT_NOT_REACHED();
  1066. }
  1067. ASSERT(read_callback);
  1068. Optional<KBuffer> generated_data;
  1069. if (!description) {
  1070. generated_data = (*read_callback)(identifier());
  1071. } else {
  1072. if (!description->generator_cache().has_value())
  1073. description->generator_cache() = (*read_callback)(identifier());
  1074. generated_data = description->generator_cache();
  1075. }
  1076. auto& data = generated_data;
  1077. if (!data.has_value())
  1078. return 0;
  1079. if ((size_t)offset >= data.value().size())
  1080. return 0;
  1081. ssize_t nread = min(static_cast<off_t>(data.value().size() - offset), static_cast<off_t>(count));
  1082. memcpy(buffer, data.value().data() + offset, nread);
  1083. if (nread == 0 && description && description->generator_cache().has_value())
  1084. description->generator_cache().clear();
  1085. return nread;
  1086. }
  1087. InodeIdentifier ProcFS::ProcFSDirectoryEntry::identifier(unsigned fsid) const
  1088. {
  1089. return to_identifier(fsid, PDI_Root, 0, (ProcFileType)proc_file_type);
  1090. }
  1091. KResult ProcFSInode::traverse_as_directory(Function<bool(const FS::DirectoryEntry&)> callback) const
  1092. {
  1093. #ifdef PROCFS_DEBUG
  1094. dbg() << "ProcFS: traverse_as_directory " << index();
  1095. #endif
  1096. if (!Kernel::is_directory(identifier()))
  1097. return KResult(-ENOTDIR);
  1098. auto pid = to_pid(identifier());
  1099. auto proc_file_type = to_proc_file_type(identifier());
  1100. auto parent_id = to_parent_id(identifier());
  1101. callback({ ".", 1, identifier(), 2 });
  1102. callback({ "..", 2, parent_id, 2 });
  1103. switch (proc_file_type) {
  1104. case FI_Root:
  1105. for (auto& entry : fs().m_entries) {
  1106. // FIXME: strlen() here is sad.
  1107. if (!entry.name)
  1108. continue;
  1109. if (entry.proc_file_type > __FI_Root_Start && entry.proc_file_type < __FI_Root_End)
  1110. callback({ entry.name, strlen(entry.name), to_identifier(fsid(), PDI_Root, 0, (ProcFileType)entry.proc_file_type), 0 });
  1111. }
  1112. for (auto pid_child : Process::all_pids()) {
  1113. char name[16];
  1114. size_t name_length = (size_t)sprintf(name, "%u", pid_child);
  1115. callback({ name, name_length, to_identifier(fsid(), PDI_Root, pid_child, FI_PID), 0 });
  1116. }
  1117. break;
  1118. case FI_Root_sys:
  1119. for (size_t i = 1; i < sys_variables().size(); ++i) {
  1120. auto& variable = sys_variables()[i];
  1121. callback({ variable.name.characters(), variable.name.length(), sys_var_to_identifier(fsid(), i), 0 });
  1122. }
  1123. break;
  1124. case FI_Root_net:
  1125. callback({ "adapters", 8, to_identifier(fsid(), PDI_Root_net, 0, FI_Root_net_adapters), 0 });
  1126. callback({ "arp", 3, to_identifier(fsid(), PDI_Root_net, 0, FI_Root_net_arp), 0 });
  1127. callback({ "tcp", 3, to_identifier(fsid(), PDI_Root_net, 0, FI_Root_net_tcp), 0 });
  1128. callback({ "udp", 3, to_identifier(fsid(), PDI_Root_net, 0, FI_Root_net_udp), 0 });
  1129. callback({ "local", 5, to_identifier(fsid(), PDI_Root_net, 0, FI_Root_net_local), 0 });
  1130. break;
  1131. case FI_PID: {
  1132. auto handle = ProcessInspectionHandle::from_pid(pid);
  1133. if (!handle)
  1134. return KResult(-ENOENT);
  1135. auto& process = handle->process();
  1136. for (auto& entry : fs().m_entries) {
  1137. if (entry.proc_file_type > __FI_PID_Start && entry.proc_file_type < __FI_PID_End) {
  1138. if (entry.proc_file_type == FI_PID_exe && !process.executable())
  1139. continue;
  1140. // FIXME: strlen() here is sad.
  1141. callback({ entry.name, strlen(entry.name), to_identifier(fsid(), PDI_PID, pid, (ProcFileType)entry.proc_file_type), 0 });
  1142. }
  1143. }
  1144. } break;
  1145. case FI_PID_fd: {
  1146. auto handle = ProcessInspectionHandle::from_pid(pid);
  1147. if (!handle)
  1148. return KResult(-ENOENT);
  1149. auto& process = handle->process();
  1150. for (int i = 0; i < process.max_open_file_descriptors(); ++i) {
  1151. auto description = process.file_description(i);
  1152. if (!description)
  1153. continue;
  1154. char name[16];
  1155. size_t name_length = (size_t)sprintf(name, "%u", i);
  1156. callback({ name, name_length, to_identifier_with_fd(fsid(), pid, i), 0 });
  1157. }
  1158. } break;
  1159. default:
  1160. return KSuccess;
  1161. }
  1162. return KSuccess;
  1163. }
  1164. RefPtr<Inode> ProcFSInode::lookup(StringView name)
  1165. {
  1166. ASSERT(is_directory());
  1167. if (name == ".")
  1168. return this;
  1169. if (name == "..")
  1170. return fs().get_inode(to_parent_id(identifier()));
  1171. auto proc_file_type = to_proc_file_type(identifier());
  1172. if (proc_file_type == FI_Root) {
  1173. for (auto& entry : fs().m_entries) {
  1174. if (entry.name == nullptr)
  1175. continue;
  1176. if (entry.proc_file_type > __FI_Root_Start && entry.proc_file_type < __FI_Root_End) {
  1177. if (name == entry.name) {
  1178. return fs().get_inode(to_identifier(fsid(), PDI_Root, 0, (ProcFileType)entry.proc_file_type));
  1179. }
  1180. }
  1181. }
  1182. auto name_as_number = name.to_uint();
  1183. if (!name_as_number.has_value())
  1184. return {};
  1185. bool process_exists = false;
  1186. {
  1187. InterruptDisabler disabler;
  1188. process_exists = Process::from_pid(name_as_number.value());
  1189. }
  1190. if (process_exists)
  1191. return fs().get_inode(to_identifier(fsid(), PDI_Root, name_as_number.value(), FI_PID));
  1192. return {};
  1193. }
  1194. if (proc_file_type == FI_Root_sys) {
  1195. for (size_t i = 1; i < sys_variables().size(); ++i) {
  1196. auto& variable = sys_variables()[i];
  1197. if (name == variable.name)
  1198. return fs().get_inode(sys_var_to_identifier(fsid(), i));
  1199. }
  1200. return {};
  1201. }
  1202. if (proc_file_type == FI_Root_net) {
  1203. if (name == "adapters")
  1204. return fs().get_inode(to_identifier(fsid(), PDI_Root, 0, FI_Root_net_adapters));
  1205. if (name == "arp")
  1206. return fs().get_inode(to_identifier(fsid(), PDI_Root, 0, FI_Root_net_arp));
  1207. if (name == "tcp")
  1208. return fs().get_inode(to_identifier(fsid(), PDI_Root, 0, FI_Root_net_tcp));
  1209. if (name == "udp")
  1210. return fs().get_inode(to_identifier(fsid(), PDI_Root, 0, FI_Root_net_udp));
  1211. if (name == "local")
  1212. return fs().get_inode(to_identifier(fsid(), PDI_Root, 0, FI_Root_net_local));
  1213. return {};
  1214. }
  1215. if (proc_file_type == FI_PID) {
  1216. auto handle = ProcessInspectionHandle::from_pid(to_pid(identifier()));
  1217. if (!handle)
  1218. return {};
  1219. auto& process = handle->process();
  1220. for (auto& entry : fs().m_entries) {
  1221. if (entry.proc_file_type > __FI_PID_Start && entry.proc_file_type < __FI_PID_End) {
  1222. if (entry.proc_file_type == FI_PID_exe && !process.executable())
  1223. continue;
  1224. if (entry.name == nullptr)
  1225. continue;
  1226. if (name == entry.name) {
  1227. return fs().get_inode(to_identifier(fsid(), PDI_PID, to_pid(identifier()), (ProcFileType)entry.proc_file_type));
  1228. }
  1229. }
  1230. }
  1231. return {};
  1232. }
  1233. if (proc_file_type == FI_PID_fd) {
  1234. auto name_as_number = name.to_uint();
  1235. if (!name_as_number.has_value())
  1236. return {};
  1237. bool fd_exists = false;
  1238. {
  1239. InterruptDisabler disabler;
  1240. if (auto* process = Process::from_pid(to_pid(identifier())))
  1241. fd_exists = process->file_description(name_as_number.value());
  1242. }
  1243. if (fd_exists)
  1244. return fs().get_inode(to_identifier_with_fd(fsid(), to_pid(identifier()), name_as_number.value()));
  1245. }
  1246. return {};
  1247. }
  1248. void ProcFSInode::flush_metadata()
  1249. {
  1250. }
  1251. ssize_t ProcFSInode::write_bytes(off_t offset, ssize_t size, const u8* buffer, FileDescription*)
  1252. {
  1253. auto result = prepare_to_write_data();
  1254. if (result.is_error())
  1255. return result;
  1256. auto* directory_entry = fs().get_directory_entry(identifier());
  1257. Function<ssize_t(InodeIdentifier, const ByteBuffer&)> callback_tmp;
  1258. Function<ssize_t(InodeIdentifier, const ByteBuffer&)>* write_callback { nullptr };
  1259. if (directory_entry == nullptr) {
  1260. if (to_proc_parent_directory(identifier()) == PDI_Root_sys) {
  1261. switch (SysVariable::for_inode(identifier()).type) {
  1262. case SysVariable::Type::Invalid:
  1263. ASSERT_NOT_REACHED();
  1264. case SysVariable::Type::Boolean:
  1265. callback_tmp = write_sys_bool;
  1266. break;
  1267. case SysVariable::Type::String:
  1268. callback_tmp = write_sys_string;
  1269. break;
  1270. }
  1271. write_callback = &callback_tmp;
  1272. } else
  1273. return -EPERM;
  1274. } else {
  1275. if (!directory_entry->write_callback)
  1276. return -EPERM;
  1277. write_callback = &directory_entry->write_callback;
  1278. }
  1279. ASSERT(is_persistent_inode(identifier()));
  1280. // FIXME: Being able to write into ProcFS at a non-zero offset seems like something we should maybe support..
  1281. ASSERT(offset == 0);
  1282. bool success = (*write_callback)(identifier(), ByteBuffer::wrap(buffer, size));
  1283. ASSERT(success);
  1284. return 0;
  1285. }
  1286. KResultOr<NonnullRefPtr<Custody>> ProcFSInode::resolve_as_link(Custody& base, RefPtr<Custody>* out_parent, int options, int symlink_recursion_level) const
  1287. {
  1288. if (!is_process_related_file(identifier()))
  1289. return Inode::resolve_as_link(base, out_parent, options, symlink_recursion_level);
  1290. // FIXME: We should return a custody for FI_PID or FI_PID_fd here
  1291. // for correctness. It's impossible to create files in ProcFS,
  1292. // so returning null shouldn't break much.
  1293. if (out_parent)
  1294. *out_parent = nullptr;
  1295. auto pid = to_pid(identifier());
  1296. auto proc_file_type = to_proc_file_type(identifier());
  1297. auto handle = ProcessInspectionHandle::from_pid(pid);
  1298. if (!handle)
  1299. return KResult(-ENOENT);
  1300. auto& process = handle->process();
  1301. if (to_proc_parent_directory(identifier()) == PDI_PID_fd) {
  1302. if (out_parent)
  1303. *out_parent = base;
  1304. int fd = to_fd(identifier());
  1305. auto description = process.file_description(fd);
  1306. if (!description)
  1307. return KResult(-ENOENT);
  1308. auto proxy_inode = ProcFSProxyInode::create(const_cast<ProcFS&>(fs()), *description);
  1309. return Custody::create(&base, "", proxy_inode, base.mount_flags());
  1310. }
  1311. Custody* res = nullptr;
  1312. switch (proc_file_type) {
  1313. case FI_PID_cwd:
  1314. res = &process.current_directory();
  1315. break;
  1316. case FI_PID_exe:
  1317. res = process.executable();
  1318. break;
  1319. case FI_PID_root:
  1320. // Note: we open root_directory() here, not
  1321. // root_directory_relative_to_global_root().
  1322. // This seems more useful.
  1323. res = &process.root_directory();
  1324. break;
  1325. default:
  1326. ASSERT_NOT_REACHED();
  1327. }
  1328. if (!res)
  1329. return KResult(-ENOENT);
  1330. return *res;
  1331. }
  1332. ProcFSProxyInode::ProcFSProxyInode(ProcFS& fs, FileDescription& fd)
  1333. : Inode(fs, 0)
  1334. , m_fd(fd)
  1335. {
  1336. }
  1337. ProcFSProxyInode::~ProcFSProxyInode()
  1338. {
  1339. }
  1340. InodeMetadata ProcFSProxyInode::metadata() const
  1341. {
  1342. InodeMetadata metadata = m_fd->metadata();
  1343. if (m_fd->is_readable())
  1344. metadata.mode |= 0444;
  1345. else
  1346. metadata.mode &= ~0444;
  1347. if (m_fd->is_writable())
  1348. metadata.mode |= 0222;
  1349. else
  1350. metadata.mode &= ~0222;
  1351. if (!metadata.is_directory())
  1352. metadata.mode &= ~0111;
  1353. return metadata;
  1354. }
  1355. KResultOr<NonnullRefPtr<Inode>> ProcFSProxyInode::create_child(const String& name, mode_t mode, dev_t dev, uid_t uid, gid_t gid)
  1356. {
  1357. if (!m_fd->inode())
  1358. return KResult(-EINVAL);
  1359. return m_fd->inode()->create_child(name, mode, dev, uid, gid);
  1360. }
  1361. KResult ProcFSProxyInode::add_child(Inode& child, const StringView& name, mode_t mode)
  1362. {
  1363. if (!m_fd->inode())
  1364. return KResult(-EINVAL);
  1365. return m_fd->inode()->add_child(child, name, mode);
  1366. }
  1367. KResult ProcFSProxyInode::remove_child(const StringView& name)
  1368. {
  1369. if (!m_fd->inode())
  1370. return KResult(-EINVAL);
  1371. return m_fd->inode()->remove_child(name);
  1372. }
  1373. RefPtr<Inode> ProcFSProxyInode::lookup(StringView name)
  1374. {
  1375. if (!m_fd->inode())
  1376. return {};
  1377. return m_fd->inode()->lookup(name);
  1378. }
  1379. size_t ProcFSProxyInode::directory_entry_count() const
  1380. {
  1381. if (!m_fd->inode())
  1382. return 0;
  1383. return m_fd->inode()->directory_entry_count();
  1384. }
  1385. KResultOr<NonnullRefPtr<Inode>> ProcFSInode::create_child(const String&, mode_t, dev_t, uid_t, gid_t)
  1386. {
  1387. return KResult(-EPERM);
  1388. }
  1389. KResult ProcFSInode::add_child(Inode&, const StringView&, mode_t)
  1390. {
  1391. return KResult(-EPERM);
  1392. }
  1393. KResult ProcFSInode::remove_child(const StringView& name)
  1394. {
  1395. (void)name;
  1396. return KResult(-EPERM);
  1397. }
  1398. size_t ProcFSInode::directory_entry_count() const
  1399. {
  1400. ASSERT(is_directory());
  1401. size_t count = 0;
  1402. traverse_as_directory([&count](const FS::DirectoryEntry&) {
  1403. ++count;
  1404. return true;
  1405. });
  1406. return count;
  1407. }
  1408. KResult ProcFSInode::chmod(mode_t)
  1409. {
  1410. return KResult(-EPERM);
  1411. }
  1412. ProcFS::ProcFS()
  1413. {
  1414. m_root_inode = adopt(*new ProcFSInode(*this, 1));
  1415. m_entries.resize(FI_MaxStaticFileIndex);
  1416. m_entries[FI_Root_mm] = { "mm", FI_Root_mm, true, procfs$mm };
  1417. m_entries[FI_Root_mounts] = { "mounts", FI_Root_mounts, false, procfs$mounts };
  1418. m_entries[FI_Root_df] = { "df", FI_Root_df, false, procfs$df };
  1419. m_entries[FI_Root_all] = { "all", FI_Root_all, false, procfs$all };
  1420. m_entries[FI_Root_memstat] = { "memstat", FI_Root_memstat, false, procfs$memstat };
  1421. m_entries[FI_Root_cpuinfo] = { "cpuinfo", FI_Root_cpuinfo, false, procfs$cpuinfo };
  1422. m_entries[FI_Root_inodes] = { "inodes", FI_Root_inodes, true, procfs$inodes };
  1423. m_entries[FI_Root_dmesg] = { "dmesg", FI_Root_dmesg, true, procfs$dmesg };
  1424. m_entries[FI_Root_self] = { "self", FI_Root_self, false, procfs$self };
  1425. m_entries[FI_Root_pci] = { "pci", FI_Root_pci, false, procfs$pci };
  1426. m_entries[FI_Root_interrupts] = { "interrupts", FI_Root_interrupts, false, procfs$interrupts };
  1427. m_entries[FI_Root_devices] = { "devices", FI_Root_devices, false, procfs$devices };
  1428. m_entries[FI_Root_uptime] = { "uptime", FI_Root_uptime, false, procfs$uptime };
  1429. m_entries[FI_Root_cmdline] = { "cmdline", FI_Root_cmdline, true, procfs$cmdline };
  1430. m_entries[FI_Root_modules] = { "modules", FI_Root_modules, true, procfs$modules };
  1431. m_entries[FI_Root_profile] = { "profile", FI_Root_profile, false, procfs$profile };
  1432. m_entries[FI_Root_sys] = { "sys", FI_Root_sys, true };
  1433. m_entries[FI_Root_net] = { "net", FI_Root_net, false };
  1434. m_entries[FI_Root_net_adapters] = { "adapters", FI_Root_net_adapters, false, procfs$net_adapters };
  1435. m_entries[FI_Root_net_arp] = { "arp", FI_Root_net_arp, true, procfs$net_arp };
  1436. m_entries[FI_Root_net_tcp] = { "tcp", FI_Root_net_tcp, false, procfs$net_tcp };
  1437. m_entries[FI_Root_net_udp] = { "udp", FI_Root_net_udp, false, procfs$net_udp };
  1438. m_entries[FI_Root_net_local] = { "local", FI_Root_net_local, false, procfs$net_local };
  1439. m_entries[FI_PID_vm] = { "vm", FI_PID_vm, false, procfs$pid_vm };
  1440. m_entries[FI_PID_vmobjects] = { "vmobjects", FI_PID_vmobjects, true, procfs$pid_vmobjects };
  1441. m_entries[FI_PID_stack] = { "stack", FI_PID_stack, false, procfs$pid_stack };
  1442. m_entries[FI_PID_regs] = { "regs", FI_PID_regs, true, procfs$pid_regs };
  1443. m_entries[FI_PID_fds] = { "fds", FI_PID_fds, false, procfs$pid_fds };
  1444. m_entries[FI_PID_exe] = { "exe", FI_PID_exe, false, procfs$pid_exe };
  1445. m_entries[FI_PID_cwd] = { "cwd", FI_PID_cwd, false, procfs$pid_cwd };
  1446. m_entries[FI_PID_unveil] = { "unveil", FI_PID_unveil, false, procfs$pid_unveil };
  1447. m_entries[FI_PID_root] = { "root", FI_PID_root, false, procfs$pid_root };
  1448. m_entries[FI_PID_fd] = { "fd", FI_PID_fd, false };
  1449. }
  1450. ProcFS::ProcFSDirectoryEntry* ProcFS::get_directory_entry(InodeIdentifier identifier) const
  1451. {
  1452. auto proc_file_type = to_proc_file_type(identifier);
  1453. if (proc_file_type != FI_Invalid && proc_file_type != FI_Root_sys_variable && proc_file_type < FI_MaxStaticFileIndex)
  1454. return const_cast<ProcFSDirectoryEntry*>(&m_entries[proc_file_type]);
  1455. return nullptr;
  1456. }
  1457. KResult ProcFSInode::chown(uid_t, gid_t)
  1458. {
  1459. return KResult(-EPERM);
  1460. }
  1461. }