ProcFS.cpp 56 KB

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