ProcFS.cpp 57 KB

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