ProcFS.cpp 55 KB

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