ProcFS.cpp 56 KB

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