ProcFS.cpp 55 KB

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