ProcFS.cpp 57 KB

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