ProcFS.cpp 57 KB

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