ProcFS.cpp 55 KB

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